From fcaa7c713d6e5eb3ce92f5023dd82109684513db Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 07:21:54 +0000 Subject: [PATCH 01/18] feat(rstack): resolve review wiring from authored service projects Signed-off-by: Jeremi Joslin --- .github/workflows/ci.yml | 2 +- Cargo.lock | 1 + crates/registry-platform-config/Cargo.toml | 2 + crates/registry-platform-config/README.md | 7 + crates/registry-platform-config/src/lib.rs | 3 + .../src/service_authoring.rs | 1107 +++++++++++++ .../src/service_compiler.rs | 256 ++- .../src/service_compiler/tests.rs | 112 +- crates/registry-rstack-dev/Cargo.toml | 2 +- crates/registry-rstack-dev/src/bindings.rs | 42 +- crates/registry-rstack-dev/src/explain.rs | 68 +- crates/registry-rstack-dev/src/journey.rs | 1 + crates/registry-rstack-dev/src/lib.rs | 25 +- crates/registry-rstack-dev/src/plan.rs | 136 +- crates/registry-rstack-dev/src/products.rs | 1068 ++++++++++++- crates/registry-rstack-dev/src/roles.rs | 3 + .../src/roles/token_shapes.rs | 1 + crates/registry-rstack-service/Cargo.toml | 2 +- crates/registry-rstack-service/src/lib.rs | 3 + crates/registry-rstack/Cargo.toml | 1 + crates/registry-rstack/src/cli.rs | 101 +- crates/registry-rstack/tests/dev_run.rs | 577 ++++++- .../tests/fixtures/service_review/mod.rs | 595 +++++++ crates/registry-rstack/tests/service_plan.rs | 1366 ++++++++++++++++- deploy/README.md | 1 + deploy/helm/registry-stack/README.md | 1 + .../run-a-project-with-rstack-dev.mdx | 66 +- .../identifiers/generated/catalog.v1.json | 4 +- products/platform/CHANGELOG.md | 6 + .../generated/dev/dev.v1alpha1.schema.json | 11 +- products/platform/scripts/test-rstack-dev.py | 46 +- 31 files changed, 5447 insertions(+), 169 deletions(-) create mode 100644 crates/registry-platform-config/src/service_authoring.rs create mode 100644 crates/registry-rstack/tests/fixtures/service_review/mod.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 770d848411..f090abbbd9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1952,7 +1952,7 @@ jobs: needs: changes if: needs.changes.outputs.breg_contracts == 'true' runs-on: ubuntu-24.04 - timeout-minutes: 30 + timeout-minutes: ${{ matrix.lane == 'contracts-journeys' && 40 || 30 }} strategy: fail-fast: false matrix: diff --git a/Cargo.lock b/Cargo.lock index 6b663a50d6..ef189615db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8390,6 +8390,7 @@ dependencies = [ "serde_json", "serde_norway", "sha2 0.11.1", + "signal-hook 0.4.6", "tempfile", "ureq", ] diff --git a/crates/registry-platform-config/Cargo.toml b/crates/registry-platform-config/Cargo.toml index 91cb2cf178..56923388ca 100644 --- a/crates/registry-platform-config/Cargo.toml +++ b/crates/registry-platform-config/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [features] test-support = [] schema = ["dep:schemars", "registry-platform-yaml/schema"] +service-authoring = ["dep:tempfile"] [dependencies] registry-platform-canonical-json = { workspace = true } @@ -25,6 +26,7 @@ serde.workspace = true serde_json.workspace = true serde_norway.workspace = true sha2.workspace = true +tempfile = { workspace = true, optional = true } thiserror.workspace = true tracing.workspace = true url.workspace = true diff --git a/crates/registry-platform-config/README.md b/crates/registry-platform-config/README.md index d7bdb252a5..a998e19635 100644 --- a/crates/registry-platform-config/README.md +++ b/crates/registry-platform-config/README.md @@ -37,6 +37,13 @@ refuses a file holding a PEM private key block (`SecretError::PrivateKeyInPublicDocument`). `inspect_public_document` checks one without reading it. +## Service authoring + +`service_compiler` projects authored service inventory into development plans. +The opt-in `service-authoring` feature exposes `service_authoring`, which +inspects the owning products' offline compiler reports to resolve review +wiring. The CLI selects the local authoring executables. + ## Loader `RuntimeConfigLoader` reads one runtime configuration file named by an diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index 4ad9dd89e7..0bddad8a45 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -24,6 +24,9 @@ mod posture_load_tests; #[cfg(feature = "schema")] pub mod schema; mod secrets; +// Keep the child-process tests in the platform's default unit-test run. +#[cfg(any(feature = "service-authoring", test))] +pub mod service_authoring; pub mod service_compiler; pub mod service_roles; diff --git a/crates/registry-platform-config/src/service_authoring.rs b/crates/registry-platform-config/src/service_authoring.rs new file mode 100644 index 0000000000..ab2fbb7f12 --- /dev/null +++ b/crates/registry-platform-config/src/service_authoring.rs @@ -0,0 +1,1107 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Resolve a native review pair from the products' offline compiler reports. + +use crate::service_compiler::{Product, ReviewContextContract, ReviewWiring}; +use crate::sha256_uri; +use registry_platform_canonical_json::{ + canonicalize_json, parse_json_preserving_integers, parse_json_strict, +}; +use registry_platform_yaml::{ + Diagnostic, Digest, Document, ExternalId, LocalId, Reader, Report, Severity, Url, + MAXIMUM_DOCUMENT_BYTES, +}; +use rustix::{ + fs::{fcntl_getfl, fcntl_setfl, open, openat, statat, AtFlags, FileType, Mode, OFlags}, + io::Errno, + process::{kill_process_group, waitid, Pid, Signal, WaitId, WaitIdOptions}, +}; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::ffi::OsStr; +use std::fs::File; +use std::io::{self, ErrorKind, Read}; +use std::os::fd::OwnedFd; +use std::os::unix::process::CommandExt; +use std::path::{Component, Path}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread; +use std::time::{Duration, Instant}; + +const BREG_CTL_REPORT: &str = "id.registrystack.org/formats/breg/ctl-report/v1alpha1"; +const BREG_ACTIONS: &str = "id.registrystack.org/formats/breg/actions-explanation/v1"; +const CASEWORK_CTL_REPORT: &str = "id.registrystack.org/formats/casework/report/v1"; +const REVIEW_PROTOCOL: &str = "id.registrystack.org/protocols/review/v1"; +const REVIEW_INDEX: &str = "generated/review-context-schemas/index.json"; +const SCHEMA_REVISION: &str = "x-registry-definition-revision"; +const PAIR_INPUT_LIMIT: u64 = 1024 * 1024; +const NOFOLLOW_DIR_FLAGS: OFlags = OFlags::RDONLY + .union(OFlags::DIRECTORY) + .union(OFlags::NOFOLLOW) + .union(OFlags::CLOEXEC); +const REPORT_LIMIT: u64 = 16 * 1024 * 1024; +const TOOL_TIMEOUT: Duration = Duration::from_secs(30); +const TOOL_POLL: Duration = Duration::from_millis(10); +const TOOL_UNAVAILABLE: &str = "rstack.service.review-tool-unavailable"; +const TOOL_FAILED: &str = "rstack.service.review-inspection"; +const TOOL_INTERRUPTED: &str = "rstack.service.review-interrupted"; + +pub enum ReviewToolFailure { + Unavailable, + Refused, + Failed, + Interrupted, +} + +pub struct ReviewToolOutput { + exit: Option, + report: Value, +} + +pub fn review_tool_failure(report: &Report) -> Option<&Diagnostic> { + report.diagnostics().iter().find(|item| { + matches!( + item.code.as_str(), + TOOL_UNAVAILABLE | TOOL_FAILED | TOOL_INTERRUPTED + ) + }) +} + +/// Run a selected local authoring tool without collecting its stderr or +/// exposing its report. Tools are never selected by project content. +pub fn run_review_tool( + tool: &Path, + args: &[&OsStr], + terminate: &AtomicBool, +) -> Result { + run_review_tool_with_timeout(tool, args, TOOL_TIMEOUT, terminate) +} + +fn run_review_tool_with_timeout( + tool: &Path, + args: &[&OsStr], + timeout: Duration, + terminate: &AtomicBool, +) -> Result { + if terminate.load(Ordering::Relaxed) { + return Err(ReviewToolFailure::Interrupted); + } + let mut child = Command::new(tool) + .args(["--format", "json"]) + .args(args) + .env_remove("RSTACK_DEV_DATABASE_URL") + .process_group(0) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|error| match error.kind() { + ErrorKind::NotFound => ReviewToolFailure::Unavailable, + _ => ReviewToolFailure::Failed, + })?; + let captured = collect_review_stdout(&mut child, Instant::now() + timeout, terminate); + let status = reap_review_tool(&mut child).map_err(|_| ReviewToolFailure::Failed)?; + if terminate.load(Ordering::Relaxed) { + return Err(ReviewToolFailure::Interrupted); + } + let bytes = captured.map_err(|_| ReviewToolFailure::Failed)?; + let report = parse_json_preserving_integers(&bytes).map_err(|_| ReviewToolFailure::Failed)?; + Ok(ReviewToolOutput { + exit: status.code(), + report, + }) +} + +fn collect_review_stdout( + child: &mut Child, + deadline: Instant, + terminate: &AtomicBool, +) -> io::Result> { + let stdout = child.stdout.take().expect("piped authoring report"); + fcntl_setfl(&stdout, fcntl_getfl(&stdout)? | OFlags::NONBLOCK)?; + let mut stdout = Some(stdout); + let mut bytes = Vec::new(); + let mut chunk = [0; 8192]; + let pid = Pid::from_child(child); + while Instant::now() < deadline { + if terminate.load(Ordering::Relaxed) { + return Err(ErrorKind::Interrupted.into()); + } + if let Some(pipe) = &mut stdout { + match pipe.read(&mut chunk) { + Ok(0) => stdout = None, + Ok(count) => { + if (bytes.len() + count) as u64 > REPORT_LIMIT { + return Err(ErrorKind::InvalidData.into()); + } + bytes.extend_from_slice(&chunk[..count]); + continue; + } + Err(error) if error.kind() == ErrorKind::Interrupted => continue, + Err(error) if error.kind() == ErrorKind::WouldBlock => {} + Err(error) => return Err(error), + } + } else if review_tool_exited(pid)? { + return Ok(bytes); + } + thread::sleep(TOOL_POLL); + } + Err(ErrorKind::TimedOut.into()) +} + +fn review_tool_exited(pid: Pid) -> io::Result { + let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT; + loop { + match waitid(WaitId::Pid(pid), options) { + Ok(status) => return Ok(status.is_some()), + Err(rustix::io::Errno::INTR) => continue, + Err(error) => return Err(error.into()), + } + } +} + +fn reap_review_tool(child: &mut Child) -> io::Result { + // Reserve the leader's PID until the group is signaled, even if the + // leader already exited and another member still holds stdout open. + let pid = Pid::from_child(child); + match kill_process_group(pid, Signal::KILL) { + Ok(()) | Err(rustix::io::Errno::SRCH) => child.wait(), + // Darwin can return EPERM for the group of an exited leader when + // the group has no signalable members. + Err(rustix::io::Errno::PERM) + if cfg!(target_os = "macos") && matches!(review_tool_exited(pid), Ok(true)) => + { + child.wait() + } + Err(error) => { + child.kill()?; + child.wait()?; + Err(error.into()) + } + } +} + +/// Read compiler metadata only when the service includes Casework and an +/// authored BReg review authority. Resolve only selections of policies this +/// Casework project declares, and require exclusive use of the runtime bindings +/// the pair would occupy. The caller selects each executable. +pub fn inspect_review( + service: &Document, + products: &[Product], + run: impl Fn(&str, &[&OsStr]) -> Result, +) -> Result, Report> { + let Some(casework) = products + .iter() + .find(|product| product.product == "casework") + else { + return Ok(None); + }; + let mut wiring = None; + let mut casework_facts = None; + for breg in products.iter().filter(|product| product.product == "breg") { + if !has_review_authority(service, breg)? { + continue; + } + let breg_facts = breg_explanation(&run, breg) + .map_err(|failure| inspection_error(service, breg, failure))?; + let facts = &breg_facts.explanation; + let actions = facts + .actions + .iter() + .filter_map(|action| { + let Execution::Proposal { proposal } = &action.execution else { + return None; + }; + let Review::Required { + authority, + source, + policy, + } = &proposal.review + else { + return None; + }; + facts + .review_authorities + .iter() + .any(|entry| &entry.id == authority && entry.protocol == REVIEW_PROTOCOL) + .then_some((&action.id, authority, source, policy, proposal)) + }) + .collect::>(); + if actions.is_empty() { + continue; + } + if casework_facts.is_none() { + casework_facts = Some( + casework_explanation(&run, casework) + .map_err(|failure| inspection_error(service, casework, failure))?, + ); + } + let cases = casework_facts + .as_ref() + .expect("the Casework project was inspected"); + let mut contracts = None; + for &(action, authority, source, selection, proposal) in &actions { + let Some(policy_id) = cases + .review_policies + .iter() + .map(|policy| &policy.binding.id) + .find(|id| id.as_str() == selection.id.as_str()) + else { + continue; + }; + let Some((policy, provider, contract, strict_policy_producers)) = + casework_pair(cases, source, policy_id, selection) + else { + return Err(problem( + service, "rstack.service.review-unresolved", casework.source_pointer(), + "The BReg review selection has no matching Casework approval policy and current-source provider for its source namespace.", + "Align the BReg Action's policy selection and source with the Casework policy and its context provider.", + )); + }; + // Native pairing requires the BReg tool build to match Casework's. + if breg_facts.version != cases.version { + return Err(inspection_error(service, breg, ReviewToolFailure::Failed)); + } + // The local runner supplies one status-reader identity. Human + // display uses the caller's own source credential. + if provider.capabilities.iter().any(|capability| { + !matches!(capability.as_str(), "human-display" | "service-status") + }) { + return Err(problem( + service, "rstack.service.review-provider-capability", casework.source_pointer(), + "Automatic local review wiring supports only human-display and service-status and supplies one status-reader identity.", + "Use a provider limited to those capabilities for the local pair, or configure the provider and its separate credentials outside automatic wiring.", + )); + } + if actions.iter().any(|&(other_action, other_authority, ..)| { + other_action != action && other_authority == authority + }) { + return Err(problem( + service, "rstack.service.review-authority-shared", breg.source_pointer(), + "The review authority selected for the local pair is also used by another reviewed BReg Action. Both Actions would use the same runtime binding.", + "Give the other reviewed Actions a different review authority in the BReg project.", + )); + } + if cases.context_providers.iter().any(|other| { + other.id != provider.id && other.deployment_ref == provider.deployment_ref + }) { + return Err(problem( + service, "rstack.service.review-deployment-ref-shared", casework.source_pointer(), + "The Casework context provider selected for the local pair shares its deploymentRef with another provider. Both providers would use the same runtime binding.", + "Give providers that share this runtime binding distinct deploymentRef values in the Casework project.", + )); + } + let context_id = proposal.review_context.as_ref().map(|context| &context.id); + if context_id.is_some() && contracts.is_none() { + contracts = Some( + breg_contracts(&run, breg, &breg_facts.revision, &cases.version) + .map_err(|failure| inspection_error(service, breg, failure))?, + ); + } + let native = match (&contracts, context_id) { + (Some(contracts), Some(context_id)) => contracts + .verified_contract(action, source, context_id) + .map_err(|failure| inspection_error(service, breg, failure))?, + _ => None, + }; + if !native.is_some_and(|native| native.matches(contract)) + || cases.review_policies.iter().any(|other| { + matches!(&other.context, Context::CurrentSource { provider: id, contract: pin } + if id == &provider.id && pin != contract) + }) + { + return Err(problem( + service, "rstack.service.review-contract", casework.source_pointer(), + "The Casework policies for this provider must all pin the exact native BReg Action export.", + "Pair the Casework provider against this BReg package and Action, and use the export's exact contract ID, revision, and schema digest in each policy.", + )); + } + if wiring.is_some() { + return Err(problem( + service, "rstack.service.review-ambiguous", "/products", + "The service has multiple authored BReg and Casework review pairs. The development runner has one authority and one context-provider credential slot.", + "Use a separate service for each review pair.", + )); + } + if policy.stages.iter().any(|stage| stage.exclude_initiator) + && !proposal.permissions.iter().any(|permission| { + matches!(permission.actor_kind, None | Some(ActorKind::Human)) + && permission + .operations + .iter() + .any(|operation| operation == "submit") + }) + { + return Err(problem( + service, "rstack.service.review-human-submit-required", breg.source_pointer(), + "A stage of the selected Casework policy excludes the initiator, but the BReg Action has no Proposal Submit permission that can admit a human.", + "Select a policy without initiator exclusion or configure the intended human Submit permission for the BReg Action.", + )); + } + let pair = ReviewWiring { + breg_project: breg.id.clone(), + casework_project: casework.id.clone(), + authority: authority.clone(), + action: action.clone(), + policy: policy_id.clone(), + context_provider: provider.id.clone(), + source_namespace: source.clone(), + context_contract: contract.clone(), + deployment_ref: provider.deployment_ref.clone(), + admitted_producer_issuers: cases + .trusted_producers + .iter() + .filter(|producer| { + producer.source_namespaces.contains(source) + && producer.review_policies.contains(policy_id) + }) + .map(|producer| (producer.id.clone(), producer.issuer.clone())) + .collect(), + strict_policy_producers: strict_policy_producers + .iter() + .map(|producer| producer.id.clone()) + .collect(), + }; + wiring = Some((pair, provider.description.clone())); + } + } + let Some((pair, declared_description)) = wiring else { + return Ok(None); + }; + if LocalId::new(pair.deployment_ref.as_str()).is_err() { + return Err(problem( + service, "rstack.service.review-deployment-ref-invalid", casework.source_pointer(), + "The selected Casework provider's deploymentRef must be a local identifier to serve as a runtime contextProviders key.", + "Set deploymentRef to a local identifier of at most 64 characters, starting with a lowercase ASCII letter and using lowercase ASCII letters, digits, hyphens, or underscores.", + )); + } + let cases = casework_facts.expect("the Casework project was inspected"); + let mut retained = cases + .context_providers + .iter() + .filter(|provider| provider.id != pair.context_provider); + // The owner reads descriptions by path components, which absorb interior + // dots and repeated separators. The runner copies only files and directories. + let default_description = format!("context-providers/{}.json", pair.context_provider); + let description = declared_description + .as_deref() + .unwrap_or(&default_description); + let destination = Path::new(description); + if retained.clone().any(|provider| { + provider + .description + .as_deref() + .is_some_and(|path| Path::new(path) == destination) + }) { + return Err(problem( + service, "rstack.service.review-provider-description-shared", casework.source_pointer(), + "Native pairing would write to a description file already used by another Casework context provider.", + "Copy the description to a separate file and update the retained providers that use it in the Casework project.", + )); + } + if !usable_pair_description( + &casework.project, + description, + declared_description.is_some(), + ) { + return Err(problem( + service, "rstack.service.review-provider-description", casework.source_pointer(), + "The selected Casework provider description cannot be written in the development copy.", + "Leave the native default destination unused. For an authored description use a file path below context-providers/ without double dots. An existing destination must be a regular file, and existing parents must be directories. Remove any symlinks along that path.", + )); + } + // Pairing supplies only the selected description. Casework's production + // package check requires one for every provider in the project. + if retained.any(|provider| provider.description.is_none()) { + return Err(problem( + service, "rstack.service.review-retained-provider-unpaired", casework.source_pointer(), + "A retained Casework context provider has no paired description required by the production package check.", + "Run caseworkctl provider pair for the remaining providers before planning this local pair.", + )); + } + Ok(Some(pair)) +} + +fn usable_pair_description(project: &Path, relative: &str, description_is_declared: bool) -> bool { + // Native pairing writes below context-providers. A trailing slash or dot + // makes the OS require a directory even though Path::components strips it. + if !relative.starts_with("context-providers/") + || relative.contains("..") + || relative.contains('\0') + || relative.ends_with('/') + || relative.ends_with("/.") + { + return false; + } + let mut components = Path::new(relative).components(); + let Some(Component::Normal(filename)) = components.next_back() else { + return false; + }; + let Ok(mut directory) = open(project, NOFOLLOW_DIR_FLAGS, Mode::empty()) else { + return false; + }; + // The runner copies only files and directories. Inspect the selected path + // without following links and let native pairing create missing parents. + for component in components { + let Component::Normal(name) = component else { + return false; + }; + match openat(&directory, name, NOFOLLOW_DIR_FLAGS, Mode::empty()) { + Ok(child) => directory = child, + Err(Errno::NOENT) => return true, + Err(_) => return false, + } + } + match statat(&directory, filename, AtFlags::SYMLINK_NOFOLLOW) { + // Pairing can replace the selected provider's declared description. + // An existing file at an implicit destination could be a project input. + Ok(metadata) => { + description_is_declared + && FileType::from_raw_mode(metadata.st_mode) == FileType::RegularFile + } + Err(Errno::NOENT) => true, + Err(_) => false, + } +} + +fn has_review_authority(service: &Document, product: &Product) -> Result { + let file = product.project.join("registry.yaml"); + let bytes = file + .canonicalize() + .ok() + .filter(|path| path.starts_with(&product.project)) + .and_then(|path| read(&path, MAXIMUM_DOCUMENT_BYTES as u64)); + let reader = Reader::new(file.display().to_string()); + match bytes { + Some(bytes) => Ok(reader + .scan(&bytes)? + .is_some_and(|node| node.pointer("/reviewAuthorities").is_some())), + None => Err(problem( + service, + "rstack.service.review-source-unreadable", + product.source_pointer(), + "The BReg project file could not be read within the project and document limits.", + "Check the registry.yaml path and size.", + )), + } +} + +fn breg_explanation( + run: &impl Fn(&str, &[&OsStr]) -> Result, + product: &Product, +) -> Result { + let report = owner_report( + run, + product, + &[ + "explain".as_ref(), + "actions".as_ref(), + product.project.as_os_str(), + ], + )?; + if report["explanation"]["apiVersion"] != BREG_ACTIONS + || report["explanation"]["kind"] != "BRegActionsExplanation" + { + return Err(ReviewToolFailure::Failed); + } + serde_json::from_value(report).map_err(|_| ReviewToolFailure::Failed) +} + +fn breg_contracts( + run: &impl Fn(&str, &[&OsStr]) -> Result, + product: &Product, + revision: &Digest, + version: &str, +) -> Result { + let scratch = tempfile::tempdir().map_err(|_| ReviewToolFailure::Failed)?; + let scratch_root = File::open(scratch.path()).map_err(|_| ReviewToolFailure::Failed)?; + let output = scratch.path().join("schemas"); + let report = owner_report( + run, + product, + &[ + "generate".as_ref(), + "schemas".as_ref(), + product.project.as_os_str(), + "--output".as_ref(), + output.as_os_str(), + ], + )?; + if report["revision"] != revision.as_str() || report["version"] != version { + return Err(ReviewToolFailure::Failed); + } + let root = openat(&scratch_root, "schemas", NOFOLLOW_DIR_FLAGS, Mode::empty()) + .map_err(|_| ReviewToolFailure::Failed)?; + let bytes = read_generated(&root, REVIEW_INDEX)?; + let contracts = + parse_json_preserving_integers(&bytes).map_err(|_| ReviewToolFailure::Failed)?; + let contracts = serde_json::from_value(contracts).map_err(|_| ReviewToolFailure::Failed)?; + Ok(GeneratedContracts { + contracts, + root, + _scratch: scratch, + }) +} + +fn read_generated(root: &OwnedFd, relative: &str) -> Result, ReviewToolFailure> { + let mut components = Path::new(relative).components(); + let Some(Component::Normal(filename)) = components.next_back() else { + return Err(ReviewToolFailure::Failed); + }; + // Resolve each member under the opened output directory and reject + // symlinks in every component of the generated tree. + let mut parent = None; + for component in components { + let Component::Normal(name) = component else { + return Err(ReviewToolFailure::Failed); + }; + let directory = openat( + parent.as_ref().unwrap_or(root), + name, + NOFOLLOW_DIR_FLAGS, + Mode::empty(), + ) + .map_err(|_| ReviewToolFailure::Failed)?; + parent = Some(directory); + } + let file = openat( + parent.as_ref().unwrap_or(root), + filename, + OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, + Mode::empty(), + ) + .map(File::from) + .map_err(|_| ReviewToolFailure::Failed)?; + if !file + .metadata() + .map_err(|_| ReviewToolFailure::Failed)? + .is_file() + { + return Err(ReviewToolFailure::Failed); + } + read_bounded(file, PAIR_INPUT_LIMIT).ok_or(ReviewToolFailure::Failed) +} + +fn casework_explanation( + run: &impl Fn(&str, &[&OsStr]) -> Result, + product: &Product, +) -> Result { + let report = owner_report( + run, + product, + &["explain".as_ref(), product.project.as_os_str()], + )?; + serde_json::from_value(report).map_err(|_| ReviewToolFailure::Failed) +} + +fn casework_pair<'a>( + explanation: &'a CaseworkExplanation, + source: &ExternalId, + policy_id: &LocalId, + selection: &PolicySelection, +) -> Option<( + &'a CaseworkPolicy, + &'a ContextProvider, + &'a ReviewContextContract, + &'a [Producer], +)> { + let policy = exactly_one( + explanation + .review_policies + .iter() + .filter(|policy| &policy.binding.id == policy_id && policy.purpose == "approval"), + )?; + let strict_policy_producers: &[_] = match (&selection.version, &selection.digest) { + (None, None) => &[], + (Some(version), Some(digest)) + if version == &policy.binding.version && digest == &policy.binding.digest => + { + policy.dependencies.trusted_producers.as_slice() + } + _ => return None, + }; + let Context::CurrentSource { provider, contract } = &policy.context else { + return None; + }; + let provider = exactly_one( + explanation + .context_providers + .iter() + .filter(|entry| &entry.id == provider && &entry.source_namespace == source), + )?; + Some((policy, provider, contract, strict_policy_producers)) +} + +fn exactly_one(mut matches: impl Iterator) -> Option { + let first = matches.next()?; + matches.next().is_none().then_some(first) +} + +fn owner_report( + run: &impl Fn(&str, &[&OsStr]) -> Result, + product: &Product, + args: &[&OsStr], +) -> Result { + let (api, kind) = match product.product { + "breg" => (BREG_CTL_REPORT, "BRegCtlReport"), + "casework" => (CASEWORK_CTL_REPORT, "CaseworkReport"), + _ => return Err(ReviewToolFailure::Failed), + }; + let command = args + .first() + .and_then(|arg| arg.to_str()) + .ok_or(ReviewToolFailure::Failed)?; + let ReviewToolOutput { exit, report } = run(product.product, args)?; + if report["apiVersion"] != api + || report["kind"] != kind + || report["command"] != command + || report["version"] + .as_str() + .is_none_or(|version| version.trim().is_empty()) + { + return Err(ReviewToolFailure::Failed); + } + match (exit, report["status"].as_str(), report["ok"].as_bool()) { + (Some(0), Some("complete"), Some(true)) => Ok(report), + (Some(1), Some("domain-refusal"), Some(false)) + if valid_domain_refusal(&report, product.product == "breg") => + { + Err(ReviewToolFailure::Refused) + } + _ => Err(ReviewToolFailure::Failed), + } +} + +fn valid_domain_refusal(report: &Value, breg: bool) -> bool { + let Some(diagnostics) = report["diagnostics"].as_array() else { + return false; + }; + diagnostics.iter().any(|entry| entry["severity"] == "error") + && diagnostics + .iter() + .all(|entry| valid_owner_diagnostic(entry, breg)) +} + +fn valid_owner_diagnostic(diagnostic: &Value, breg: bool) -> bool { + let severity = diagnostic["severity"].as_str(); + // Classification uses only the common diagnostic members and never + // forwards the owner's message, source location or additional fields. + (matches!(severity, Some("error" | "warning")) || (breg && severity == Some("finding"))) + && ["code", "path", "message", "suggestedAction"] + .into_iter() + .all(|key| diagnostic[key].is_string()) +} + +fn read(path: &Path, limit: u64) -> Option> { + if !path.is_file() { + return None; + } + read_bounded(File::open(path).ok()?, limit) +} + +fn read_bounded(file: File, limit: u64) -> Option> { + let mut bytes = Vec::new(); + file.take(limit + 1).read_to_end(&mut bytes).ok()?; + (bytes.len() as u64 <= limit).then_some(bytes) +} + +fn inspection_error(service: &Document, product: &Product, failure: ReviewToolFailure) -> Report { + let (code, message, action) = match failure { + ReviewToolFailure::Unavailable => ( + TOOL_UNAVAILABLE, + "The owning authoring tool is unavailable for review inspection.", + "Install matching bregctl and caseworkctl tools or select their local executable overrides.", + ), + ReviewToolFailure::Refused => ( + "rstack.service.review-project-refused", + "The owning authoring tool refused the project during review inspection.", + "Run the owning tool's check on the referenced project and resolve its diagnostics.", + ), + ReviewToolFailure::Failed => ( + TOOL_FAILED, + "The owning authoring tool did not complete with compatible review metadata.", + "Check that bregctl and caseworkctl are from the same build, then run the owning tool's check on the referenced project.", + ), + ReviewToolFailure::Interrupted => ( + TOOL_INTERRUPTED, + "Review inspection was interrupted.", + "Run the command again when ready to complete review inspection.", + ), + }; + problem(service, code, product.source_pointer(), message, action) +} + +fn problem(service: &Document, code: &str, path: &str, message: &str, next: &str) -> Report { + service.report_with([service.diagnostic_at_value(Severity::Error, code, path, message, next)]) +} + +#[derive(Deserialize)] +struct BregExplanationReport { + version: String, + revision: Digest, + explanation: BregExplanation, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct BregExplanation { + actions: Vec, + review_authorities: Vec, +} + +#[derive(Deserialize)] +struct Action { + id: LocalId, + execution: Execution, +} + +#[derive(Deserialize)] +#[serde(tag = "mode", rename_all = "kebab-case")] +enum Execution { + Proposal { proposal: Proposal }, + Immediate, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Proposal { + review: Review, + review_context: Option, + permissions: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ProposalPermission { + actor_kind: Option, + operations: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case")] +enum ActorKind { + Human, + Agent, + Service, +} + +#[derive(Deserialize)] +struct BregReviewContext { + id: LocalId, +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "kebab-case")] +enum Review { + Required { + authority: LocalId, + source: ExternalId, + policy: PolicySelection, + }, + None, +} + +#[derive(Deserialize)] +struct Authority { + id: LocalId, + protocol: String, +} + +#[derive(Deserialize)] +struct PolicySelection { + #[serde(deserialize_with = "review_policy_id")] + id: ExternalId, + #[serde(default, deserialize_with = "deserialize_present_pin")] + version: Option, + #[serde(default, deserialize_with = "deserialize_present_pin")] + digest: Option, +} + +fn deserialize_present_pin<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(deserializer).map(Some) +} + +fn review_policy_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let id = ExternalId::deserialize(deserializer)?; + // The BReg PolicySelectionSource applies the Review protocol's UTF-8 byte limit. + if id.trim().is_empty() || id.len() > 128 { + return Err(serde::de::Error::custom( + "expected a nonblank review policy ID of at most 128 UTF-8 bytes", + )); + } + Ok(id) +} + +#[derive(Deserialize)] +struct BregContract { + id: ExternalId, + revision: Digest, + digest: Digest, + path: String, +} + +impl BregContract { + fn matches(&self, contract: &ReviewContextContract) -> bool { + self.id == contract.id + && self.revision == contract.revision + && self.digest == contract.schema_digest + } +} + +struct GeneratedContracts { + contracts: BTreeMap, + root: OwnedFd, + _scratch: tempfile::TempDir, +} + +impl GeneratedContracts { + fn verified_contract( + &self, + action: &LocalId, + source: &ExternalId, + context_id: &LocalId, + ) -> Result, ReviewToolFailure> { + let Some(contract) = self.contracts.get(action) else { + return Ok(None); + }; + let bytes = read_generated(&self.root, &contract.path)?; + if sha256_uri(&bytes) != contract.digest.as_str() { + return Err(ReviewToolFailure::Failed); + } + let mut schema = parse_json_strict(&bytes).map_err(|_| ReviewToolFailure::Failed)?; + let context = &schema["x-registry-review-context"]; + if schema["$schema"] != "https://json-schema.org/draft/2020-12/schema" + || schema["$id"] != contract.id.as_str() + || context["actionId"] != action.as_str() + || context["sourceNamespace"] != source.as_str() + || context["contextId"] != context_id.as_str() + { + return Err(ReviewToolFailure::Failed); + } + let revision = schema + .as_object_mut() + .and_then(|object| object.remove(SCHEMA_REVISION)); + if revision.as_ref().and_then(Value::as_str) != Some(contract.revision.as_str()) { + return Err(ReviewToolFailure::Failed); + } + // Native pairing derives the meaning revision from the schema without + // its revision member. The digest above covers the exact file bytes. + let canonical = canonicalize_json(&schema).map_err(|_| ReviewToolFailure::Failed)?; + if sha256_uri(&canonical) != contract.revision.as_str() { + return Err(ReviewToolFailure::Failed); + } + Ok(Some(contract)) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct CaseworkExplanation { + version: String, + review_policies: Vec, + context_providers: Vec, + trusted_producers: Vec, +} + +#[derive(Deserialize)] +struct CaseworkPolicy { + binding: PolicyBinding, + purpose: String, + context: Context, + dependencies: PolicyDependencies, + stages: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct CaseworkStage { + exclude_initiator: bool, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct PolicyDependencies { + trusted_producers: Vec, +} + +#[derive(Deserialize)] +struct PolicyBinding { + id: LocalId, + version: String, + digest: Digest, +} + +#[derive(Deserialize)] +#[serde(tag = "mode", rename_all = "kebab-case")] +enum Context { + CurrentSource { + provider: LocalId, + contract: ReviewContextContract, + }, + Submitted, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ContextProvider { + id: LocalId, + source_namespace: ExternalId, + deployment_ref: ExternalId, + capabilities: Vec, + description: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Producer { + id: LocalId, + issuer: Url, + source_namespaces: Vec, + review_policies: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn interrupted_inspection_is_an_operational_failure() { + let report = Report::new(vec![Diagnostic::error( + "rstack.service.review-interrupted", + "/products/breg/projects/workshops/path", + "Review inspection was interrupted.", + "Run the command again when ready to complete review inspection.", + )]); + assert_eq!( + review_tool_failure(&report).map(|finding| finding.code.as_str()), + Some("rstack.service.review-interrupted") + ); + } + + #[test] + fn interrupted_review_does_not_launch_owner() { + let scratch = tempfile::tempdir().unwrap(); + let missing = scratch.path().join("owner"); + assert!(matches!( + run_review_tool(&missing, &[], &AtomicBool::new(true)), + Err(ReviewToolFailure::Interrupted) + )); + } + + #[test] + fn interrupted_review_reaps_running_owner() { + let scratch = tempfile::tempdir().unwrap(); + let tool = scratch.path().join("owner"); + let ready = scratch.path().join("ready"); + fs::write( + &tool, + "#!/usr/bin/env bash\nset -euo pipefail\nprintf '%s\\n' \"$$\" > \"$3\"\nexec sleep 30\n", + ) + .unwrap(); + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); + let terminate = AtomicBool::new(false); + + thread::scope(|scope| { + let owner = scope.spawn(|| run_review_tool(&tool, &[ready.as_os_str()], &terminate)); + let deadline = Instant::now() + Duration::from_secs(5); + let pid = loop { + if let Some(pid) = fs::read_to_string(&ready).ok().and_then(|value| { + value + .strip_suffix('\n') + .and_then(|value| value.parse().ok()) + .and_then(Pid::from_raw) + }) { + break Some(pid); + } + if Instant::now() >= deadline { + break None; + } + thread::sleep(TOOL_POLL); + }; + terminate.store(true, Ordering::Relaxed); + assert!(matches!( + owner.join().unwrap(), + Err(ReviewToolFailure::Interrupted) + )); + assert_eq!( + rustix::process::getpgid(Some(pid.expect("owner started"))), + Err(rustix::io::Errno::SRCH) + ); + }); + } + + #[test] + fn timeout_reaps_the_owner_and_closes_its_descendants_pipes() { + let scratch = tempfile::tempdir().unwrap(); + let tool = scratch.path().join("owner"); + let retained_pipe = scratch.path().join("retained-pipe"); + assert!(Command::new("mkfifo") + .args(["-m", "600"]) + .arg(&retained_pipe) + .status() + .unwrap() + .success()); + fs::write( + &tool, + r#"#!/usr/bin/env bash +set -euo pipefail +exec 3>"$3" +sleep 5 & +printf '%s\n' "$$" >&3 +if [ "$4" = wait ]; then + wait +fi +"#, + ) + .unwrap(); + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); + + for action in ["wait", "exit"] { + let mut pipe = File::from( + rustix::fs::open( + &retained_pipe, + OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC, + Mode::empty(), + ) + .unwrap(), + ); + let started = Instant::now(); + let timeout = Duration::from_secs(1); + let result = run_review_tool_with_timeout( + &tool, + &[retained_pipe.as_os_str(), action.as_ref()], + timeout, + &AtomicBool::new(false), + ); + assert!(matches!(result, Err(ReviewToolFailure::Failed))); + assert!((timeout..Duration::from_secs(4)).contains(&started.elapsed())); + + let mut pid_text = Vec::new(); + let settling = Instant::now() + Duration::from_secs(1); + loop { + match pipe.read_to_end(&mut pid_text) { + Ok(_) => break, + Err(error) + if error.kind() == ErrorKind::WouldBlock && Instant::now() < settling => + { + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("a descendant still owns the test pipe: {error}"), + } + } + let pid_text = std::str::from_utf8(&pid_text).unwrap(); + let pid = Pid::from_raw(pid_text.trim().parse().unwrap()).unwrap(); + assert_eq!( + rustix::process::getpgid(Some(pid)), + Err(rustix::io::Errno::SRCH) + ); + } + } +} diff --git a/crates/registry-platform-config/src/service_compiler.rs b/crates/registry-platform-config/src/service_compiler.rs index 384346f968..4999bd9d79 100644 --- a/crates/registry-platform-config/src/service_compiler.rs +++ b/crates/registry-platform-config/src/service_compiler.rs @@ -10,8 +10,8 @@ use crate::{ AuthoredExpressions, }; use registry_platform_yaml::{ - ApiVersion, Decoded, Diagnostic, Document, EnvelopeRule, Expect, ExternalId, FormatSpec, - LocalId, Reader, Report, Source, UniqueList, MAXIMUM_DOCUMENT_BYTES, + ApiVersion, Decoded, Diagnostic, Digest, Document, EnvelopeRule, Expect, ExternalId, + FormatSpec, LocalId, Reader, Report, Source, UniqueList, Url, MAXIMUM_DOCUMENT_BYTES, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -170,6 +170,45 @@ pub struct Product { source: String, } +impl Product { + pub fn source_pointer(&self) -> &str { + &self.source + } +} + +/// Authoring references needed to connect one native BReg review handoff. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReviewWiring { + pub breg_project: LocalId, + pub casework_project: LocalId, + pub authority: LocalId, + pub action: LocalId, + pub policy: LocalId, + pub context_provider: LocalId, + pub source_namespace: ExternalId, + pub context_contract: ReviewContextContract, + /// Logical key the Casework package expects in its runtime binding map. + pub deployment_ref: ExternalId, + /// Admitted producers and their exact issuers, used only to check a local connector. + #[serde(skip)] + pub admitted_producer_issuers: BTreeMap, + /// Producer IDs included in the Casework policy digest when the Action pins it. + #[serde(skip)] + pub strict_policy_producers: BTreeSet, +} + +#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReviewContextContract { + pub id: ExternalId, + pub revision: Digest, + pub schema_digest: Digest, +} + +pub type ReviewInspector<'a> = + dyn Fn(&Document, &[Product]) -> Result, Report> + 'a; + #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct ServicePlan { @@ -179,6 +218,8 @@ pub struct ServicePlan { service: Option, pub products: Vec, #[serde(skip_serializing_if = "Option::is_none")] + pub review_wiring: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub ui: Option, pub functions: BTreeMap, #[serde(skip_serializing_if = "Option::is_none")] @@ -200,6 +241,7 @@ pub struct Options<'a> { pub checked_routes: Option<&'a Path>, pub route_selections: &'a [String], pub for_client: bool, + pub inspect_review: Option<&'a ReviewInspector<'a>>, } pub fn plan(file: &Path, options: Options<'_>) -> Result { @@ -291,30 +333,44 @@ pub fn plan(file: &Path, options: Options<'_>) -> Result { options.route_selections, )?) }; - let (dev_root, dev_plan) = match options.dev_config { + let (review_wiring, dev_root, dev_plan) = match options.dev_config { Some(path) => { let path = path.canonicalize().map_err(|_| unreadable(path))?; let root = path.parent().ok_or_else(|| unreadable(&path))?; let settings = Reader::new(path.display().to_string()) .with_hook(&mut AuthoredExpressions) .read(&read(&path)?, &Expect::one(&DEV_FORMAT))?; - let projection = if settings.span_of("/products").is_none() { - project_dev(root, &settings, &products, doc)? + let (review, projection) = if settings.span_of("/products").is_none() { + let review = inspect_dev_review(&settings, doc, &products, options.inspect_review)?; + let projection = project_dev(root, &settings, &products, doc, review.as_ref())?; + (review, projection) } else if products.is_empty() { let entries = dev_inventory(root, &settings)?; - project_dev(root, &settings, &entries, &settings)? + ( + None, + project_dev(root, &settings, &entries, &settings, None)?, + ) } else { return Err(two_inventories(&settings, doc)); }; - (Some(root.to_owned()), Some(projection.native)) + (review, Some(root.to_owned()), Some(projection.native)) } - None => (None, None), + None => ( + options + .inspect_review + .map(|inspect| inspect(doc, &products)) + .transpose()? + .flatten(), + None, + None, + ), }; Ok(ServicePlan { file, workspace_root: workspace, service, products, + review_wiring, ui, functions, session, @@ -463,8 +519,50 @@ pub fn development_product_kinds(root: &Path) -> Result, Repor /// Apply the directory's product inventory to dev.yaml while leaving native /// dev validation to its runner. pub fn development_plan(root: &Path, settings: &Document) -> Result { + development_plan_with_review(root, settings, None) +} + +pub fn development_plan_with_review( + root: &Path, + settings: &Document, + inspect_review: Option<&ReviewInspector<'_>>, +) -> Result { let (inventory, entries) = development_inventory(root, settings)?; - project_dev(root, settings, &entries, &inventory) + let review = inspect_dev_review(settings, &inventory, &entries, inspect_review)?; + project_dev(root, settings, &entries, &inventory, review.as_ref()) +} + +fn inspect_dev_review( + settings: &Document, + inventory: &Document, + entries: &[Product], + inspect_review: Option<&ReviewInspector<'_>>, +) -> Result, Report> { + match inspect_review { + Some(inspect) + if settings.span_of("/products").is_none() && needs_review_wiring(settings) => + { + inspect(inventory, entries) + } + _ => Ok(None), + } +} + +const REVIEW_AUTHORITY: &str = "/bindings/bregReviewAuthority"; +const CONTEXT_PROVIDER: &str = "/bindings/caseworkContextProvider"; + +fn needs_review_wiring(settings: &Document) -> bool { + [ + (REVIEW_AUTHORITY, &["id"][..]), + (CONTEXT_PROVIDER, &["id", "action"][..]), + ] + .into_iter() + .any(|(pointer, fields)| { + settings.root().pointer(pointer).is_some_and(|binding| { + matches!(binding.value, registry_platform_yaml::NodeValue::Mapping(_)) + && fields.iter().any(|field| binding.get(field).is_none()) + }) + }) } fn products( @@ -671,6 +769,8 @@ fn route_selection_error() -> Report { pub struct DevelopmentPlan { pub native: Value, pub sources: DevelopmentSources, + /// The shorthand bindings were resolved from the service's review pair. + pub automatic_review: bool, } pub struct DevelopmentSources { @@ -712,6 +812,7 @@ fn project_dev( doc: &Document, products: &[Product], inventory: &Document, + review: Option<&ReviewWiring>, ) -> Result { if products.is_empty() { return Err(problem( @@ -776,6 +877,7 @@ fn project_dev( )); } let mut dev = doc.to_json_value(); + let automatic_review = connect_review(doc, &mut dev, review)?; let dev_mapping = dev .as_object_mut() .expect("the reader checked the envelope"); @@ -783,6 +885,7 @@ fn project_dev( dev_mapping.insert("products".to_owned(), Value::Array(native_products)); Ok(DevelopmentPlan { native: dev, + automatic_review, sources: DevelopmentSources { inventory: inventory.clone(), products: sources, @@ -790,6 +893,141 @@ fn project_dev( }) } +fn connect_review( + settings: &Document, + dev: &mut Value, + review: Option<&ReviewWiring>, +) -> Result { + const DEPLOYMENT_REF: &str = "/bindings/caseworkContextProvider/deploymentRef"; + if settings.span_of(DEPLOYMENT_REF).is_some() { + return Err(problem( + settings, + "rstack.service.review-binding", + DEPLOYMENT_REF, + "The provider's deployment binding key is declared in the Casework project.", + "Remove deploymentRef from dev.yaml.", + )); + } + if !needs_review_wiring(settings) { + return Ok(false); + } + let refusal = |pointer, message, next| { + problem( + settings, + "rstack.service.review-binding", + pointer, + message, + next, + ) + }; + let review = review.ok_or_else(|| { + refusal( + "/bindings", + "The abbreviated review bindings require one exact authored review pair in service.yaml.", + "Resolve the service review wiring or supply the complete explicit bindings.", + ) + })?; + const EXTERNAL_JWKS: &str = "/externalJwksUri"; + if settings.span_of(EXTERNAL_JWKS).is_some() { + return Err(refusal( + EXTERNAL_JWKS, + "The abbreviated review bindings need the run's own key set, so they cannot use externalJwksUri.", + "Remove externalJwksUri and use a runner-managed issuer, or supply the complete explicit bindings.", + )); + } + for (binding, field, expected) in [ + (REVIEW_AUTHORITY, "id", &review.authority), + (CONTEXT_PROVIDER, "id", &review.context_provider), + (CONTEXT_PROVIDER, "action", &review.action), + ] { + let value = dev.pointer_mut(binding).and_then(Value::as_object_mut).ok_or_else(|| { + refusal( + "/bindings", + "The local review connector requires both machine bindings.", + "Supply bregReviewAuthority and caseworkContextProvider with their local identities.", + ) + })?; + if let Some(authored) = value.get(field) { + if authored.as_str() != Some(expected.as_str()) { + return Err(refusal( + &format!("{binding}/{field}"), + "This explicit binding value conflicts with the authored review pair.", + "Remove this value to use the service review wiring, or supply complete explicit bindings.", + )); + } + } else { + value.insert(field.into(), json!(expected)); + } + } + const PRODUCER: &str = "/bindings/bregReviewAuthority/producer"; + let Some(admitted_issuer) = dev + .pointer(PRODUCER) + .and_then(Value::as_str) + .and_then(|producer| LocalId::new(producer).ok()) + .and_then(|producer| review.admitted_producer_issuers.get(&producer)) + else { + return Err(refusal( + if settings.span_of(PRODUCER).is_some() { + PRODUCER + } else { + REVIEW_AUTHORITY + }, + "The local producer must be trusted for the authored policy and source namespace.", + "Set producer to an existing trustedProducers entry that admits this policy and source.", + )); + }; + for binding in [REVIEW_AUTHORITY, "/bindings/coordinatorReviewProducer"] { + let guard = format!("{binding}/runIssuerBinding"); + if dev.pointer(&guard).is_some_and(Value::is_object) + && dev + .pointer(&format!("{binding}/producer")) + .and_then(Value::as_str) + .is_some_and(|producer| { + review + .strict_policy_producers + .iter() + .any(|id| id.as_str() == producer) + }) + { + return Err(refusal( + &guard, + "This run issuer binding would change the digest of the Casework policy pinned by the BReg Action.", + "Use a fixed issuer without rewriting the pinned policy's producers, or select the policy by ID alone in the BReg Action.", + )); + } + } + const BREG_RUN_GUARD: &str = "/bindings/bregReviewAuthority/runIssuerBinding"; + match dev["issuer"].as_str() { + Some("run") if !dev.pointer(BREG_RUN_GUARD).is_some_and(Value::is_object) => { + return Err(refusal( + if settings.span_of(BREG_RUN_GUARD).is_some() { + BREG_RUN_GUARD + } else { + REVIEW_AUTHORITY + }, + "The selected BReg review producer needs its own runIssuerBinding to accept tokens from the run issuer.", + "Supply the exact run issuer guards on bregReviewAuthority, or use the fixed issuer of the selected Casework producer.", + )); + } + Some("run") => {} + Some(issuer) if issuer != admitted_issuer.as_str() => { + return Err(refusal( + "/issuer", + "The fixed development issuer must match the selected Casework producer's issuer.", + "Set issuer to the issuer pinned by the selected trustedProducers entry.", + )); + } + _ => {} + } + if review.deployment_ref.as_str() != review.context_provider.as_str() { + dev.pointer_mut(CONTEXT_PROVIDER) + .and_then(Value::as_object_mut) + .expect("the connector checked the mapping") + .insert("deploymentRef".into(), json!(review.deployment_ref)); + } + Ok(true) +} + fn resolve( doc: &Document, directory: &Path, diff --git a/crates/registry-platform-config/src/service_compiler/tests.rs b/crates/registry-platform-config/src/service_compiler/tests.rs index 904b9d6ade..c3e52d9c49 100644 --- a/crates/registry-platform-config/src/service_compiler/tests.rs +++ b/crates/registry-platform-config/src/service_compiler/tests.rs @@ -19,6 +19,13 @@ audiences: casework: urn:example:casework "; +const SERVICE_REVIEW_INVENTORY: &str = "products: + breg: + projects: + breg: {path: registry} + casework: {path: casework} +"; + struct Directory { _directory: tempfile::TempDir, root: PathBuf, @@ -186,11 +193,8 @@ fn an_explicit_dev_config_uses_its_own_inventory_beside_a_roles_only_service() { let plan = plan( &directory.root.join("service.yaml"), Options { - workspace_root: None, dev_config: Some(&dev), - checked_routes: None, - route_selections: &[], - for_client: false, + ..Default::default() }, ) .expect("the roles-only service plans with the dev inventory"); @@ -200,6 +204,106 @@ fn an_explicit_dev_config_uses_its_own_inventory_beside_a_roles_only_service() { ); } +#[test] +fn explicit_review_bindings_do_not_inspect_the_service_review_pair() { + let directory = Directory::new( + "audiences: {breg: urn:example:registry, casework: urn:example:casework} +bindings: + bregReviewAuthority: {id: review, producer: requester, identity: producer} + caseworkContextProvider: {id: source, action: approve, identity: reader} +", + ) + .service(SERVICE_REVIEW_INVENTORY); + let service = directory.root.join("service.yaml"); + let dev = directory.root.join("dev.yaml"); + let inspect = |document: &Document, _: &[Product]| { + Err(problem( + document, + "rstack.service.review-inspection", + "/products", + "The projects could not be inspected.", + "Check the owning tools.", + )) + }; + + let explicit = plan( + &service, + Options { + dev_config: Some(&dev), + inspect_review: Some(&inspect), + ..Default::default() + }, + ) + .expect("an explicit plan does not need automatic review inspection"); + assert!(explicit.review_wiring.is_none()); + assert_eq!( + explicit.dev_plan.unwrap()["bindings"], + directory.settings().to_json_value()["bindings"] + ); + let projection = + development_plan_with_review(&directory.root, &directory.settings(), Some(&inspect)) + .expect("the runner does not inspect explicit review bindings"); + assert!(!projection.automatic_review); + + let standalone = plan( + &service, + Options { + inspect_review: Some(&inspect), + ..Default::default() + }, + ) + .err() + .expect("standalone service planning still inspects the review pair"); + assert_eq!(refusal(standalone).code, "rstack.service.review-inspection"); +} + +#[test] +fn shorthand_review_bindings_mark_the_projection_without_adding_a_plan_field() { + let directory = Directory::new( + "audiences: {breg: urn:example:registry, casework: urn:example:casework} +bindings: + bregReviewAuthority: {producer: requester, identity: producer} + caseworkContextProvider: {identity: reader} +", + ) + .service(SERVICE_REVIEW_INVENTORY); + let inspect = |_: &Document, _: &[Product]| { + let digest = Digest::new(format!("sha256:{}", "a".repeat(64))).unwrap(); + Ok(Some(ReviewWiring { + breg_project: LocalId::new("breg").unwrap(), + casework_project: LocalId::new("casework").unwrap(), + authority: LocalId::new("review").unwrap(), + action: LocalId::new("approve").unwrap(), + policy: LocalId::new("approval").unwrap(), + context_provider: LocalId::new("source").unwrap(), + source_namespace: ExternalId::new("urn:example:source").unwrap(), + context_contract: ReviewContextContract { + id: ExternalId::new("urn:example:contract").unwrap(), + revision: digest.clone(), + schema_digest: digest, + }, + deployment_ref: ExternalId::new("source").unwrap(), + admitted_producer_issuers: BTreeMap::from([( + LocalId::new("requester").unwrap(), + Url::new("https://issuer.example.test").unwrap(), + )]), + strict_policy_producers: BTreeSet::new(), + })) + }; + let projected = + development_plan_with_review(&directory.root, &directory.settings(), Some(&inspect)) + .expect("the service review pair supplies the missing fields"); + assert!(projected.automatic_review); + assert_eq!( + projected.native["bindings"], + json!({ + "bregReviewAuthority": {"id": "review", "producer": "requester", "identity": "producer"}, + "caseworkContextProvider": {"id": "source", "action": "approve", "identity": "reader"}, + }) + ); + assert!(projected.native.get("automaticReview").is_none()); +} + #[test] fn single_project_runner_products_take_a_path() { let directory = Directory::new( diff --git a/crates/registry-rstack-dev/Cargo.toml b/crates/registry-rstack-dev/Cargo.toml index abeddad28b..833cf0d98b 100644 --- a/crates/registry-rstack-dev/Cargo.toml +++ b/crates/registry-rstack-dev/Cargo.toml @@ -41,7 +41,7 @@ rcgen.workspace = true registry-cli-report.workspace = true registry-platform-buildinfo.workspace = true registry-platform-canonical-json.workspace = true -registry-platform-config.workspace = true +registry-platform-config = { workspace = true, features = ["service-authoring"] } registry-platform-crypto.workspace = true registry-platform-hooks = { workspace = true, features = ["receiver"] } registry-platform-httputil.workspace = true diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 3a2bef870a..c5c099aaf7 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -124,7 +124,7 @@ pub(super) struct CoordinatorReviewProducer { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct BregReviewAuthority { - /// Local identifier of the review authority. + /// Local identifier of the review authority. Omit it to use the exact review wiring of the sibling service. #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub(super) id: String, /// Local identifier of the review producer. @@ -188,15 +188,29 @@ pub(super) enum RunInitiatorTrust { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct CaseworkContextProvider { - /// Local identifier of the context provider. + /// Local identifier of the context provider. Omit it to use the exact review wiring of the sibling service. #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub(super) id: String, /// Name of the test person, in `people`, whose BReg grant Casework uses to authenticate. That grant needs at least one scope. #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub(super) identity: String, - /// Local identifier of the BReg action that the provider pairs with. + /// Local identifier of the BReg Action that the provider pairs with. Omit it to use the exact review wiring of the sibling service. #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] pub(super) action: String, + /// Binding key projected from the Casework package when it differs from the provider ID. + #[serde( + default, + rename = "deploymentRef", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr(feature = "schema", schemars(skip))] + pub(super) deployment_ref: Option, +} + +impl CaseworkContextProvider { + pub(super) fn deployment_ref(&self) -> &str { + self.deployment_ref.as_deref().unwrap_or(&self.id) + } } impl Bindings { @@ -763,7 +777,7 @@ fn render( }; let grant = &plan.people[&binding.identity].grants[&Product::Breg]; let (client_id_ref, client_assertion_key_ref) = client_refs(CASEWORK_CONTEXT_CLIENT); - config["contextProviders"][binding.id.as_str()] = json!({ + config["contextProviders"][binding.deployment_ref()] = json!({ "humanSourceAuthentication": { "audience": plan.product(Product::Breg).audience, }, @@ -905,7 +919,7 @@ pub(super) fn casework_binding_field( } } -fn roles_field(alias: &str) -> String { +pub(super) fn roles_field(alias: &str) -> String { format!( "/people/{}/roles", registry_platform_yaml::escape_pointer_segment(alias) @@ -1808,10 +1822,12 @@ mod tests { id: "registry".to_owned(), identity: "context-reader".to_owned(), action: "reviewed-change".to_owned(), + deployment_ref: None, }), coordinator_review_producer: None, coordinator_breg_client: None, }, + automatic_review: false, journey_file: PathBuf::from("dev-journeys.yaml"), schema_test_people: BTreeMap::new(), application: None, @@ -1827,6 +1843,7 @@ mod tests { application_root: None, application_node: None, preview: None, + automatic_review: false, plan, scenarios: Vec::new(), scenario_digest: String::new(), @@ -2329,6 +2346,20 @@ mod tests { ); } + #[test] + fn casework_runtime_uses_the_projected_deployment_ref() { + let mut plan = plan(); + let provider = plan.bindings.casework_context_provider.as_mut().unwrap(); + provider.deployment_ref = Some("local-source-slot".into()); + let mut output = json!({}); + render_for_check(&plan, Product::Casework, &mut output); + assert!(output["contextProviders"].get("registry").is_none()); + assert_eq!( + output["contextProviders"]["local-source-slot"]["statusProfile"], + "casework-review-status", + ); + } + #[test] fn configure_writes_native_product_bindings() { let root = tempfile::tempdir().unwrap(); @@ -3811,6 +3842,7 @@ mod tests { id: "registry".to_owned(), identity: "coordinator-service".to_owned(), action: "reviewed-change".to_owned(), + deployment_ref: None, }); let error = shared.bindings.validate(&shared).unwrap_err().to_string(); assert!( diff --git a/crates/registry-rstack-dev/src/explain.rs b/crates/registry-rstack-dev/src/explain.rs index e9865687b8..00e7d949de 100644 --- a/crates/registry-rstack-dev/src/explain.rs +++ b/crates/registry-rstack-dev/src/explain.rs @@ -5,7 +5,13 @@ use anyhow::{Context, Result}; use serde_json::Value; -use std::{collections::BTreeSet, path::Path, sync::atomic::AtomicBool}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::Path, + sync::atomic::AtomicBool, +}; + +type ReviewStatusScopes = BTreeMap<(String, String, String), BTreeSet>; /// What `bregctl explain access` and `bregctl explain model` report about one /// project, limited to the members the runner needs. @@ -22,6 +28,8 @@ pub(super) struct BregFacts { pub access_profiles: BTreeSet, pub actions: BTreeSet, pub review_authorities: BTreeSet, + /// Required scopes for compiled status grants, keyed by Action, review authority, and profile. + pub review_status_scopes: ReviewStatusScopes, } /// The owning tool refused the project. `findings` carries its own diagnostics @@ -152,9 +160,48 @@ fn facts_from_reports(access: &Value, model: &Value) -> Result { access_profiles: ids(model, "accessProfiles")?, actions: ids(model, "actions")?, review_authorities: ids(model, "reviewAuthorities")?, + review_status_scopes: review_status_scopes(access)?, }) } +fn review_status_scopes(access: &Value) -> Result { + let mut grants = BTreeMap::new(); + for action in access["actions"]["actions"] + .as_array() + .into_iter() + .flatten() + { + for permission in action["execution"]["proposal"]["permissions"] + .as_array() + .into_iter() + .flatten() + { + let Some(authority) = permission["reviewAuthority"].as_str() else { + continue; + }; + if !permission["operations"] + .as_array() + .is_some_and(|operations| operations.iter().any(|op| op == "get-review-status")) + { + continue; + } + let action = action["id"] + .as_str() + .context("an explained BReg Action has no ID")?; + let profile = permission["profileId"] + .as_str() + .context("an explained BReg status grant has no profile")?; + let scopes = strings(&permission["requiredScopes"]) + .context("an explained BReg status grant has no required scope list")?; + grants.insert( + (action.to_owned(), authority.to_owned(), profile.to_owned()), + scopes, + ); + } + } + Ok(grants) +} + fn strings(value: &Value) -> Option> { value .as_array()? @@ -198,7 +245,16 @@ mod tests { "purposeRequired": true, "requesterClients": ["applier", "context-status", "staff"] }, - "consent": {"clients": [{"client": "recipient", "other": 1}]} + "consent": {"clients": [{"client": "recipient", "other": 1}]}, + "actions": {"actions": [{ + "id": "correct-status", + "execution": {"mode": "proposal", "proposal": {"permissions": [ + {"profileId": "operator", "operations": ["get"]}, + {"profileId": "reviewer", "operations": ["get-review-status"]}, + {"profileId": "status-reader", "reviewAuthority": "casework", + "operations": ["get-review-status"], "requiredScopes": ["read-status"]} + ]}} + }]} } }); let model = json!({ @@ -233,6 +289,14 @@ mod tests { access_profiles: set(&["operator", "reviewer"]), actions: set(&["correct-status"]), review_authorities: set(&["casework"]), + review_status_scopes: BTreeMap::from([( + ( + "correct-status".to_owned(), + "casework".to_owned(), + "status-reader".to_owned() + ), + set(&["read-status"]), + )]), } ); } diff --git a/crates/registry-rstack-dev/src/journey.rs b/crates/registry-rstack-dev/src/journey.rs index ef5d59ccc1..0dcf47b436 100644 --- a/crates/registry-rstack-dev/src/journey.rs +++ b/crates/registry-rstack-dev/src/journey.rs @@ -849,6 +849,7 @@ mod tests { application_root: None, application_node: None, preview: None, + automatic_review: false, plan, scenarios: vec![journey], scenario_digest: String::new(), diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index d7195db1aa..dc74900c77 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -195,6 +195,9 @@ struct RunInput { application_node: Option, #[serde(default, skip_serializing_if = "Option::is_none")] preview: Option, + /// Captured from the service projection for the supervisor's preflight. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + automatic_review: bool, #[serde(deserialize_with = "deserialize_captured_plan")] plan: Plan, #[serde(default)] @@ -999,7 +1002,10 @@ fn check( project.display() ) }) - .and_then(|project| plan::check(&project)); + .and_then(|project| { + let terminate = signals()?; + plan::check(&project, &terminate) + }); let (report, exit) = match outcome { Ok(report) => { let refused = report.has_errors() @@ -1146,7 +1152,8 @@ fn start( project.display() ) })?; - let loaded = plan::load(&project)?; + let signals = signals()?; + let loaded = plan::load_with_signals(&project, &signals)?; let mut plan = loaded.plan; products::require_canonical_review_pair(&project, &plan)?; ensure!( @@ -1179,7 +1186,6 @@ fn start( _ => None, }; let schema_people = products::schema_people(&project, &plan, true)?; - let signals = signals()?; let inspection = products::inspect(&project, &plan, &signals); if let Some(preview) = &preview { loaded @@ -1237,6 +1243,7 @@ fn start( application_root, application_node, preview, + automatic_review: plan.automatic_review, plan, scenarios: loaded.scenarios, scenario_digest: loaded.scenario_digest, @@ -1269,7 +1276,8 @@ fn export_preview(project: &Path, output: &Path) -> Result { project.display() ) })?; - let loaded = plan::load(&project)?; + let signals = signals()?; + let loaded = plan::load_with_signals(&project, &signals)?; let plan = loaded.plan; let build = loaded .preview @@ -1280,7 +1288,6 @@ fn export_preview(project: &Path, output: &Path) -> Result { plan: build, }; let application_node = Some(products::preflight_preview()?); - let signals = signals()?; let inspection = products::inspect(&project, &plan, &signals); loaded .authored_digests @@ -1319,6 +1326,7 @@ fn export_preview(project: &Path, output: &Path) -> Result { application_root: None, application_node, preview: Some(preview), + automatic_review: false, plan, scenarios: Vec::new(), scenario_digest: loaded.scenario_digest, @@ -1388,7 +1396,7 @@ fn prepare_issuer_input( project.display() ) })?; - let loaded = plan::load(&project)?; + let loaded = plan::load_with_signals(&project, signals)?; capture_issuer_input(project, ttl_seconds, signals, resolve_tool, loaded) } @@ -1414,6 +1422,7 @@ fn capture_issuer_input( application_root: None, application_node: None, preview: None, + automatic_review: false, plan, scenarios: Vec::new(), scenario_digest: loaded.scenario_digest, @@ -1739,9 +1748,11 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { let prepared = catch_startup(|| { products.capture_preview_project()?; products.check()?; + products.prepare_casework_run_issuer()?; if let Some(artifact) = &preview_artifact { products.build_preview(artifact)?; } + products.ensure_active()?; let issuer = Arc::new(Issuer::create(root)?); let connected = if input.needs_database() { let (admin, ca) = if input.managed_database { @@ -1769,6 +1780,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { } engine.require_free_volume(key)?; let volume_exists = engine.has_project_volume(key)?; + products.ensure_active()?; retained_volume = !input.clean && volume_exists; if input.clean { engine.remove_project_volume(key)?; @@ -4751,6 +4763,7 @@ EOF application_root: None, application_node: None, preview: None, + automatic_review: false, issuer_only: false, plan, scenarios: Vec::new(), diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 2ee250ef8f..1ac0c19c77 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -3,7 +3,12 @@ use anyhow::{Context, Result}; use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use registry_platform_config::contains_environment_expression; -use registry_platform_config::service_compiler::DevelopmentSources; +use registry_platform_config::service_authoring::{ + inspect_review, review_tool_failure, run_review_tool, ReviewToolFailure, +}; +use registry_platform_config::service_compiler::{ + development_plan_with_review, DevelopmentSources, +}; use registry_platform_httputil::{valid_resource_uri, valid_scope_token}; use registry_platform_yaml::{ escape_pointer_segment, ApiVersion, BoundedU32, Document, EnvelopeRule, Expect, FormatSpec, @@ -20,6 +25,7 @@ use std::{ fs, io::Read, path::{Component, Path, PathBuf}, + sync::atomic::{AtomicBool, Ordering}, }; /// Refuses every `${...}` substitution expression in a development file: the @@ -120,12 +126,25 @@ pub(crate) fn schema() -> schemars::Schema { .expect("Plan has a properties mapping"); properties.insert("products".to_owned(), products.to_value()); properties.insert("audiences".to_owned(), audiences.to_value()); - // The native product list item is internal once products is the mapping. - schema + // The local connector may leave these structural members to the service + // projection. Native plans and retained snapshots always carry the IDs. + let definitions = schema .get_mut("$defs") .and_then(Value::as_object_mut) - .expect("Plan has definitions") - .remove("ProductPlan"); + .expect("Plan has definitions"); + for (name, members) in [ + ("BregReviewAuthority", &["id"][..]), + ("CaseworkContextProvider", &["id", "action"][..]), + ] { + definitions + .get_mut(name) + .and_then(|binding| binding.get_mut("required")) + .and_then(Value::as_array_mut) + .expect("a native review binding requires its IDs") + .retain(|value| !value.as_str().is_some_and(|field| members.contains(&field))); + } + // The native product list item is internal once products is the mapping. + definitions.remove("ProductPlan"); let required = schema .get_mut("required") .and_then(Value::as_array_mut) @@ -403,6 +422,9 @@ pub(super) struct Plan { /// Run-local connections between BReg and Casework. Leave empty when the products do not call each other. A `runIssuerBinding` replaces the producer's fixed issuer with the run's own, so it requires `issuer: run`. #[serde(default)] pub bindings: super::bindings::Bindings, + /// Set by the service projection and used during authored-plan inspection. + #[serde(skip)] + pub automatic_review: bool, /// Chooses the test person for a BReg fixture step in tests/journeys.yaml, keyed by journey identifier and then step identifier. Needed only when several people could run the step; every named person needs a BReg grant. #[serde(default)] #[cfg_attr( @@ -1065,8 +1087,12 @@ struct AuthoredPlan { sources: Option, } -fn read_plan(root: &Path, offline_check: bool) -> Result<(AuthoredPlan, AuthoredDigests)> { - let (authored, dev) = decode_authored_plan(root)?; +fn read_plan( + root: &Path, + offline_check: bool, + terminate: &AtomicBool, +) -> Result<(AuthoredPlan, AuthoredDigests)> { + let (authored, dev) = decode_authored_plan(root, terminate)?; authored .value .validate_structure(root) @@ -1117,6 +1143,7 @@ fn read_plan(root: &Path, offline_check: bool) -> Result<(AuthoredPlan, Authored fn decode_authored_plan( root: &Path, + terminate: &AtomicBool, ) -> Result<(AuthoredPlan, String)> { let file = root.join("dev.yaml"); let bytes = read( @@ -1131,9 +1158,41 @@ fn decode_authored_plan( remedy: WRITE_THE_VALUE, }) .read(&bytes, &Expect::one(&FORMAT))?; - let projection = registry_platform_config::service_compiler::development_plan(root, &document)?; + let projection = development_plan_with_review( + root, + &document, + Some(&|service, products| { + inspect_review(service, products, |product, args| { + if terminate.load(Ordering::Relaxed) { + return Err(ReviewToolFailure::Interrupted); + } + let product = match product { + "breg" => Product::Breg, + "casework" => Product::Casework, + _ => return Err(ReviewToolFailure::Unavailable), + }; + let tool = + super::product_tool(product).map_err(|_| ReviewToolFailure::Unavailable)?; + run_review_tool(&tool, args, terminate) + }) + }), + ) + .map_err(|report| { + let Some(item) = review_tool_failure(&report) else { + return anyhow::Error::from(report); + }; + let mut failure = super::products::InspectionUnavailable::new( + &item.path, + &item.message, + &item.suggested_action, + ); + if let Some(location) = item.source.clone() { + failure = failure.at(&item.path, location); + } + failure.into() + })?; let bytes = serde_json::to_vec(&projection.native)?; - let decoded = Reader::new(&name) + let mut decoded = Reader::new(&name) .decode::>(&bytes, &Expect::one(&FORMAT)) .map_err(|mut report| { // The reader positioned these diagnostics in the projected JSON. @@ -1185,6 +1244,7 @@ fn decode_authored_plan( } report })?; + decoded.value.automatic_review = projection.automatic_review; Ok(( AuthoredPlan { value: decoded.value, @@ -1293,16 +1353,15 @@ pub(super) struct LoadedPlan { pub preview: Option, } -pub(crate) fn check(root: &Path) -> Result { - let (decoded, authored_digests) = read_plan(root, true)?; +pub(crate) fn check(root: &Path, terminate: &AtomicBool) -> Result { + let (decoded, authored_digests) = read_plan(root, true, terminate)?; validate_plan(root, &decoded)?; read_journeys(root, &decoded.value)?; let preview = preview_plan(root, &decoded, &authored_digests)?; if let Err(refusal) = super::products::schema_people(root, &decoded.value, false) { return Err(refusal_report(&decoded, &refusal).into()); } - let terminate = super::signals()?; - let inspection = super::products::inspect(root, &decoded.value, &terminate); + let inspection = super::products::inspect(root, &decoded.value, terminate); if let Some(preview) = preview { authored_digests.verify_preview_native(&preview.product.project)?; } @@ -1321,8 +1380,8 @@ pub(crate) fn check(root: &Path) -> Result { Ok(decoded.document.report_with(Vec::new())) } -pub(super) fn load(root: &Path) -> Result { - let (decoded, authored_digests) = read_plan(root, false)?; +pub(super) fn load_with_signals(root: &Path, terminate: &AtomicBool) -> Result { + let (decoded, authored_digests) = read_plan(root, false, terminate)?; validate_plan(root, &decoded)?; let (scenarios, scenario_digest) = read_journeys(root, &decoded.value)?; let preview = preview_plan(root, &decoded, &authored_digests)?; @@ -1335,6 +1394,11 @@ pub(super) fn load(root: &Path) -> Result { }) } +#[cfg(test)] +pub(super) fn load(root: &Path) -> Result { + load_with_signals(root, &AtomicBool::new(false)) +} + fn preview_plan( root: &Path, decoded: &AuthoredPlan, @@ -2327,6 +2391,40 @@ mod tests { }) } + #[test] + fn interrupted_dev_decode_skips_review_tool_resolution() { + use registry_platform_config::service_compiler::{SERVICE_API_VERSION, SERVICE_FORMAT}; + + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("registry.yaml"), "reviewAuthorities: {}\n").unwrap(); + fs::write(root.path().join("casework.yaml"), "{}\n").unwrap(); + fs::write( + root.path().join("service.yaml"), + format!( + "apiVersion: {SERVICE_API_VERSION}\nkind: {}\n\ + products: {{breg: {{projects: {{breg: {{path: .}}}}}}, casework: {{path: .}}}}\n", + SERVICE_FORMAT.kind + ), + ) + .unwrap(); + fs::write( + root.path().join("dev.yaml"), + format!( + "apiVersion: {API_VERSION}\nkind: {KIND}\nbindings: {{bregReviewAuthority: {{}}}}\n" + ), + ) + .unwrap(); + + let error = decode_authored_plan(root.path(), &AtomicBool::new(true)) + .err() + .expect("review inspection was interrupted"); + let failure = error + .downcast_ref::() + .expect("an interrupted owner inspection is operational"); + assert_eq!(failure.field(), "/products/breg/projects/breg/path"); + assert_eq!(failure.reason(), "Review inspection was interrupted."); + } + #[test] fn authored_grants_name_roles_and_service_yaml_before_other_inputs_are_read() { let root = tempfile::tempdir().unwrap(); @@ -2337,7 +2435,9 @@ mod tests { ), ) .unwrap(); - let error = decode_authored_plan(root.path()).err().unwrap(); + let error = decode_authored_plan(root.path(), &AtomicBool::new(false)) + .err() + .unwrap(); let report = error.downcast_ref::().unwrap(); let diagnostic = report .diagnostics() @@ -2372,7 +2472,9 @@ mod tests { ), ) .unwrap(); - let error = decode_authored_plan(root.path()).err().unwrap(); + let error = decode_authored_plan(root.path(), &AtomicBool::new(false)) + .err() + .unwrap(); let report = error.downcast_ref::().unwrap(); let [diagnostic] = report.diagnostics() else { panic!("expected exactly one diagnostic: {report}"); diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 6b6603c7fe..2a41d17222 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2,8 +2,12 @@ //! Activate ordinary packages and serve them on the run's private bindings. use anyhow::{bail, ensure, Context, Result}; -use registry_platform_config::DatabaseTransport; -use serde::Serialize; +use registry_platform_config::{ + identity_facts::{ActorKind, ACTOR_KIND_CLAIM}, + DatabaseTransport, +}; +use registry_platform_yaml::{escape_pointer_segment, Diagnostic, Node, Report, Source}; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::{ cell::RefCell, @@ -59,6 +63,7 @@ pub(super) const FIELD_KEY: &str = "field-key"; /// The largest tool report the runner reads or retains. const MAX_TOOL_REPORT: u64 = 4 * 1024 * 1024; +const TOOL_REPORT_WAIT: Duration = Duration::from_secs(30); /// The format of the file `bregctl test --credentials` reads. The published /// schema is `products/breg/generated/tools/schema-test-credentials.v1.schema.json`. @@ -394,6 +399,7 @@ pub(super) struct ProductRunner<'a> { input: Arc, root: &'a Path, preview_project: Option, + bound_casework_project: Option, terminate: &'a AtomicBool, deadline: Instant, runtime: tokio::runtime::Runtime, @@ -435,6 +441,7 @@ impl<'a> ProductRunner<'a> { input, root, preview_project: None, + bound_casework_project: None, terminate, deadline: Instant::now() + Duration::from_secs(300), runtime: tokio::runtime::Builder::new_current_thread() @@ -579,6 +586,73 @@ impl<'a> ProductRunner<'a> { Ok(()) } + pub(super) fn prepare_casework_run_issuer(&mut self) -> Result<()> { + let plan = &self.input.plan; + if !self.input.automatic_review || !has_run_source(plan) { + return Ok(()); + } + self.ensure_active()?; + let project = product_root(&self.input.project, plan, Product::Casework)? + .context("missing Casework project for automatic review")?; + let bound = SelectedProduct { + field: project.field, + root: self.root.join("casework-bound"), + }; + bind_casework_run_issuer(plan, &project.root, &bound.root)?; + let report = self.projected_casework_report(&bound.root); + check_projected_casework(&bound, report, stopping(self.root, self.terminate))?; + self.bound_casework_project = Some(bound.root); + Ok(()) + } + + fn projected_casework_report(&self, project: &Path) -> Result<(ExitStatus, Value)> { + self.ensure_active()?; + // Drain the report while polling the guard so a blocked pipe cannot + // delay the supervisor's response to a stop request. + let (report, stdout) = std::io::pipe()?; + let flags = rustix::fs::fcntl_getfl(&report)?; + rustix::fs::fcntl_setfl(&report, flags | rustix::fs::OFlags::NONBLOCK)?; + let mut report = report.take(MAX_TOOL_REPORT + 1); + let mut bytes = Vec::new(); + let mut read_report = || -> Result<()> { + match report.read_to_end(&mut bytes) { + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {} + Err(error) => return Err(error.into()), + } + ensure!( + bytes.len() as u64 <= MAX_TOOL_REPORT, + "the caseworkctl check report exceeds the size limit" + ); + Ok(()) + }; + let mut child = spawn_guarded_tool( + &self.input.binaries[&Product::Casework].tool, + &[ + "--format".as_ref(), + "json".as_ref(), + "check".as_ref(), + project.as_os_str(), + ], + self.root, + ("caseworkctl", "check"), + stdout.into(), + Stdio::null(), + )?; + let deadline = Instant::now() + TOOL_REPORT_WAIT; + let status = wait_for_guarded_tool(&mut child, || { + self.ensure_active()?; + ensure!(Instant::now() < deadline, "caseworkctl check timed out"); + read_report() + })?; + self.ensure_active()?; + read_report()?; + Ok(( + status, + parse_tool_report(&bytes, "caseworkctl", "check", true)?, + )) + } + /// Where each Messaging provider's sent messages can be read, by provider /// ID. It is empty unless the run started Messaging. pub(super) fn sinks(&self) -> Value { @@ -1455,7 +1529,9 @@ impl<'a> ProductRunner<'a> { breg_package: Option<&Path>, ) -> Result { let bound; - let project = if has_run_source(&self.input.plan) { + let project = if let Some(bound) = &self.bound_casework_project { + bound.as_path() + } else if has_run_source(&self.input.plan) { bound = self.root.join("casework-bound"); bind_casework_run_issuer(&self.input.plan, project, &bound)?; self.tool(Product::Casework, "check", &[bound.as_os_str()])?; @@ -2381,15 +2457,14 @@ fn run_logged_tool( ) -> Result<()> { let name = format!("{product}-{stage}"); let mut output = tempfile::tempfile_in(root)?; - let mut command = guard::Command::new(root, &format!("tool-{product}-{stage}"), binary) - .map_err(operational)?; - let mut child = command - .args(args) - .stdout(output.try_clone()?) - .stderr(open_log(root, &name)?) - .spawn() - .with_context(|| format!("cannot start {product} {stage}")) - .map_err(operational)?; + let mut child = spawn_guarded_tool( + binary, + args, + root, + (product, stage), + output.try_clone()?.into(), + open_log(root, &name)?.into(), + )?; let status = wait_for_guarded_tool(&mut child, active)?; if stage == "apply" && !status.success() { let unchanged = match product { @@ -2418,6 +2493,24 @@ fn run_logged_tool( Ok(()) } +fn spawn_guarded_tool( + binary: &Path, + args: &[&std::ffi::OsStr], + root: &Path, + (product, stage): (&str, &str), + stdout: Stdio, + stderr: Stdio, +) -> Result { + guard::Command::new(root, &format!("tool-{product}-{stage}"), binary) + .map_err(operational)? + .args(args) + .stdout(stdout) + .stderr(stderr) + .spawn() + .with_context(|| format!("cannot start {product} {stage}")) + .map_err(operational) +} + fn retain_tool_receipt( output: &mut fs::File, root: &Path, @@ -2706,6 +2799,10 @@ fn casework_config( } fn authored_document(path: &Path) -> Result { + Ok(authored_tree(path)?.to_json_value()) +} + +fn authored_tree(path: &Path) -> Result { use registry_platform_yaml::{Reader, MAXIMUM_DOCUMENT_BYTES}; let mut bytes = Vec::new(); fs::File::open(path)? @@ -2717,7 +2814,6 @@ fn authored_document(path: &Path) -> Result { ); Reader::new(path.display().to_string()) .scan(&bytes)? - .map(|node| node.to_json_value()) .context("project document is empty") } @@ -2800,7 +2896,7 @@ pub(super) struct InspectionUnavailable { } impl InspectionUnavailable { - fn new(field: &str, reason: &str, remedy: &str) -> Self { + pub(super) fn new(field: &str, reason: &str, remedy: &str) -> Self { Self { field: field.to_owned(), location: None, @@ -2849,6 +2945,15 @@ pub(super) fn inspection_failed( if terminate.load(Ordering::Relaxed) { return error; } + inspection_unavailable(product, field, action, error) +} + +fn inspection_unavailable( + product: Product, + field: &str, + action: &str, + error: anyhow::Error, +) -> anyhow::Error { let (tool, variable) = super::product_tool_info(product); InspectionUnavailable::new( field, @@ -2914,9 +3019,9 @@ pub(super) fn inspect_with( }) } -fn product_root( +fn product_root( root: &Path, - plan: &Plan, + plan: &Plan, product: Product, ) -> plan::SemanticResult> { let Some((index, entry)) = plan @@ -3021,6 +3126,7 @@ fn breg_authority( } } check_breg_grants(&facts, &plan.people)?; + validate_automatic_review_status(plan, &facts)?; let principal = breg_principal(plan, &facts.principal_claims)?; Ok(Some(BregAuthority { principal, @@ -3098,9 +3204,8 @@ fn validate_breg_binding_ids(bindings: &Bindings, facts: &BregFacts) -> plan::Se /// Every BReg grant must name an access profile the project declares, /// including profiles that carry only proposal permissions and so belong to no -/// entity. Scopes are not checked here: a profile's required scopes are a -/// per-entity rule the runtime applies, and a mismatch surfaces when the -/// journey runs. +/// entity. BReg applies each operation's required scopes at runtime. The +/// automatic review pair checks its exact service-status grant separately. fn check_breg_grants( facts: &BregFacts, people: &BTreeMap, @@ -3121,10 +3226,144 @@ fn check_breg_grants( Ok(()) } +fn validate_automatic_review_status(plan: &Plan, facts: &BregFacts) -> plan::SemanticResult<()> { + if !plan.automatic_review { + return Ok(()); + } + let provider = plan + .bindings + .casework_context_provider + .as_ref() + .expect("automatic review resolves a Casework context provider binding"); + let authority = plan + .bindings + .breg_review_authority + .as_ref() + .expect("automatic review resolves a BReg review authority binding"); + let grant = &plan.people[&provider.identity].grants[&Product::Breg]; + let field = super::bindings::roles_field(&provider.identity); + let key = ( + provider.action.clone(), + authority.id.clone(), + grant.profile.clone(), + ); + let scopes = facts.review_status_scopes.get(&key).ok_or_else(|| { + plan::SemanticRefusal::new( + &field, + "The BReg grant lacks get-review-status for the selected Action and review authority.", + "Give the status profile a get-review-status permission for the paired Action and its reviewAuthority.", + ) + })?; + plan::require( + scopes.iter().all(|scope| grant.scopes.contains(scope)), + &field, + "The BReg status grant lacks required scopes for the selected Action.", + "Supply the scopes the selected BReg status profile requires in the binding identity's grant.", + )?; + // The local machine issuer signs the resolved grant, including any + // omissions applied by tokenFixtures. BReg requires a service caller for + // the compiled named review-authority status permission. + plan::require( + grant.claims.get(ACTOR_KIND_CLAIM).and_then(Value::as_str) + == Some(ActorKind::Service.as_str()), + &field, + "The BReg status grant must carry the service actor kind.", + "Assign a service role to the status identity and retain registry_actor_kind in its BReg token fixture.", + ) +} + +/// Check the completion declarations before Casework generates identity facts. +/// The facts runtime can load authored destinations, but the development +/// runtime only renders the hook owned by its bound Coordinator producer. +pub(super) fn check_automatic_review_completions( + root: &Path, + plan: &Plan, +) -> Result<()> { + if !plan.automatic_review { + return Ok(()); + } + let Some(project) = product_root(root, plan, Product::Casework)? else { + return Ok(()); + }; + let source = project.root.join("casework.yaml"); + let tree = authored_tree(&source)?; + let policy = tree.to_json_value(); + let breg_producer = plan + .bindings + .breg_review_authority + .as_ref() + .map(|binding| &binding.producer); + let mut findings = Vec::new(); + for (producer, entry) in policy["trustedProducers"].as_object().into_iter().flatten() { + let Some(destination) = entry["completion"]["destinationId"].as_str() else { + continue; + }; + let receiver = plan + .bindings + .coordinator_review_producer + .as_ref() + .filter(|binding| binding.completion_destination == destination); + let (message, remedy) = match receiver { + _ if breg_producer == Some(producer) => ( + "The automatic BReg review producer uses polling and cannot declare a completion hook.", + "Remove completion from the BReg review producer. Use a separate producer for the Coordinator hook.", + ), + Some(binding) if &binding.producer == producer => continue, + Some(_) => ( + "The local completion destination belongs to the bound Coordinator producer.", + "Remove completion from this producer. Keep the local hook on the bound Coordinator producer.", + ), + None => ( + "This producer declares a completion destination the development run does not configure.", + "Remove completion from this producer or use the destination of its bound Coordinator connection.", + ), + }; + findings.push(casework_completion_diagnostic( + &source, + &tree, + producer, + "destinationId", + message, + remedy, + )); + } + if findings.is_empty() { + return Ok(()); + } + Err(Report::new(findings).into()) +} + +fn casework_completion_diagnostic( + source: &Path, + tree: &Node, + producer: &str, + member: &str, + message: &str, + remedy: &str, +) -> Diagnostic { + let pointer = format!( + "/trustedProducers/{}/completion/{member}", + escape_pointer_segment(producer) + ); + let position = tree.pointer(&pointer).map(|node| node.span.start); + let mut diagnostic = Diagnostic::error( + "rstack.dev.invalid-review-completion", + pointer, + message, + remedy, + ); + diagnostic.source = Some(Source { + file: source.display().to_string(), + line: position.map(|pos| pos.line), + column: position.map(|pos| pos.column), + }); + diagnostic +} + fn casework_principals( root: &Path, plan: &Plan, - _breg: Option<&BregAuthority>, + breg: Option<&BregAuthority>, terminate: &AtomicBool, resolve_tool: &impl Fn(Product) -> Result, ) -> Result> { @@ -3172,8 +3411,28 @@ fn casework_principals( .and_then(|person| person.grants.get(&Product::Breg)) .map(|grant| grant.profile.as_str()); validate_casework_binding_ids(&plan.bindings, &facts, status_profile)?; + if plan.automatic_review { + let policy = authored_document(&project.root.join("casework.yaml")).map_err(|_| { + plan::SemanticRefusal::new( + &project.field, + "The Casework policy could not be read to check the selected producer's scopes.", + "Restore the Casework policy and run the development check again.", + ) + })?; + validate_automatic_review_producer(plan, &facts, breg, &policy)?; + } if has_run_source(plan) { - checked_casework_run_issuer(plan, &project.root)?; + let document = checked_casework_run_issuer(plan, &project.root)?; + if plan.automatic_review { + let scratch = tempfile::tempdir()?; + let bound = SelectedProduct { + field: project.field.clone(), + root: scratch.path().join("casework-bound"), + }; + let issuer = casework_projection_issuer(&document)?; + write_bound_casework_project(plan, &project.root, &bound.root, document, &issuer)?; + inspect_projected_casework(&tool, &bound, terminate)?; + } } if let Some(coordinator) = product_root(root, plan, Product::Coordinator)? { checked_coordinator_review_producer(plan, &project.root, &coordinator.root)?; @@ -3313,7 +3572,7 @@ fn read_tool_report( stdout.take(MAX_TOOL_REPORT + 1).read_to_end(&mut bytes)?; Ok::<_, std::io::Error>(bytes) }); - let deadline = Instant::now() + Duration::from_secs(30); + let deadline = Instant::now() + TOOL_REPORT_WAIT; let status = wait_for_tool(&mut child, || { ensure!( !terminate.load(Ordering::Relaxed), @@ -3329,13 +3588,16 @@ fn read_tool_report( bytes.len() as u64 <= MAX_TOOL_REPORT, "the {name} {command} report exceeds the size limit" ); + Ok((status, parse_tool_report(&bytes, name, command, strict)?)) +} + +fn parse_tool_report(bytes: &[u8], name: &str, command: &str, strict: bool) -> Result { let malformed = || anyhow::anyhow!("{name} {command} did not emit a JSON report"); - let report = if strict { - registry_platform_crypto::parse_json_strict(&bytes).map_err(|_| malformed())? + if strict { + registry_platform_crypto::parse_json_strict(bytes).map_err(|_| malformed()) } else { - serde_json::from_slice(&bytes).map_err(|_| malformed())? - }; - Ok((status, report)) + serde_json::from_slice(bytes).map_err(|_| malformed()) + } } fn casework_domain_refusal(report: &Value, command: &str) -> bool { @@ -3367,8 +3629,8 @@ const CHECK_BIND: &str = "127.0.0.1:1"; /// Renders the Casework runtime configuration the run writes and lets the /// selected `caseworkctl check` decide whether Casework would accept the -/// context provider binding in it. A refusal lands on the plan field that -/// produced the member Casework names. +/// context provider binding in it or require task authority the run cannot +/// supply. A refusal lands on the relevant authored plan field. fn check_casework_binding( tool: &Path, project: &SelectedProduct, @@ -3420,8 +3682,14 @@ fn check_casework_binding( )) } }; - match casework_binding_check(status.code(), &report, &binding.id) { + match casework_binding_check(status.code(), &report, binding.deployment_ref()) { BindingCheck::Accepted => Ok(()), + BindingCheck::TaskAuthorityRequired => Err(plan::SemanticRefusal::new( + &project.field, + "Casework requires taskAuthority for this project, and the development runner cannot supply it.", + "Select a Casework project without taskTemplates for this run, or deploy Casework with its own configured task authority.", + ) + .into()), BindingCheck::Refused { member, message } => Err(plan::SemanticRefusal::new( super::bindings::casework_binding_field(plan, binding, &member), format!( @@ -3444,6 +3712,8 @@ fn check_casework_binding( #[derive(Debug, Eq, PartialEq)] enum BindingCheck { Accepted, + /// The project needs the task authority that the development run omits. + TaskAuthorityRequired, /// Casework refused `member`, a JSON pointer relative to the binding. Refused { member: String, @@ -3455,10 +3725,10 @@ enum BindingCheck { /// What a `caseworkctl check` that exited with `code` and printed `report` /// decided about the context provider binding `id` in the configuration the -/// run writes. Only refusals at the binding count: the rest of the file names -/// stand-in paths and the project is not yet paired, and `start` checks both -/// as they are. A refusal by the shared loader elsewhere in the file means -/// Casework never read the binding. +/// run writes. The overall file uses stand-in paths and the project has yet +/// to be paired, so `start` checks those inputs when they are available. +/// A required task authority stays absent at startup. A shared loader +/// refusal elsewhere in the file means Casework never read the binding. fn casework_binding_check(code: Option, report: &Value, id: &str) -> BindingCheck { if code == Some(0) && report["apiVersion"] == CASEWORK_REPORT_API_VERSION @@ -3477,6 +3747,7 @@ fn casework_binding_check(code: Option, report: &Value, id: &str) -> Bindin registry_platform_yaml::escape_pointer_segment(id) ); let mut unread = false; + let mut task_authority_required = false; for diagnostic in report["diagnostics"].as_array().into_iter().flatten() { if diagnostic["severity"] != "error" || diagnostic["artifact"] != "CaseworkRuntimeConfig" { continue; @@ -3496,9 +3767,13 @@ fn casework_binding_check(code: Option, report: &Value, id: &str) -> Bindin }; } } + task_authority_required |= + code == "casework.runtime.invalid-task-authority" && path == "/taskAuthority"; unread |= !code.starts_with("casework.runtime."); } - if unread { + if task_authority_required { + BindingCheck::TaskAuthorityRequired + } else if unread { BindingCheck::Unchecked } else { BindingCheck::Accepted @@ -3529,10 +3804,9 @@ fn casework_findings(report: &Value) -> String { .join("; ") } -#[derive(Debug, Eq, PartialEq)] struct CaseworkFacts { profiles: BTreeMap, - trusted_producers: BTreeSet, + trusted_producers: BTreeMap, /// Each context provider's ID with the profile its policy names for the /// `service-status` capability, when it names one. context_providers: BTreeMap>, @@ -3567,7 +3841,7 @@ fn casework_report_facts(report: &Value) -> Result { } Ok(CaseworkFacts { profiles: principals, - trusted_producers: casework_report_ids(report, "trustedProducers")?, + trusted_producers: casework_trusted_producers(report)?, context_providers: casework_context_providers(report)?, }) } @@ -3592,21 +3866,21 @@ fn casework_context_providers(report: &Value) -> Result Result> { - let entries = report[member] +fn casework_trusted_producers(report: &Value) -> Result> { + let entries = report["trustedProducers"] .as_array() - .with_context(|| format!("caseworkctl explain did not report {member}"))?; - let mut ids = BTreeSet::new(); + .context("caseworkctl explain did not report trustedProducers")?; + let mut producers = BTreeMap::new(); for entry in entries { let id = entry["id"] .as_str() - .with_context(|| format!("a caseworkctl explain {member} entry has no ID"))?; + .context("a caseworkctl explain trustedProducers entry has no ID")?; ensure!( - ids.insert(id.to_owned()), - "caseworkctl explain returned duplicate {member} IDs" + producers.insert(id.to_owned(), entry.clone()).is_none(), + "caseworkctl explain returned duplicate trustedProducers IDs" ); } - Ok(ids) + Ok(producers) } fn validate_casework_binding_ids( @@ -3616,7 +3890,7 @@ fn validate_casework_binding_ids( ) -> plan::SemanticResult<()> { if let Some(binding) = &bindings.breg_review_authority { plan::require( - facts.trusted_producers.contains(&binding.producer), + facts.trusted_producers.contains_key(&binding.producer), "/bindings/bregReviewAuthority/producer", "The BReg review producer does not name a trusted producer in the Casework project.", "Set producer to a trusted producer defined by the Casework project.", @@ -3646,6 +3920,120 @@ fn validate_casework_binding_ids( Ok(()) } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct CaseworkProducerAuthority { + issuer: String, + profile: String, + subject: String, + trusted_initiator_issuer: Option, + trusted_initiator_principal_claim: Option, +} + +fn validate_automatic_review_producer( + plan: &Plan, + facts: &CaseworkFacts, + breg: Option<&BregAuthority>, + policy: &Value, +) -> plan::SemanticResult<()> { + if !plan.automatic_review { + return Ok(()); + } + const PRODUCER: &str = "/bindings/bregReviewAuthority/producer"; + const IDENTITY: &str = "/bindings/bregReviewAuthority/identity"; + let binding = plan + .bindings + .breg_review_authority + .as_ref() + .expect("automatic review resolves a BReg review authority binding"); + let producer = facts + .trusted_producers + .get(&binding.producer) + .and_then(|entry| CaseworkProducerAuthority::deserialize(entry).ok()) + .ok_or_else(|| { + plan::SemanticRefusal::new( + PRODUCER, + "The Casework explanation does not describe the selected producer's authority.", + "Check the trusted producer with the matching Casework tool.", + ) + })?; + let person = &plan.people[&binding.identity]; + let grant = &person.grants[&Product::Casework]; + let run_issuer = plan.issuer == "run"; + plan::require( + run_issuer || producer.issuer == plan.issuer, + "/issuer", + "The fixed development issuer must match the selected Casework producer's issuer.", + "Set issuer to the issuer pinned by the selected trustedProducers entry.", + )?; + // BReg explicitly requests the grant's primary profile. The issuer puts + // the same person subject in sub and any Casework-selected principal claim. + plan::require( + producer.profile == grant.profile, + IDENTITY, + "The identity's Casework grant profile must match the selected trusted producer's profile.", + "Assign a role that selects the producer's Casework profile for this identity.", + )?; + plan::require( + producer.subject == person.subject, + IDENTITY, + "The identity's subject must match the selected trusted producer's subject.", + "Use a test identity whose subject matches the Casework trusted producer.", + )?; + check_casework_producer_scopes(&binding.identity, grant, policy)?; + // Casework drops untrusted initiator identities when the policy permits it. + if producer.trusted_initiator_issuer.is_none() + && producer.trusted_initiator_principal_claim.is_none() + { + return Ok(()); + } + if run_issuer { + plan::require( + binding + .run_issuer_binding + .as_ref() + .is_some_and(|guard| guard.initiator.is_some()), + "/bindings/bregReviewAuthority/runIssuerBinding", + "The selected producer's trusted initiator issuer must follow the run issuer.", + "Set an initiator guard matching the issuer pinned by the selected trusted producer.", + )?; + } else { + plan::require( + producer.trusted_initiator_issuer.as_deref() == Some(plan.issuer.as_str()), + "/issuer", + "The fixed development issuer must match the selected producer's trusted initiator issuer.", + "Align issuer and the selected trusted producer's trustedInitiatorIssuer for this development pair.", + )?; + } + plan::require( + breg.is_some_and(|authority| { + producer.trusted_initiator_principal_claim.as_deref() + == Some(authority.principal.as_str()) + }), + PRODUCER, + "The selected producer's trusted initiator claim must match the BReg principal claim.", + "Align trustedInitiatorPrincipalClaim with the principal claim selected by the BReg project.", + ) +} + +fn check_casework_producer_scopes( + identity: &str, + grant: &plan::Grant, + policy: &Value, +) -> plan::SemanticResult<()> { + let mut required = policy["accessProfiles"][&grant.profile]["requiredScopes"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str); + plan::require( + required.all(|scope| grant.scopes.iter().any(|granted| granted == scope)), + &super::bindings::roles_field(identity), + "The identity's Casework grant lacks required scopes for the producer's profile.", + "Assign a role that supplies the required Casework scopes.", + ) +} + impl Drop for ProductRunner<'_> { fn drop(&mut self) { // The normal exit reports stop failures explicitly. @@ -3684,7 +4072,7 @@ pub(super) fn wait_for_tool( fn wait_for_guarded_tool( child: &mut guard::Child, - active: impl Fn() -> Result<()>, + mut active: impl FnMut() -> Result<()>, ) -> Result { loop { if let Err(error) = active() { @@ -4067,17 +4455,26 @@ fn guarded_producers(plan: &Plan) -> Vec> { /// binding names an initiator. The caller then runs the public `caseworkctl /// check` and `package` on the copy, which refuse every other policy error. fn bind_casework_run_issuer(plan: &Plan, project: &Path, bound: &Path) -> Result<()> { - let mut document = checked_casework_run_issuer(plan, project)?; + let document = checked_casework_run_issuer(plan, project)?; ensure!( is_loopback_run_issuer(&plan.issuer), - "the run issuer {} is not a loopback URL of the form http://127.0.0.1:", - plan.issuer + "the run issuer is not a loopback URL of the form http://127.0.0.1:" ); + write_bound_casework_project(plan, project, bound, document, &plan.issuer) +} + +fn write_bound_casework_project( + plan: &Plan, + project: &Path, + bound: &Path, + mut document: Value, + issuer: &str, +) -> Result<()> { for bound_producer in guarded_producers(plan) { let entry = &mut document["trustedProducers"][bound_producer.producer]; - entry["issuer"] = json!(plan.issuer); + entry["issuer"] = json!(issuer); if bound_producer.initiator.is_some() { - entry["trustedInitiatorIssuer"] = json!(plan.issuer); + entry["trustedInitiatorIssuer"] = json!(issuer); } } copy_project(project, bound)?; @@ -4087,6 +4484,92 @@ fn bind_casework_run_issuer(plan: &Plan, project: &Path, bound: &Path) -> Result ) } +/// Avoid a collision caused only by a stand-in. Startup checks the allocated +/// issuer on the private copy it will pair and package. +fn casework_projection_issuer(policy: &Value) -> Result { + let authored_issuers: BTreeSet<_> = policy["trustedProducers"] + .as_object() + .into_iter() + .flat_map(serde_json::Map::values) + .filter_map(|producer| producer["issuer"].as_str()) + .collect(); + (1..=u16::MAX) + .map(|port| format!("http://127.0.0.1:{port}")) + .find(|issuer| !authored_issuers.contains(issuer.as_str())) + .context("no unused stand-in issuer for Casework review inspection") +} + +fn inspect_projected_casework( + tool: &Path, + project: &SelectedProduct, + terminate: &AtomicBool, +) -> Result<()> { + let report = strict_tool_report( + tool, + "caseworkctl", + "check", + &[project.root.as_os_str()], + terminate, + ); + check_projected_casework(project, report, terminate.load(Ordering::Relaxed)) +} + +/// Reuse Casework's project authority checks after rebinding. Report the +/// native refusal class at its plan field without carrying producer values. +fn check_projected_casework( + project: &SelectedProduct, + report: Result<(ExitStatus, Value)>, + interrupted: bool, +) -> Result<()> { + let unavailable = |error| { + if interrupted { + return error; + } + inspection_unavailable( + Product::Casework, + &project.field, + "check the Casework project with the run issuer", + error, + ) + }; + let (status, report) = report.map_err(unavailable)?; + if status.success() + && report["apiVersion"] == CASEWORK_REPORT_API_VERSION + && report["kind"] == "CaseworkReport" + && report["command"] == "check" + && report["status"] == "complete" + && report["ok"] == true + { + return Ok(()); + } + if status.code() == Some(1) && casework_domain_refusal(&report, "check") { + let duplicate = report["diagnostics"] + .as_array() + .into_iter() + .flatten() + .any(|finding| { + finding["severity"] == "error" + && finding["code"] == "casework.review-producer.duplicate-principal" + }); + if duplicate { + return Err(plan::SemanticRefusal::new( + "/bindings/bregReviewAuthority/runIssuerBinding", + "The run issuer gives two Casework producers the same profile, issuer and subject.", + "Give each producer a distinct profile or subject and align its development binding.", + ).into()); + } + return Err(plan::SemanticRefusal::new( + &project.field, + "Casework refused the project with the projected run issuer.", + "Correct the Casework producer bindings and run the development check again.", + ) + .into()); + } + Err(unavailable(anyhow::anyhow!( + "caseworkctl check did not report a project result" + ))) +} + /// Reads the Casework project's `casework.yaml` and refuses, at the dev.yaml /// pointer, a run issuer binding that does not match the trusted producer it /// names. `check` runs this before any product starts; `start` runs it again @@ -4118,10 +4601,6 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { let run_issuer_binding = format!("{binding}/runIssuerBinding"); let identity = &plan.people[alias]; let grant = &identity.grants[&Product::Casework]; - let person = format!( - "/people/{}", - registry_platform_yaml::escape_pointer_segment(alias) - ); let producer = document["trustedProducers"][id].clone(); if !producer.is_object() { return Err(refuse( @@ -4156,21 +4635,7 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { "Set expectedSubject and the identity's subject to the producer's subject.", )); } - let required = document["accessProfiles"][&expected.expected_profile]["requiredScopes"] - .as_array() - .cloned() - .unwrap_or_default(); - if let Some(missing) = required - .iter() - .filter_map(Value::as_str) - .find(|scope| !grant.scopes.iter().any(|granted| granted == scope)) - { - return Err(refuse( - format!("{person}/roles"), - &format!("The identity's Casework grant lacks the scope {missing} that the producer's profile requires."), - "Assign a role whose Casework profile supplies the required scope.", - )); - } + check_casework_producer_scopes(alias, grant, &document)?; if let Some(initiator) = initiator { if producer["trustedInitiatorIssuer"].as_str() != Some(initiator.expected_issuer.as_str()) @@ -4186,7 +4651,7 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { Ok(document) } -/// Refuses, at the dev.yaml pointer, a Coordinator review producer the run +/// Refuses, at the authored field, a Coordinator review producer the run /// cannot bind exactly: a `casework-review-producer` connection without the /// binding, a binding whose connection, producer, profile or completion does /// not match the Coordinator runtime and `casework.yaml`, or a producer whose @@ -4284,6 +4749,19 @@ fn checked_coordinator_review_runtime(plan: &Plan, casework: &Path, runtime: &Va )); } if completion["recipientBinding"].as_str() != Some(recipient) { + if plan.automatic_review { + let source = casework.join("casework.yaml"); + let tree = authored_tree(&source)?; + return Err(Report::new(vec![casework_completion_diagnostic( + &source, + &tree, + &binding.producer, + "recipientBinding", + "The completion recipientBinding must match the bound Coordinator connection.", + "Use the same recipientBinding in the producer's completion and the Coordinator connection.", + )]) + .into()); + } return Err(refuse( format!("{BINDING}/connection"), "The Coordinator connection's completion recipientBinding is not the one casework.yaml names for this producer.", @@ -4847,12 +5325,14 @@ mod tests { .unwrap() .push(json!({"id": "reviewer", "principalClaim": "different"})); assert!(casework_report_facts(&report) - .unwrap_err() + .err() + .expect("duplicate profiles are refused") .to_string() .contains("duplicate")); report["command"] = json!("check"); assert!(casework_report_facts(&report) - .unwrap_err() + .err() + .expect("a different report command is refused") .to_string() .contains("incompatible report")); } @@ -4897,7 +5377,7 @@ mod tests { fn casework_authority_restrictions_are_typed_and_located() { let facts = |principal: &str| CaseworkFacts { profiles: BTreeMap::from([("reviewer".to_owned(), principal.to_owned())]), - trusted_producers: BTreeSet::new(), + trusted_producers: BTreeMap::new(), context_providers: BTreeMap::new(), }; @@ -4935,12 +5415,173 @@ mod tests { id: "proposal-context".to_owned(), identity: "context-reader".to_owned(), action: "review-action".to_owned(), + deployment_ref: None, }), coordinator_review_producer: None, coordinator_breg_client: None, } } + #[test] + fn automatic_review_agrees_with_the_machine_grant_and_breg_initiator() { + let mut plan = authority_plan(json!({}), json!({})); + plan.automatic_review = true; + plan.bindings = product_bindings(); + plan.bindings + .breg_review_authority + .as_mut() + .unwrap() + .identity = "operator".to_owned(); + plan.bindings + .casework_context_provider + .as_mut() + .unwrap() + .identity = "operator".to_owned(); + let breg = BregAuthority { + principal: breg_principal(&plan, &BTreeSet::from(["person_handle".to_owned()])) + .unwrap(), + purpose: false, + named_clients: BTreeSet::new(), + requires_postgis: false, + encrypts_fields: false, + }; + let mut report = json!({ + "apiVersion": CASEWORK_REPORT_API_VERSION, + "kind": "CaseworkReport", "command": "explain", "status": "complete", "ok": true, + "accessProfiles": [{"id": "reviewer", "principalClaim": "machine_handle"}], + "trustedProducers": [{ + "id": "review-producer", "issuer": plan.issuer, "profile": "reviewer", + "subject": "operator", "trustedInitiatorIssuer": plan.issuer, + "trustedInitiatorPrincipalClaim": "person_handle" + }], + "contextProviders": [] + }); + let policy = json!({ + "accessProfiles": {"reviewer": {"requiredScopes": ["casework:staff"]}} + }); + plan.people + .get_mut("operator") + .unwrap() + .grants + .get_mut(&Product::Casework) + .unwrap() + .scopes + .push("casework:staff".to_owned()); + let validate = |plan: &Plan, report: &Value| { + validate_automatic_review_producer( + plan, + &casework_report_facts(report).unwrap(), + Some(&breg), + &policy, + ) + }; + validate(&plan, &report).unwrap(); + let grant = plan + .people + .get_mut("operator") + .unwrap() + .grants + .get_mut(&Product::Casework) + .unwrap(); + grant.scopes.clear(); + let missing_scope = validate(&plan, &report).unwrap_err().to_string(); + assert!( + missing_scope.contains("/people/operator/roles"), + "{missing_scope}" + ); + assert!(!missing_scope.contains("casework:staff"), "{missing_scope}"); + plan.automatic_review = false; + validate(&plan, &report).unwrap(); + plan.automatic_review = true; + plan.people + .get_mut("operator") + .unwrap() + .grants + .get_mut(&Product::Casework) + .unwrap() + .scopes + .push("casework:staff".to_owned()); + + // A held secondary profile is never the profile BReg writes into the request. + plan.people + .get_mut("operator") + .unwrap() + .grants + .get_mut(&Product::Casework) + .unwrap() + .additional_profiles + .push("profile-canary".to_owned()); + for (member, value, pointer, reason) in [ + ( + "profile", + "profile-canary", + "/bindings/bregReviewAuthority/identity", + "Casework grant profile", + ), + ( + "subject", + "subject-canary", + "/bindings/bregReviewAuthority/identity", + "subject", + ), + ( + "issuer", + "https://producer-canary.example.invalid", + "/issuer", + "producer's issuer", + ), + ( + "trustedInitiatorIssuer", + "https://initiator-canary.example.invalid", + "/issuer", + "initiator issuer", + ), + ( + "trustedInitiatorPrincipalClaim", + "claim-canary", + "/bindings/bregReviewAuthority/producer", + "BReg principal claim", + ), + ] { + let mut mismatch = report.clone(); + mismatch["trustedProducers"][0][member] = json!(value); + let error = validate(&plan, &mismatch).unwrap_err().to_string(); + assert!( + error.starts_with(&format!("dev.yaml {pointer}: ")), + "{error}" + ); + assert!(error.contains(reason) && !error.contains(value), "{error}"); + + plan.automatic_review = false; + validate(&plan, &mismatch).unwrap(); + plan.automatic_review = true; + } + + plan.issuer = "run".to_owned(); + let missing_guard = validate(&plan, &report).unwrap_err().to_string(); + assert!(missing_guard.contains("/bindings/bregReviewAuthority/runIssuerBinding")); + let issuer = &report["trustedProducers"][0]["issuer"]; + plan.bindings.breg_review_authority.as_mut().unwrap().run_issuer_binding = + Some(serde_json::from_value(json!({ + "producer": {"expectedIssuer": issuer, "expectedProfile": "reviewer", "expectedSubject": "operator"}, + "initiator": {"expectedIssuer": issuer, "trust": "run-test-people"} + })).unwrap()); + validate(&plan, &report).unwrap(); + + let producer = report["trustedProducers"][0].as_object_mut().unwrap(); + producer.remove("trustedInitiatorIssuer"); + producer.remove("trustedInitiatorPrincipalClaim"); + plan.bindings + .breg_review_authority + .as_mut() + .unwrap() + .run_issuer_binding + .as_mut() + .unwrap() + .initiator = None; + validate(&plan, &report).unwrap(); + } + /// A Casework and Coordinator plan whose Coordinator `review` connection is /// bound as the `coordinator` producer, with its casework.yaml and the /// Coordinator runtime.yaml. @@ -5002,6 +5643,146 @@ mod tests { (casework, project) } + #[test] + fn automatic_review_accepts_the_rendered_coordinator_hook_and_breg_polling() { + let root = tempfile::tempdir().unwrap(); + let root = root.path().canonicalize().unwrap(); + let (plan, mut policy, mut runtime) = coordinator_producer_fixture(); + let mut plan: Plan = serde_json::from_value(plan).unwrap(); + plan.automatic_review = true; + plan.products[0].project = PathBuf::from("project"); + policy["trustedProducers"]["breg-producer"] = json!({}); + let (casework, coordinator) = coordinator_producer_projects(&root, &policy, &runtime); + + check_automatic_review_completions(&root, &plan).unwrap(); + checked_coordinator_review_producer(&plan, &casework, &coordinator).unwrap(); + let mut sender = json!({}); + super::super::bindings::render_for_check(&plan, Product::Casework, &mut sender); + super::super::bindings::render_for_check(&plan, Product::Coordinator, &mut runtime); + let completion = &policy["trustedProducers"]["coordinator"]["completion"]; + let destination = completion["destinationId"].as_str().unwrap(); + let hook = &sender["destinations"]["hooks"][destination]; + let receiver = &runtime["connections"]["review"]["completion"]; + assert_eq!( + sender["destinations"]["hooks"].as_object().unwrap().len(), + 1 + ); + assert_eq!( + hook["url"], + format!( + "{}{}", + super::super::bindings::CHECK_ORIGIN, + super::super::bindings::REVIEW_COMPLETIONS_PATH + ) + ); + assert!(hook["hmacSha256KeyRef"].is_string()); + assert_eq!(hook["hmacSha256KeyRef"], receiver["hmacSha256KeyRef"]); + assert_eq!(completion["recipientBinding"], receiver["recipientBinding"]); + + // A shared producer ID must not divert BReg's review results to the + // Coordinator even if the configured destination and recipient match. + let mut breg = product_bindings().breg_review_authority.unwrap(); + breg.producer = plan + .bindings + .coordinator_review_producer + .as_ref() + .unwrap() + .producer + .clone(); + plan.bindings.breg_review_authority = Some(breg); + let error = check_automatic_review_completions(&root, &plan).unwrap_err(); + let report = error.downcast_ref::().unwrap(); + assert_eq!( + report.diagnostics()[0].path, + "/trustedProducers/coordinator/completion/destinationId" + ); + assert!(report.diagnostics()[0] + .message + .contains("BReg review producer uses polling")); + } + + #[test] + fn automatic_review_without_coordinator_has_no_completion_destination() { + let scratch = tempfile::tempdir().unwrap(); + let root = scratch.path().canonicalize().unwrap(); + let mut plan = plan::paired_test_plan(); + plan.automatic_review = true; + plan.products[1].project = PathBuf::from("project"); + let policy = json!({"trustedProducers": {"registry": {}}}); + let project = write_casework_project(&root, &policy); + check_automatic_review_completions(&root, &plan).unwrap(); + let mut config = json!({}); + super::super::bindings::render_for_check(&plan, Product::Casework, &mut config); + assert!(config.get("destinations").is_none()); + + let source = project.join("casework.yaml"); + let mut policy = policy; + policy["trustedProducers"]["registry"]["completion"] = json!({ + "destinationId": "unserved-canary", "recipientBinding": "recipient-canary" + }); + fs::write(&source, serde_norway::to_string(&policy).unwrap()).unwrap(); + let error = check_automatic_review_completions(&root, &plan).unwrap_err(); + let report = error.downcast_ref::().unwrap(); + assert_eq!( + report.diagnostics()[0].path, + "/trustedProducers/registry/completion/destinationId" + ); + assert!(!error.to_string().contains("-canary")); + plan.automatic_review = false; + check_automatic_review_completions(&root, &plan).unwrap(); + } + + #[test] + fn automatic_review_refuses_all_unserved_completion_declarations_at_the_policy() { + for (producer, destination, recipient, member) in [ + ( + "other-producer", + "unserved-canary", + "coordinator-v1", + "destinationId", + ), + ( + "breg-producer", + "coordinator-wake", + "coordinator-v1", + "destinationId", + ), + ( + "coordinator", + "coordinator-wake", + "recipient-canary", + "recipientBinding", + ), + ] { + let root = tempfile::tempdir().unwrap(); + let root = root.path().canonicalize().unwrap(); + let (plan, mut policy, runtime) = coordinator_producer_fixture(); + let mut plan: Plan = serde_json::from_value(plan).unwrap(); + plan.automatic_review = true; + plan.products[0].project = PathBuf::from("project"); + policy["trustedProducers"][producer]["completion"] = json!({ + "destinationId": destination, "recipientBinding": recipient + }); + let (casework, coordinator) = coordinator_producer_projects(&root, &policy, &runtime); + + let error = check_automatic_review_completions(&root, &plan) + .and_then(|()| checked_coordinator_review_producer(&plan, &casework, &coordinator)) + .unwrap_err(); + let report = error + .downcast_ref::() + .unwrap(); + let finding = &report.diagnostics()[0]; + assert_eq!( + finding.path, + format!("/trustedProducers/{producer}/completion/{member}") + ); + let source = finding.source.as_ref().unwrap(); + assert!(source.file.ends_with("casework.yaml")); + assert!(source.line.is_some() && source.column.is_some()); + assert!(!error.to_string().contains("-canary")); + } + } + #[test] fn a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer() { type Break = fn(&mut Value, &mut Value, &mut Value); @@ -5362,6 +6143,69 @@ mod tests { } } + #[test] + fn automatic_review_requires_the_selected_breg_status_grant() { + let mut plan = plan::paired_test_plan(); + plan.automatic_review = true; + let mut facts = BregFacts::default(); + for key in [ + ("another-action", "casework", "review-status"), + ("correct-status", "another-authority", "review-status"), + ("correct-status", "casework", "another-profile"), + ] { + facts.review_status_scopes.insert( + (key.0.to_owned(), key.1.to_owned(), key.2.to_owned()), + BTreeSet::new(), + ); + } + let error = validate_automatic_review_status(&plan, &facts) + .unwrap_err() + .to_string(); + assert!(error.contains("/people/context-status/roles"), "{error}"); + assert!(error.contains("get-review-status"), "{error}"); + assert!(!error.contains("correct-status"), "{error}"); + plan.automatic_review = false; + validate_automatic_review_status(&plan, &facts).unwrap(); + plan.automatic_review = true; + + let key = ( + "correct-status".to_owned(), + "casework".to_owned(), + "review-status".to_owned(), + ); + facts + .review_status_scopes + .insert(key.clone(), BTreeSet::from(["scope-canary".to_owned()])); + let error = validate_automatic_review_status(&plan, &facts) + .unwrap_err() + .to_string(); + assert!( + error.contains("required scopes") && !error.contains("scope-canary"), + "{error}" + ); + facts + .review_status_scopes + .insert(key, BTreeSet::from(["registry:review-status".to_owned()])); + validate_automatic_review_status(&plan, &facts).unwrap(); + + let grant = plan + .people + .get_mut("context-status") + .unwrap() + .grants + .get_mut(&Product::Breg) + .unwrap(); + // A BReg synthetic token fixture can omit this claim from the final grant. + grant.claims.remove(ACTOR_KIND_CLAIM).unwrap(); + let error = validate_automatic_review_status(&plan, &facts) + .unwrap_err() + .to_string(); + assert!(error.contains("/people/context-status/roles"), "{error}"); + assert!(error.contains("service actor kind"), "{error}"); + plan.automatic_review = false; + validate_automatic_review_status(&plan, &facts).unwrap(); + } + #[test] fn casework_binding_ids_use_the_existing_explain_facts() { let bindings = product_bindings(); @@ -5441,7 +6285,7 @@ mod tests { } #[test] - fn only_a_casework_refusal_at_the_binding_refuses_the_binding() { + fn casework_binding_check_distinguishes_task_authority_from_deferred_refusals() { let report = |status: &str, diagnostics: Value| { json!({ "apiVersion": "id.registrystack.org/formats/casework/report/v1", @@ -5489,6 +6333,15 @@ mod tests { )]), refused(""), ), + ( + Some(1), + json!([diagnostic( + runtime, + "casework.runtime.invalid-task-authority", + "/taskAuthority" + )]), + BindingCheck::TaskAuthorityRequired, + ), // Another provider, Casework rules about the stand-in files or // the unpaired project, and project diagnostics are not this // binding's. @@ -5505,6 +6358,7 @@ mod tests { "casework.runtime.context-providers-mismatch", "/contextProviders" ), + diagnostic(runtime, "casework.runtime.invalid-audit", "/audit/path"), diagnostic( "CaseworkProject", "casework.project.invalid", @@ -5790,7 +6644,8 @@ mod tests { ]}}] }); assert!(casework_report_facts(&report) - .unwrap_err() + .err() + .expect("an absent profile list is refused") .to_string() .contains("did not report access profiles")); } @@ -6156,6 +7011,58 @@ mod tests { project } + #[test] + fn projected_casework_uses_the_native_principal_uniqueness_check() { + let (plan, mut casework) = run_issuer_fixture(false); + let mut plan: Plan = serde_json::from_value(plan).unwrap(); + plan.products[1].project = PathBuf::from("project"); + casework["trustedProducers"]["other-producer"] = json!({ + "issuer": plan.issuer, "profile": "review-producer", "subject": "breg-producer" + }); + let scratch = tempfile::tempdir().unwrap(); + let root = scratch.path().canonicalize().unwrap(); + let project = write_casework_project(&root, &casework); + let tool = root.join("caseworkctl"); + crate::write_executable_fixture(&tool, r#"#!/usr/bin/env bash +set -euo pipefail +[[ "$1 $2 $3" == '--format json check' ]] +[[ "$4" == */casework-bound ]] +cat <<'EOF' +{"apiVersion":"id.registrystack.org/formats/casework/report/v1","kind":"CaseworkReport","command":"check","status":"domain-refusal","ok":false,"diagnostics":[{"severity":"error","code":"casework.review-producer.duplicate-principal","path":"/trustedProducers/other-producer","message":"diagnostic-canary","suggestedAction":"Correct it."}]} +EOF +exit 1 +"#).unwrap(); + let run = root.join("run"); + private_directory(&run).unwrap(); + let bound = SelectedProduct { + field: "/products/1/project".to_owned(), + root: run.join("casework-bound"), + }; + bind_casework_run_issuer(&plan, &project, &bound.root).unwrap(); + let terminate = AtomicBool::new(false); + let error = inspect_projected_casework(&tool, &bound, &terminate) + .unwrap_err() + .to_string(); + assert!( + error.contains("/bindings/bregReviewAuthority/runIssuerBinding"), + "{error}" + ); + assert!( + error.contains("same profile, issuer and subject"), + "{error}" + ); + assert!(!error.contains("diagnostic-canary"), "{error}"); + assert_eq!( + authored_document(&project.join("casework.yaml")).unwrap(), + casework + ); + let projected = authored_document(&run.join("casework-bound/casework.yaml")).unwrap(); + assert_eq!( + projected["trustedProducers"]["producer"]["issuer"], + casework["trustedProducers"]["other-producer"]["issuer"] + ); + } + #[test] fn casework_run_issuer_binding_refuses_each_mismatch_at_its_pointer() { type Break = fn(&mut Value, &mut Value); @@ -6911,6 +7818,7 @@ mod tests { application_root: None, application_node: None, preview: None, + automatic_review: false, plan: serde_json::from_value(json!({ "issuer": "https://issuer.example.invalid", "products": [{"product": "breg", "project": ".", "audience": "registry"}], @@ -7212,7 +8120,9 @@ printf '%s' '{"ok":true,"explanation":{"deliveries":[{"destinationId":"declared" let terminate = AtomicBool::new(false); let missing = Path::new("/nonexistent/caseworkctl"); - let error = explain_casework_facts(missing, Path::new("."), &terminate).unwrap_err(); + let error = explain_casework_facts(missing, Path::new("."), &terminate) + .err() + .expect("the owning tool is absent"); let failed = inspection_failed( Product::Casework, "products[0]", diff --git a/crates/registry-rstack-dev/src/roles.rs b/crates/registry-rstack-dev/src/roles.rs index 40e4df2679..7b58316ebf 100644 --- a/crates/registry-rstack-dev/src/roles.rs +++ b/crates/registry-rstack-dev/src/roles.rs @@ -165,6 +165,7 @@ pub(super) fn resolve( authored: Plan, offline_check: bool, ) -> Result<(Plan, Option)> { + super::products::check_automatic_review_completions(root, &authored)?; let Plan { issuer, external_jwks_uri, @@ -175,6 +176,7 @@ pub(super) fn resolve( people, journey_file, bindings, + automatic_review, schema_test_people, application, preview, @@ -270,6 +272,7 @@ pub(super) fn resolve( people: resolved, journey_file, bindings, + automatic_review, schema_test_people, application, preview, diff --git a/crates/registry-rstack-dev/src/roles/token_shapes.rs b/crates/registry-rstack-dev/src/roles/token_shapes.rs index 6fb2aa6343..97d4fefd3b 100644 --- a/crates/registry-rstack-dev/src/roles/token_shapes.rs +++ b/crates/registry-rstack-dev/src/roles/token_shapes.rs @@ -121,6 +121,7 @@ fn capture( application_root: None, application_node: None, preview: None, + automatic_review: false, plan, scenarios: Vec::new(), scenario_digest: String::new(), diff --git a/crates/registry-rstack-service/Cargo.toml b/crates/registry-rstack-service/Cargo.toml index 2b3a4cad87..dd6bca9ea6 100644 --- a/crates/registry-rstack-service/Cargo.toml +++ b/crates/registry-rstack-service/Cargo.toml @@ -15,4 +15,4 @@ workspace = true schema = ["registry-platform-config/schema"] [dependencies] -registry-platform-config.workspace = true +registry-platform-config = { workspace = true, features = ["service-authoring"] } diff --git a/crates/registry-rstack-service/src/lib.rs b/crates/registry-rstack-service/src/lib.rs index 887f14d6ac..0d6ed2d9ac 100644 --- a/crates/registry-rstack-service/src/lib.rs +++ b/crates/registry-rstack-service/src/lib.rs @@ -1,4 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Tool-side API for the shared service compiler. +pub use registry_platform_config::service_authoring::{ + inspect_review, review_tool_failure, run_review_tool, ReviewToolFailure, ReviewToolOutput, +}; pub use registry_platform_config::service_compiler::*; diff --git a/crates/registry-rstack/Cargo.toml b/crates/registry-rstack/Cargo.toml index 5ffb2f9677..f86dde7348 100644 --- a/crates/registry-rstack/Cargo.toml +++ b/crates/registry-rstack/Cargo.toml @@ -28,6 +28,7 @@ registry-thunderid-tooling.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true +signal-hook.workspace = true rustix.workspace = true tempfile.workspace = true ureq.workspace = true diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index 39b2fa51e0..b7bbfcf9f3 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -13,12 +13,16 @@ use registry_platform_config::{ use registry_platform_yaml::{Diagnostic, Report}; use registry_rstack_service as service_plan; use serde_json::{json, Value}; -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::fs; use std::io::{self, Write}; use std::os::unix::process::CommandExt; use std::path::PathBuf; use std::process::Command as ProcessCommand; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; const PRODUCTS: [&str; 10] = [ "breg", @@ -1177,19 +1181,50 @@ fn execute(cli: Cli, format_supplied: bool, evidence_junit: bool) -> Result<(), session_routes, session_route, }, - }) => match service_plan::plan( - file, - service_plan::Options { - workspace_root: workspace_root.as_deref(), - dev_config: dev_config.as_deref(), - checked_routes: session_routes.as_deref(), - route_selections: session_route, - for_client: false, - }, - ) { - Ok(plan) => match format { + }) => { + let terminate = Arc::new(AtomicBool::new(false)); + for signal in [signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT] { + signal_hook::flag::register(signal, Arc::clone(&terminate)).map_err(|error| { + CliFailure::operational(format!( + "cannot install service plan signal handler: {error}" + )) + })?; + } + let plan = match service_plan::plan( + file, + service_plan::Options { + workspace_root: workspace_root.as_deref(), + dev_config: dev_config.as_deref(), + checked_routes: session_routes.as_deref(), + route_selections: session_route, + for_client: false, + inspect_review: Some(&|document, products| { + service_plan::inspect_review(document, products, |product, args| { + service_review_tool(&cli, product, args, &terminate) + }) + }), + }, + ) { + Ok(plan) => plan, + Err(report) => return refuse_service(report, format), + }; + if terminate.load(Ordering::Relaxed) { + return Err(CliFailure::operational( + "service planning interrupted".into(), + )); + } + match format { ReportFormat::Human => { reportln!("Resolved service declaration {}", file.display()); + if let Some(review) = &plan.review_wiring { + reportln!( + "BReg Action {} in {} uses Casework policy {} and context provider {}.", + review.action.as_str(), + review.breg_project.as_str(), + review.policy.as_str(), + review.context_provider.as_str(), + ); + } reportln!("Use --format json to read the development and client inputs."); } ReportFormat::Json => reportln!( @@ -1197,9 +1232,8 @@ fn execute(cli: Cli, format_supplied: bool, evidence_junit: bool) -> Result<(), serde_json::to_string(&plan) .map_err(|error| CliFailure::operational(error.to_string()))? ), - }, - Err(report) => return refuse_service(report, format), - }, + } + } Some(Command::Client { command: ClientCommand::Generate(arguments), }) => generate_client(&cli, arguments, format)?, @@ -1276,6 +1310,11 @@ fn execute(cli: Cli, format_supplied: bool, evidence_junit: bool) -> Result<(), } fn refuse_service(report: Report, format: ReportFormat) -> Result<(), CliFailure> { + let exit = if service_plan::review_tool_failure(&report).is_some() { + 3 + } else { + 1 + }; match format { ReportFormat::Human => { write!(io::stderr().lock(), "{}", report.render_human()).map_err(|error| { @@ -1287,7 +1326,7 @@ fn refuse_service(report: Report, format: ReportFormat) -> Result<(), CliFailure json!({"ok": false, "diagnostics": report.to_json_value()}) ), } - Err(CliFailure::reported(1)) + Err(CliFailure::reported(exit)) } fn generate_client( @@ -1460,6 +1499,26 @@ fn driven_tool(cli: &Cli, product: &ProductSpec) -> Result, F })) } +fn service_review_tool( + cli: &Cli, + product: &str, + args: &[&OsStr], + terminate: &AtomicBool, +) -> Result { + use service_plan::ReviewToolFailure; + if terminate.load(Ordering::Relaxed) { + return Err(ReviewToolFailure::Interrupted); + } + let spec = identity::PRODUCTS + .iter() + .find(|spec| spec.name == product) + .ok_or(ReviewToolFailure::Unavailable)?; + let tool = driven_tool(cli, spec) + .map_err(|_| ReviewToolFailure::Failed)? + .ok_or(ReviewToolFailure::Unavailable)?; + service_plan::run_review_tool(&tool.path, args, terminate) +} + fn product_help_request( arguments: &[OsString], default_format: ReportFormat, @@ -2707,6 +2766,16 @@ fn set_selected_generation_environment( mod tests { use super::*; + #[test] + fn interrupted_service_plan_skips_review_tool_resolution() { + let cli = Cli::try_parse_from(["rstack"]).unwrap(); + let terminate = AtomicBool::new(true); + assert!(matches!( + service_review_tool(&cli, "unknown", &[], &terminate), + Err(service_plan::ReviewToolFailure::Interrupted) + )); + } + #[test] fn dev_check_owner_report_requires_an_explicit_exclusive_format() { let parse = |args: &[&str]| { diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 9dfb8962bb..49dfb3c544 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -2377,6 +2377,381 @@ journeyFile: dev-journeys.yaml\n", assert!(!state.exists()); } +#[test] +fn dev_check_uses_service_review_wiring_for_abbreviated_bindings() { + let scratch = tempfile::tempdir().unwrap(); + let project = scratch.path().join("project"); + let state = scratch.path().join("state"); + copy_tree( + &example_project("breg/acceptance/reviewed-evidence-journey"), + &project, + ); + let tool = host("caseworkctl"); + let check = || check_with_casework_tool(&project, &state, &tool); + + let legacy = check(); + assert!(legacy.status.success(), "{legacy:?}"); + + let read = |file: &std::path::Path| { + registry_platform_yaml::Reader::new(utf8(file)) + .scan(&fs::read(file).unwrap()) + .unwrap() + .unwrap() + .to_json_value() + }; + let dev_file = project.join("dev.yaml"); + let service_file = project.join("service.yaml"); + let mut dev = read(&dev_file); + let mut service = read(&service_file); + service["products"] = dev.as_object_mut().unwrap().remove("products").unwrap(); + fs::write(service_file, serde_norway::to_string(&service).unwrap()).unwrap(); + for (binding, field) in [ + ("bregReviewAuthority", "id"), + ("caseworkContextProvider", "id"), + ("caseworkContextProvider", "action"), + ] { + assert!(dev["bindings"][binding] + .as_object_mut() + .unwrap() + .remove(field) + .is_some()); + } + fs::write(&dev_file, serde_norway::to_string(&dev).unwrap()).unwrap(); + + let migrated = check(); + assert!(migrated.status.success(), "{migrated:?}"); + assert!(migrated.stderr.is_empty(), "{migrated:?}"); + assert!(!state.exists()); + + dev["bindings"]["bregReviewAuthority"]["producer"] = "untrusted-producer".into(); + fs::write(&dev_file, serde_norway::to_string(&dev).unwrap()).unwrap(); + let refused = check(); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).unwrap(); + assert_eq!( + report["diagnostics"][0]["code"], + "rstack.service.review-binding" + ); + assert_eq!( + report["diagnostics"][0]["path"], + "/bindings/bregReviewAuthority/producer" + ); + assert!(!state.exists()); +} + +#[test] +fn dev_refuses_the_task_authority_casework_requires_before_provisioning() { + let scratch = tempfile::tempdir().unwrap(); + let project = scratch.path().join("project"); + let state = scratch.path().join("state"); + copy_tree( + &example_project("breg/acceptance/reviewed-evidence-journey"), + &project, + ); + let tool = scratch.path().join("caseworkctl"); + symlink( + host("caseworkctl"), + scratch.path().join("caseworkctl-native"), + ) + .unwrap(); + fs::write( + &tool, + r#"#!/usr/bin/env bash +set -euo pipefail +if [[ $# -eq 6 && $3 == check && $5 == --runtime-config ]]; then + "${0%/*}/caseworkctl-native" "$@" | tee "${0%/*}/casework-check.json" +else + exec "${0%/*}/caseworkctl-native" "$@" +fi +"#, + ) + .unwrap(); + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); + + let accepted = check_with_casework_tool(&project, &state, &tool); + assert!(accepted.status.success(), "{accepted:?}"); + assert!(accepted.stderr.is_empty(), "{accepted:?}"); + assert!(!state.exists()); + + let policy = project.join("casework/casework.yaml"); + let authored = fs::read_to_string(&policy).unwrap(); + fs::write( + &policy, + format!( + "{authored}{}", + r#" +teams: + review-team: + label: Review team + serves: [reviews] + memberProfiles: [staff] + supervisorProfiles: [supervisor] +taskTemplates: + synthetic-booking: + version: "1" + label: Book an appointment + eligibleTeams: [review-team] + eligibleProfiles: [staff] + source: registry + reviewPolicies: [status-review] + agent: {issuer: https://issuer.example.test, subject: synthetic-agent-marker} + client: producer + resource: urn:synthetic:booking-marker + scopes: [scheduling:read] + purpose: review + bounds: + type: scheduling + permissions: + - {service: status-review, location: review-desk, actions: [appointment.create]} + subjects: {} + lifetimeSeconds: 900 +"# + ), + ) + .unwrap(); + // The role facts reader can use an authored authority. The dev runtime + // renderer supplies neither its configuration nor its signing key. + fs::write( + project.join("casework/runtime.yaml"), + r#"taskAuthority: + issuer: https://synthetic-authority-marker.example.test + exchangeAudience: urn:synthetic:task-exchange + signingKeyRef: secret:file/synthetic-signing-key-marker + statusClients: {} +"#, + ) + .unwrap(); + + let checked = check_with_casework_tool(&project, &state, &tool); + let owner: serde_json::Value = + serde_json::from_slice(&fs::read(scratch.path().join("casework-check.json")).unwrap()) + .unwrap(); + assert_eq!(owner["status"], "domain-refusal", "{owner}"); + assert!( + owner["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|finding| { + finding["severity"] == "error" + && finding["artifact"] == "CaseworkRuntimeConfig" + && finding["code"] == "casework.runtime.invalid-task-authority" + && finding["path"] == "/taskAuthority" + }), + "{owner}" + ); + + let message = "Casework requires taskAuthority for this project, and the development runner cannot supply it."; + let remedy = "Select a Casework project without taskTemplates for this run, or deploy Casework with its own configured task authority."; + assert_eq!(checked.status.code(), Some(1), "{checked:?}"); + assert!(checked.stderr.is_empty(), "{checked:?}"); + let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); + assert_eq!(report["status"], "domain-refusal", "{report}"); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "rstack.dev.invalid-plan", "{report}"); + assert_eq!(diagnostic["path"], "/products/casework/path", "{report}"); + assert_eq!(diagnostic["message"], message, "{report}"); + assert_eq!(diagnostic["suggestedAction"], remedy, "{report}"); + + let started = start_with_casework_tool(&project, &state, &tool); + assert_eq!(started.status.code(), Some(1), "{started:?}"); + assert!(started.stderr.is_empty(), "{started:?}"); + let start_report: serde_json::Value = serde_json::from_slice(&started.stdout).unwrap(); + assert_error_envelope(&start_report, "domain"); + let failure = start_report["error"]["message"].as_str().unwrap(); + assert!(failure.contains(message), "{start_report}"); + assert!(failure.contains(remedy), "{start_report}"); + for canary in [ + "synthetic-agent-marker", + "booking-marker", + "synthetic-authority-marker", + "synthetic-signing-key-marker", + ] { + assert!(!report.to_string().contains(canary), "{report}"); + assert!(!start_report.to_string().contains(canary), "{start_report}"); + } + assert!(!state.exists()); +} + +#[test] +fn native_dev_review_wiring_pins_the_policy_and_respects_the_authored_producer() { + let scratch = tempfile::tempdir().unwrap(); + let project = scratch.path().join("project"); + let state = scratch.path().join("state"); + copy_tree( + &example_project("breg/acceptance/reviewed-evidence-journey"), + &project, + ); + let breg = project.join("registry"); + let casework = project.join("casework"); + let bregctl = host("bregctl"); + let caseworkctl = host("caseworkctl"); + let check = || check_with_casework_tool(&project, &state, &caseworkctl); + let assert_checked = |output: std::process::Output| { + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["status"], "complete", "{report}"); + assert!(!state.exists()); + }; + assert_checked(check()); + + let explain_policy = || { + let output = Command::new(&caseworkctl) + .args(["--format", "json", "explain"]) + .arg(&casework) + .env_remove("REGISTRY_STACK_POSTURE") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["status"], "complete", "{report}"); + assert_eq!( + report["reviewPolicies"][0]["binding"]["id"], + "status-review" + ); + report + }; + let export_context = |destination| { + let output_dir = scratch.path().join(destination); + let output = Command::new(&bregctl) + .args(["--format", "json", "generate", "schemas"]) + .arg(&breg) + .arg("--output") + .arg(&output_dir) + .env_remove("REGISTRY_STACK_POSTURE") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let exports = output_dir.join("generated/review-context-schemas"); + ( + fs::read(exports.join("index.json")).unwrap(), + fs::read(exports.join("correct-status.schema.json")).unwrap(), + ) + }; + let original_policy = explain_policy(); + let original_context = export_context("original-schemas"); + assert_eq!( + original_context.1, + fs::read(casework.join("schemas/status.schema.json")).unwrap() + ); + + let casework_file = casework.join("casework.yaml"); + let authored_casework = fs::read_to_string(&casework_file).unwrap(); + assert!(authored_casework.contains("deploymentRef: registry\n")); + let distinct_ref = authored_casework.replacen( + "deploymentRef: registry\n", + "deploymentRef: registry-runtime-slot\n", + 1, + ); + fs::write(&casework_file, &distinct_ref).unwrap(); + let explained = explain_policy(); + assert_eq!(explained["contextProviders"][0]["id"], "registry"); + assert_eq!( + explained["contextProviders"][0]["deploymentRef"], + "registry-runtime-slot" + ); + assert_ne!( + explained["reviewPolicies"][0]["binding"]["digest"], + original_policy["reviewPolicies"][0]["binding"]["digest"] + ); + assert_eq!( + explained["reviewPolicies"][0]["context"], + original_policy["reviewPolicies"][0]["context"] + ); + + let registry_file = breg.join("registry.yaml"); + let authored_registry = fs::read_to_string(®istry_file).unwrap(); + let pin_policy = |explanation: &serde_json::Value| { + let binding = &explanation["reviewPolicies"][0]["binding"]; + let version = binding["version"].as_str().unwrap(); + let digest = binding["digest"].as_str().unwrap(); + let selection = " policy:\n id: status-review\n"; + assert!(authored_registry.contains(selection)); + fs::write( + ®istry_file, + authored_registry.replacen( + selection, + &format!( + "{selection} version: {version:?}\n digest: {digest:?}\n" + ), + 1, + ), + ) + .unwrap(); + }; + pin_policy(&explained); + assert_eq!(export_context("pinned-schemas"), original_context); + + let read = |file: &std::path::Path| { + registry_platform_yaml::Reader::new(utf8(file)) + .scan(&fs::read(file).unwrap()) + .unwrap() + .unwrap() + .to_json_value() + }; + let dev_file = project.join("dev.yaml"); + let service_file = project.join("service.yaml"); + let mut dev = read(&dev_file); + let mut service = read(&service_file); + service["products"] = dev.as_object_mut().unwrap().remove("products").unwrap(); + fs::write(service_file, serde_norway::to_string(&service).unwrap()).unwrap(); + dev["bindings"] = serde_json::json!({ + "bregReviewAuthority": {"producer": "registry", "identity": "producer"}, + "caseworkContextProvider": {"identity": "context-status"}, + }); + fs::write(&dev_file, serde_norway::to_string(&dev).unwrap()).unwrap(); + assert_checked(check()); + + // Keep the strict selection exact while changing the real producer's issuer. + let other_issuer = "https://different-producer.example.test"; + let producer_issuer = " issuer: https://issuer.example.test\n"; + assert!(distinct_ref.contains(producer_issuer)); + fs::write( + &casework_file, + distinct_ref.replacen(producer_issuer, &format!(" issuer: {other_issuer}\n"), 1), + ) + .unwrap(); + let refused_policy = explain_policy(); + assert_eq!( + refused_policy["trustedProducers"][0]["issuer"], + other_issuer + ); + pin_policy(&refused_policy); + + let refused = check(); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + assert!(refused.stderr.is_empty(), "{refused:?}"); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).unwrap(); + let code = "rstack.service.review-binding"; + let message = + "The fixed development issuer must match the selected Casework producer's issuer."; + assert_eq!(report["status"], "domain-refusal", "{report}"); + assert_eq!(report["diagnostics"][0]["code"], code, "{report}"); + assert_eq!(report["diagnostics"][0]["path"], "/issuer", "{report}"); + assert_eq!(report["diagnostics"][0]["message"], message, "{report}"); + assert!(report["diagnostics"][0]["source"]["file"] + .as_str() + .unwrap() + .ends_with("/dev.yaml")); + assert!(!report.to_string().contains(other_issuer)); + assert!(!state.exists()); + + let refused = start_with_casework_tool(&project, &state, &caseworkctl); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + assert!(refused.stderr.is_empty(), "{refused:?}"); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).unwrap(); + assert_error_envelope(&report, "domain"); + let error = report["error"]["message"].as_str().unwrap(); + for expected in ["dev.yaml", code, "/issuer", message] { + assert!(error.contains(expected), "{report}"); + } + assert!(!report.to_string().contains(other_issuer)); + assert!(!state.exists()); +} + #[test] fn check_and_start_resolve_casework_profiles_and_bindings_with_the_owning_report() { for (profile, bindings, path, message, action, supplied) in [ @@ -4442,14 +4817,214 @@ fn casework_run_issuer_binding_needs_no_run_source_command() { !calls.contains("run-source"), "the runner must not call generate run-source: {calls}\n{report}" ); + let state = run.state.canonicalize().unwrap_or(run.state); assert!( calls .lines() - .any(|line| line.starts_with("check ") && line.contains("casework-bound")), + .any(|line| line.starts_with("--format json check ") + && line.contains(utf8(&state)) + && line.ends_with("/casework-bound")), "the runner checks the bound copy with the public check: {calls}\n{report}" ); } +#[test] +fn refused_supervisor_startup_preserves_managed_project_state() { + use sha2::{Digest, Sha256}; + use std::os::unix::fs::DirBuilderExt; + + for (stop_at, clean, has_volume) in [ + ("casework", true, true), + ("docker", true, true), + ("docker", false, false), + ("refusal", true, true), + ] { + let scratch = tempfile::tempdir().unwrap(); + let fixture = scratch.path().canonicalize().unwrap(); + let state = fixture.join("state"); + let root = state.join(RUN_ID); + fs::DirBuilder::new() + .mode(0o700) + .recursive(true) + .create(&root) + .unwrap(); + let project = fixture.join("project"); + fs::create_dir_all(project.join("casework")).unwrap(); + fs::write( + project.join("casework/casework.yaml"), + r#" +accessProfiles: + requester: {requiredScopes: [review.write]} +trustedProducers: + registry: {issuer: https://issuer.example.invalid, profile: requester, subject: producer} +"#, + ) + .unwrap(); + + let mut hash = Sha256::new(); + hash.update(project.as_os_str().as_encoded_bytes()); + hash.update([0]); + hash.update(state.as_os_str().as_encoded_bytes()); + let key = hex::encode(&hash.finalize()[..16]); + let retained = state.join(format!("development-project-{key}")); + fs::DirBuilder::new().mode(0o700).create(&retained).unwrap(); + let marker = retained.join("generation"); + fs::write(&marker, "fixture-generation").unwrap(); + fs::set_permissions(&marker, fs::Permissions::from_mode(0o600)).unwrap(); + let fake_docker = fixture.join("docker-state"); + fs::create_dir_all(fake_docker.join("volumes")).unwrap(); + let volume = fake_docker.join(format!("volumes/rstack-development-project-{key}")); + let labels = format!("org.registrystack.rstack.development-project={key}\norg.registrystack.rstack.generation=fixture-generation\n"); + if has_volume { + fs::write(&volume, &labels).unwrap(); + } + + let casework = fixture.join("caseworkctl"); + fs::write( + &casework, + r#"#!/usr/bin/env bash +set -euo pipefail +if [[ $# == 4 && "$1 $2 $3" == '--format json check' && "$4" == "$RUN_ROOT/casework-bound" ]]; then + : >"$FIXTURE/casework-started" + if [[ "$STOP_AT" == casework ]]; then + : >"$RUN_ROOT/stop" + sleep 5 + : >"$FIXTURE/casework-finished" + fi + if [[ "$STOP_AT" == refusal ]]; then + printf 'stderr-canary\n' >&2 + printf '%s\n' '{"apiVersion":"id.registrystack.org/formats/casework/report/v1","kind":"CaseworkReport","command":"check","status":"domain-refusal","ok":false,"diagnostics":[{"severity":"error","code":"casework.review-producer.duplicate-principal","path":"/trustedProducers/other-producer","message":"diagnostic-canary","suggestedAction":"Correct it."}]}' + exit 1 + fi +elif [[ $# != 4 || "$1 $3 $4" != 'check --format json' || "$2" != "$FIXTURE/project/casework" ]]; then + printf 'unexpected Casework check invocation\n' >&2 + exit 2 +fi +printf '%s\n' '{"apiVersion":"id.registrystack.org/formats/casework/report/v1","kind":"CaseworkReport","command":"check","status":"complete","ok":true}' +"#, + ) + .unwrap(); + let docker = fixture.join("docker"); + fs::write( + &docker, + r#"#!/usr/bin/env bash +set -euo pipefail +if [[ "$1" == run ]]; then + printf 'unexpected managed database start\n' >&2 + exit 1 +fi +"$DOCKER_FIXTURE" "$@" +if [[ "$STOP_AT" == docker && "$1 ${2:-}" == 'volume ls' ]]; then + : >"$RUN_ROOT/stop" +fi +"#, + ) + .unwrap(); + for tool in [&casework, &docker] { + fs::set_permissions(tool, fs::Permissions::from_mode(0o700)).unwrap(); + } + let input = serde_json::json!({ + "run_id": RUN_ID, "project": project, "ttl_seconds": 60, + "plan": { + "issuer": "run", "journeyFile": "dev-journeys.yaml", + "products": [ + {"product": "breg", "project": ".", "audience": "registry"}, + {"product": "casework", "project": "casework", "audience": "review"} + ], + "people": {"producer": {"subject": "producer", "client": "producer-client", + "grants": {"casework": {"profile": "requester", "scopes": ["review.write"]}}}}, + "bindings": {"bregReviewAuthority": {"id": "casework", "producer": "registry", + "identity": "producer", "runIssuerBinding": {"producer": { + "expectedIssuer": "https://issuer.example.invalid", + "expectedProfile": "requester", "expectedSubject": "producer" + }}}} + }, + "automatic_review": true, "managed_database": true, "project_key": key, "clean": clean, + "schema_people": [], "breg_authority": null, "casework_principals": {}, + "binaries": { + "breg": {"tool": system_binary("true"), "runtime": system_binary("false")}, + "casework": {"tool": casework, "runtime": system_binary("false")} + } + }); + fs::write(root.join("input.json"), input.to_string()).unwrap(); + + let fake_path = fake_docker_path(); + let docker_fixture = std::env::split_paths(&fake_path) + .next() + .unwrap() + .join("docker"); + let path = std::env::join_paths( + std::iter::once(fixture.clone()).chain(std::env::split_paths(&fake_path)), + ) + .unwrap(); + let output = Command::new(host("bregctl")) + .args(["rstack-dev", "supervisor"]) + .arg(&root) + .env("RSTACK_DEV_STATE_DIR", &state) + .env("REGISTRY_STACK_POSTURE", "development") + .env("FAKE_DOCKER_STATE", &fake_docker) + .env("DOCKER_FIXTURE", docker_fixture) + .env("PATH", path) + .env("RUN_ROOT", &root) + .env("FIXTURE", &fixture) + .env("STOP_AT", stop_at) + .output() + .unwrap(); + + assert!( + output.status.success() && output.stderr.is_empty(), + "{output:?}" + ); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["outcome"], "failed", "{report}"); + assert_eq!(report["operational"], false, "{report}"); + if stop_at == "refusal" { + let error = report["error"].as_str().unwrap(); + assert!( + error.contains("/bindings/bregReviewAuthority/runIssuerBinding"), + "{error}" + ); + assert!( + error.contains("same profile, issuer and subject"), + "{error}" + ); + assert!(!error.contains("diagnostic-canary"), "{error}"); + assert!( + !state.join("failed").exists(), + "the projected stderr should be discarded" + ); + } else { + assert_eq!(report["error"], "development run was stopped", "{report}"); + } + assert!(fixture.join("casework-started").exists()); + assert!(!fixture.join("casework-finished").exists()); + assert!(!root.exists(), "the stopped supervisor did not clean up"); + assert_eq!(fs::read_to_string(marker).unwrap(), "fixture-generation"); + if has_volume { + assert_eq!(fs::read_to_string(volume).unwrap(), labels); + } else { + assert!(!volume.exists()); + } + let calls = fake_docker.join("argv.log"); + if stop_at != "docker" { + assert!( + !calls.exists(), + "Docker was called after the refused preflight" + ); + } else { + let calls = fs::read_to_string(calls).unwrap(); + assert!( + calls.lines().any(|line| line.starts_with("volume ls ")), + "{calls}" + ); + assert!( + !calls.lines().any(|line| line.starts_with("volume rm ")), + "{calls}" + ); + } + } +} + #[test] #[ignore = "requires RSTACK_DEV_DATABASE_URL, RSTACK_DEV_DATABASE_CA and built bregctl, breg, caseworkctl and casework binaries"] fn casework_run_issuer_mismatch_names_the_dev_yaml_pointer() { diff --git a/crates/registry-rstack/tests/fixtures/service_review/mod.rs b/crates/registry-rstack/tests/fixtures/service_review/mod.rs new file mode 100644 index 0000000000..09bdca1d91 --- /dev/null +++ b/crates/registry-rstack/tests/fixtures/service_review/mod.rs @@ -0,0 +1,595 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Synthetic owner reports for review wiring projection and preflight refusals. + +use registry_platform_canonical_json::canonicalize_json; +use registry_platform_config::sha256_uri; +use registry_platform_yaml::{ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader}; +use serde_json::{json, Value}; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::{Command, Output}; + +const SERVICE: &str = "apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +"; +pub(super) const WORKFLOW_ISSUER: &str = "https://workflow-issuer.example.test"; +const TOOL_VERSION: &str = "0.53.0-dev"; +const CASEWORK_EXAMPLE: &str = + include_str!("../../../../../products/casework/examples/canonical-review/casework.yaml"); +const CASEWORK_SCHEMA: &str = + include_str!("../../../../../products/casework/generated/project/project.schema.json"); +const CASEWORK_PROJECT: FormatSpec<'static> = FormatSpec { + kind: "CaseworkProject", + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current( + "id.registrystack.org/formats/casework/project/v1", + )], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +const BREG_TOOL: &str = r#"#!/usr/bin/env bash +set -euo pipefail +if [[ "$1" == rstack-dev ]]; then + exec "$RSTACK_TEST_BREGCTL_HOST" "$@" +fi +case "$3" in + explain) cat -- "$5/explanation.json" ;; + generate) + mkdir -p -- "$7/generated/review-context-schemas" + cp -- "$5/context-index.json" "$7/generated/review-context-schemas/index.json" + cp -- "$5"/context-schemas/*.schema.json "$7/generated/review-context-schemas/" + cat -- "$5/generation.json" + ;; + *) exit 2 ;; +esac +"#; + +const CASEWORK_TOOL: &str = r#"#!/usr/bin/env bash +set -euo pipefail +[[ "$3" == explain ]] +cat -- "$4/explanation.json" +"#; + +pub(super) struct ReviewFixture { + directory: tempfile::TempDir, +} + +impl ReviewFixture { + pub(super) fn new( + name: &str, + authority: &str, + action: &str, + policy: &str, + provider: &str, + namespace: &str, + ) -> Self { + let fixture = Self { + directory: tempfile::tempdir().unwrap(), + }; + let root = fixture.root(); + fs::create_dir(root.join("registry")).unwrap(); + fs::create_dir(root.join("registry/context-schemas")).unwrap(); + fs::create_dir(root.join("casework")).unwrap(); + fs::write( + root.join("service.yaml"), + format!( + "{SERVICE}products:\n breg:\n projects:\n {name}: {{path: registry}}\n casework: {{path: casework}}\n" + ), + ) + .unwrap(); + fs::write( + root.join("registry/registry.yaml"), + format!( + "apiVersion: id.registrystack.org/formats/breg/project/v1\nkind: BRegProject\nreviewAuthorities:\n {authority}: {{protocol: id.registrystack.org/protocols/review/v1}}\n" + ), + ) + .unwrap(); + fs::write( + root.join("dev.yaml"), + format!( + "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\nkind: RStackDev\nissuer: https://issuer.example.test\naudiences: {{{name}: 'urn:synthetic:source', casework: 'urn:synthetic:review'}}\njourneyFile: dev-journeys.yaml\npeople: {{}}\nbindings:\n bregReviewAuthority: {{producer: {name}-requester, identity: synthetic-producer}}\n caseworkContextProvider: {{identity: synthetic-status}}\n" + ), + ) + .unwrap(); + + let mut action_report = Self::action(action, authority, namespace, policy); + if name == "workshop" { + // This service pins a policy revision as well as a context contract. + let review = &mut action_report["execution"]["proposal"]["review"]; + review["policy"]["version"] = json!("2"); + review["policy"]["digest"] = json!(Self::digest('8')); + } + let breg = json!({ + "apiVersion": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "kind": "BRegCtlReport", "ok": true, "status": "complete", + "command": "explain", "version": TOOL_VERSION, "revision": Self::digest('a'), + "explanation": { + "apiVersion": "id.registrystack.org/formats/breg/actions-explanation/v1", + "kind": "BRegActionsExplanation", + "reviewAuthorities": [Self::authority(authority)], + "actions": [action_report], + }, + }); + let generated = json!({ + "apiVersion": breg["apiVersion"], "kind": breg["kind"], + "ok": true, "status": "complete", "command": "generate", + "version": TOOL_VERSION, "revision": breg["revision"], + }); + let contract = fixture.write_context_schema(name, action, namespace); + fixture.write_json("registry/explanation.json", &breg); + fixture.write_json("registry/generation.json", &generated); + fixture.write_json( + "registry/context-index.json", + &json!({(action): Self::export(action, &contract)}), + ); + let mut policy_report = Self::policy(policy, provider, contract); + if name == "workshop" { + policy_report["binding"]["version"] = json!("2"); + policy_report["binding"]["digest"] = json!(Self::digest('8')); + } + let producer = Self::producer( + &format!("{name}-requester"), + "https://issuer.example.test", + "synthetic-producer", + namespace, + policy, + ); + fixture.write_casework(json!({ + "apiVersion": "id.registrystack.org/formats/casework/report/v1", + "kind": "CaseworkReport", "ok": true, "status": "complete", "command": "explain", + "version": TOOL_VERSION, + "reviewPolicies": [policy_report], + "contextProviders": [Self::provider(provider, namespace, "source-slot")], + "trustedProducers": [producer], + })); + for (file, script) in [("bregctl", BREG_TOOL), ("caseworkctl", CASEWORK_TOOL)] { + let path = root.join(file); + fs::write(&path, script).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + } + fixture + } + + pub(super) fn root(&self) -> &Path { + self.directory.path() + } + + pub(super) fn run(&self, arguments: &[&str]) -> Output { + self.command() + .args(["service", "plan", "service.yaml", "--format", "json"]) + .args(arguments) + .output() + .unwrap() + } + + pub(super) fn run_dev(&self, action: &str) -> Output { + let host = Path::new(env!("CARGO_BIN_EXE_rstack")).with_file_name("bregctl"); + assert!(host.is_file(), "build the bregctl development host first"); + self.command() + .args(["--format", "json", "dev", action, "."]) + .env_remove("REGISTRY_STACK_POSTURE") + .env_remove("RSTACK_DEV_DATABASE_URL") + .env_remove("RSTACK_DEV_DATABASE_CA") + .env("RSTACK_TEST_BREGCTL_HOST", host) + .env("RSTACK_DEV_STATE_DIR", self.root().join("runs")) + .env("RSTACK_BREG_BIN", self.root().join("bregctl")) + .env("RSTACK_CASEWORK_BIN", self.root().join("caseworkctl")) + .env("RSTACK_COORDINATORCTL_BIN", self.root().join("caseworkctl")) + .env("RSTACK_COORDINATOR_BIN", self.root().join("caseworkctl")) + .output() + .unwrap() + } + + fn command(&self) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_rstack")); + command + .current_dir(self.root()) + .args([ + "--install-root", + "missing-install", + "--bin-dir", + "missing-bins", + ]) + .env("RSTACK_BREGCTL_BIN", self.root().join("bregctl")) + .env("RSTACK_CASEWORKCTL_BIN", self.root().join("caseworkctl")); + command + } + + pub(super) fn set_producer_issuer(&self, issuer: &str) { + let mut report: Value = serde_json::from_slice( + &fs::read(self.root().join("casework/explanation.json")).unwrap(), + ) + .unwrap(); + report["trustedProducers"][0]["issuer"] = json!(issuer); + self.write_casework(report); + } + + pub(super) fn add_coordinator(&self, policy: &str) { + let mut casework: Value = serde_json::from_slice( + &fs::read(self.root().join("casework/explanation.json")).unwrap(), + ) + .unwrap(); + let namespace = if casework["reviewPolicies"][0]["binding"]["id"] == policy { + // A producer for a current-source policy must admit its provider's namespace. + casework["contextProviders"][0]["sourceNamespace"] + .as_str() + .unwrap() + } else { + casework["reviewPolicies"] + .as_array_mut() + .unwrap() + .push(json!({ + "binding": {"id": policy, "version": "1", "digest": Self::digest('7')}, + "purpose": "answer", + "context": {"mode": "submitted"}, + "stages": [{"excludeInitiator": false}], + })); + "workflow-items" + }; + let mut producer = Self::producer( + "workflow-requester", + WORKFLOW_ISSUER, + "synthetic-workflow-producer", + namespace, + policy, + ); + producer["completion"] = json!({"destinationId": "wake-flow", "recipientBinding": "flow"}); + casework["trustedProducers"] + .as_array_mut() + .unwrap() + .push(producer); + self.write_casework(casework); + + let service = self.root().join("service.yaml"); + let dev = self.root().join("dev.yaml"); + fs::create_dir(self.root().join("workflow")).unwrap(); + fs::write(self.root().join("workflow/workflow.yaml"), "").unwrap(); + fs::write( + &service, + format!( + "{} coordinator:\n projects:\n flow: {{path: workflow}}\n", + fs::read_to_string(&service).unwrap(), + ), + ) + .unwrap(); + fs::write( + &dev, + fs::read_to_string(&dev).unwrap().replace( + "audiences: {", + "audiences: {flow: 'urn:synthetic:workflow', ", + ), + ) + .unwrap(); + } + + pub(super) fn contract(name: &str, action: &str, namespace: &str) -> Value { + Self::context_schema(name, action, namespace).1 + } + + fn context_schema(name: &str, action: &str, namespace: &str) -> (Vec, Value) { + let mut schema = Self::display_schema(); + let id = format!("urn:registry:breg:review-context:{name}:{action}:summary"); + schema["$schema"] = json!("https://json-schema.org/draft/2020-12/schema"); + schema["$id"] = json!(id); + schema["x-registry-review-context"] = json!({ + "registryId": name, "actionId": action, "sourceNamespace": namespace, + "contextId": "summary", "projection": {"summary": {"type": "input", "input": "summary"}}, + "bindings": {"summary": {"kind": "input"}}, "classifications": {"summary": "internal"} + }); + let revision = sha256_uri(&canonicalize_json(&schema).unwrap()); + schema["x-registry-definition-revision"] = json!(revision); + let bytes = canonicalize_json(&schema).unwrap(); + let contract = json!({"id": id, "revision": revision, "schemaDigest": sha256_uri(&bytes)}); + (bytes, contract) + } + + fn write_context_schema(&self, name: &str, action: &str, namespace: &str) -> Value { + let (bytes, contract) = Self::context_schema(name, action, namespace); + self.replace_context_schema(action, &bytes, false); + contract + } + + pub(super) fn write_provider_description( + &self, + description: &str, + name: &str, + action: &str, + namespace: &str, + ) { + let (bytes, contract) = Self::context_schema(name, action, namespace); + let file = format!("casework/{description}"); + fs::create_dir_all(self.root().join(&file).parent().unwrap()).unwrap(); + self.write_json( + &file, + &json!({ + "apiVersion": "id.registrystack.org/formats/casework/breg-context-export/v1", + "kind": "CaseworkBregContextExport", "sourceNamespace": namespace, + "actionId": action, "contextId": "summary", "contract": contract, + "schema": serde_json::from_slice::(&bytes).unwrap(), + "schemaBytes": std::str::from_utf8(&bytes).unwrap(), + }), + ); + } + + pub(super) fn context_schema_bytes(&self, action: &str) -> Vec { + fs::read( + self.root() + .join(format!("registry/context-schemas/{action}.schema.json")), + ) + .unwrap() + } + + pub(super) fn replace_context_schema(&self, action: &str, bytes: &[u8], update_pins: bool) { + fs::write( + self.root() + .join(format!("registry/context-schemas/{action}.schema.json")), + bytes, + ) + .unwrap(); + if update_pins { + let digest = json!(sha256_uri(bytes)); + let mut index = self.read_json("registry/context-index.json"); + index[action]["digest"] = digest.clone(); + self.write_json("registry/context-index.json", &index); + let mut casework = self.read_json("casework/explanation.json"); + casework["reviewPolicies"][0]["context"]["contract"]["schemaDigest"] = digest; + self.write_json("casework/explanation.json", &casework); + } + } + + pub(super) fn replace_context_index_path(&self, action: &str, path: &str) { + let mut index = self.read_json("registry/context-index.json"); + index[action]["path"] = json!(path); + self.write_json("registry/context-index.json", &index); + } + + pub(super) fn replace_owner_output(&self, owner: &str, exit: u8, report: &Value) { + let file = format!("{owner}-response.json"); + self.write_json(&file, report); + fs::write( + self.root().join(format!("{owner}ctl")), + format!("#!/usr/bin/env bash\nset -euo pipefail\ncat -- \"$(dirname -- \"$0\")/{file}\"\nexit {exit}\n"), + ) + .unwrap(); + } + + pub(super) fn add_withdrawal_export(&self, policy: &str) -> Value { + let mut breg: Value = serde_json::from_slice( + &fs::read(self.root().join("registry/explanation.json")).unwrap(), + ) + .unwrap(); + breg["explanation"]["reviewAuthorities"] + .as_array_mut() + .unwrap() + .push(Self::authority("adjudication")); + breg["explanation"]["actions"] + .as_array_mut() + .unwrap() + .push(Self::action( + "withdraw-entry", + "adjudication", + "withdrawals", + policy, + )); + self.write_json("registry/explanation.json", &breg); + + let contract = self.write_context_schema("withdrawals", "withdraw-entry", "withdrawals"); + let mut exports: Value = serde_json::from_slice( + &fs::read(self.root().join("registry/context-index.json")).unwrap(), + ) + .unwrap(); + exports["withdraw-entry"] = Self::export("withdraw-entry", &contract); + self.write_json("registry/context-index.json", &exports); + contract + } + + pub(super) fn add_second_pair(&self, mut casework: Value) { + let contract = self.add_withdrawal_export("withdrawal-check"); + casework["reviewPolicies"] + .as_array_mut() + .unwrap() + .push(Self::policy( + "withdrawal-check", + "withdrawal-details", + contract, + )); + casework["contextProviders"] + .as_array_mut() + .unwrap() + .push(Self::provider( + "withdrawal-details", + "withdrawals", + "withdrawals-slot", + )); + casework["trustedProducers"] + .as_array_mut() + .unwrap() + .push(Self::producer( + "withdrawal-requester", + "https://issuer.example.test", + "synthetic-withdrawal-producer", + "withdrawals", + "withdrawal-check", + )); + self.write_casework(casework); + } + + pub(super) fn write_json(&self, file: &str, value: &Value) { + fs::write(self.root().join(file), serde_json::to_vec(value).unwrap()).unwrap(); + } + + pub(super) fn read_json(&self, file: &str) -> Value { + serde_json::from_slice(&fs::read(self.root().join(file)).unwrap()).unwrap() + } + + pub(super) fn write_casework(&self, mut report: Value) { + let mut project = Reader::new("casework.yaml") + .read(CASEWORK_EXAMPLE.as_bytes(), &Expect::one(&CASEWORK_PROJECT)) + .unwrap() + .to_json_value(); + let submitted = project["reviewPolicies"]["decision"].clone(); + let mut current_source = project["reviewPolicies"]["facility-address-review"].clone(); + current_source["displaySchema"] = Self::display_schema(); + project["reviewPolicies"] = json!({}); + project["contextProviders"] = Self::authored_entries(&report["contextProviders"]); + project["trustedProducers"] = Self::authored_entries(&report["trustedProducers"]); + + let producers = report["trustedProducers"].clone(); + for policy in report["reviewPolicies"].as_array_mut().unwrap() { + let id = policy["binding"]["id"].as_str().unwrap(); + let mut authored = match policy["context"]["mode"].as_str().unwrap() { + "current-source" => current_source.clone(), + "submitted" => submitted.clone(), + mode => panic!("unexpected Casework context mode {mode}"), + }; + authored["version"] = policy["binding"]["version"].clone(); + authored["context"] = policy["context"].clone(); + let stage_template = authored["stages"][0].clone(); + authored["stages"] = Value::Array( + policy["stages"] + .as_array() + .unwrap() + .iter() + .enumerate() + .map(|(index, stage)| { + let mut authored = stage_template.clone(); + if index != 0 { + authored["id"] = json!(format!("stage-{index}")); + } + authored["excludeInitiator"] = stage["excludeInitiator"].clone(); + authored + }) + .collect(), + ); + project["reviewPolicies"][id] = authored; + + let trusted: Vec<_> = producers + .as_array() + .unwrap() + .iter() + .filter(|producer| { + producer["reviewPolicies"] + .as_array() + .unwrap() + .contains(&json!(id)) + }) + .cloned() + .collect(); + if let Some(provider) = policy["context"]["provider"].as_str() { + let declaration = &project["contextProviders"][provider]; + assert!(trusted.iter().all(|producer| producer["sourceNamespaces"] + .as_array() + .unwrap() + .contains(&declaration["sourceNamespace"]))); + let mut dependency = declaration.clone(); + dependency["id"] = json!(provider); + // This fixture has no task templates or current-source routing. + // The compiled policy retains only the capabilities it uses. + dependency["capabilities"] = json!(["human-display", "service-status"]); + dependency["serviceProfiles"] = + json!({"service-status": declaration["serviceProfiles"]["service-status"]}); + policy["dependencies"]["contextProvider"] = dependency; + } + policy["dependencies"]["trustedProducers"] = json!(trusted); + } + for producer in producers.as_array().unwrap() { + for policy in producer["reviewPolicies"].as_array().unwrap() { + assert!(project["reviewPolicies"][policy.as_str().unwrap()].is_object()); + } + } + let schema = serde_json::from_str(CASEWORK_SCHEMA).unwrap(); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + if let Err(errors) = validator.validate(&project) { + let errors: Vec<_> = errors.map(|error| error.to_string()).collect(); + panic!("invalid Casework fixture: {errors:?}"); + } + fs::write( + self.root().join("casework/casework.yaml"), + serde_norway::to_string(&project).unwrap(), + ) + .unwrap(); + self.write_json("casework/explanation.json", &report); + } + + fn authored_entries(entries: &Value) -> Value { + Value::Object( + entries + .as_array() + .unwrap() + .iter() + .map(|entry| { + let mut authored = entry.as_object().unwrap().clone(); + let id = authored.remove("id").unwrap(); + (id.as_str().unwrap().to_owned(), Value::Object(authored)) + }) + .collect(), + ) + } + + fn display_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["summary"], + "properties": {"summary": {"type": "string", "maxLength": 160}}, + }) + } + + fn digest(hex: char) -> String { + format!("sha256:{}", hex.to_string().repeat(64)) + } + + fn authority(id: &str) -> Value { + json!({"id": id, "protocol": "id.registrystack.org/protocols/review/v1"}) + } + + fn action(id: &str, authority: &str, source: &str, policy: &str) -> Value { + json!({ + "id": id, + "execution": {"mode": "proposal", "proposal": { + "review": {"type": "required", "authority": authority, "source": source, "policy": {"id": policy}}, + "reviewContext": {"id": "summary", "fields": {"summary": {"type": "input", "input": "summary"}}}, + "permissions": [{"profileId": "submitter", "actorKind": "human", "operations": ["submit"]}], + }}, + }) + } + + fn provider(id: &str, namespace: &str, deployment_ref: &str) -> Value { + json!({ + "id": id, "sourceNamespace": namespace, "deploymentRef": deployment_ref, + "capabilities": ["human-display", "service-status"], + "serviceProfiles": {"service-status": "review-status"}, + }) + } + + fn producer(id: &str, issuer: &str, subject: &str, namespace: &str, policy: &str) -> Value { + json!({ + "id": id, "issuer": issuer, "profile": "requester", "subject": subject, + "sourceNamespaces": [namespace], "reviewPolicies": [policy], + "retention": {"receiptRetentionDays": 30}, + }) + } + + fn policy(id: &str, provider: &str, contract: Value) -> Value { + json!({ + "binding": {"id": id, "version": "1", "digest": Self::digest('9')}, + "purpose": "approval", + "context": {"mode": "current-source", "provider": provider, "contract": contract}, + "stages": [{"excludeInitiator": false}], + "dependencies": {"trustedProducers": []}, + }) + } + + fn export(action: &str, contract: &Value) -> Value { + json!({ + "id": contract["id"], "revision": contract["revision"], "digest": contract["schemaDigest"], + "path": format!("generated/review-context-schemas/{action}.schema.json"), + }) + } +} diff --git a/crates/registry-rstack/tests/service_plan.rs b/crates/registry-rstack/tests/service_plan.rs index 93c6530cbf..abc340b65c 100644 --- a/crates/registry-rstack/tests/service_plan.rs +++ b/crates/registry-rstack/tests/service_plan.rs @@ -75,8 +75,12 @@ impl Fixture { } } -fn assert_refusal(output: Output, code: &str, pointer: &str) { - assert_eq!(output.status.code(), Some(1), "{output:?}"); +fn assert_refusal(output: Output, code: &str, pointer: &str) -> Value { + assert_plan_error(output, 1, code, pointer) +} + +fn assert_plan_error(output: Output, exit: i32, code: &str, pointer: &str) -> Value { + assert_eq!(output.status.code(), Some(exit), "{output:?}"); assert!(output.stderr.is_empty(), "{output:?}"); let report: Value = serde_json::from_slice(&output.stdout).unwrap(); let diagnostic = &report["diagnostics"][0]; @@ -85,6 +89,7 @@ fn assert_refusal(output: Output, code: &str, pointer: &str) { assert!(diagnostic["source"]["file"].is_string(), "{report}"); assert!(diagnostic["source"]["line"].is_number(), "{report}"); assert!(diagnostic["source"]["column"].is_number(), "{report}"); + report } #[test] @@ -368,6 +373,1363 @@ fn changing_casework_path_projects_both_products_and_keeps_native_bindings() { ); } +#[test] +fn plan_resolves_two_independently_authored_review_services_without_dev_settings() { + for (name, authority, action, policy, provider, namespace) in [ + ( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ), + ( + "workshop", + "committee", + "accept-repair", + "repair-approval", + "job-summary", + "tool-desk", + ), + ] { + let fixture = ReviewFixture::new(name, authority, action, policy, provider, namespace); + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["products"][0]["id"], name); + assert_eq!(report["products"][1]["id"], "casework"); + assert!(report.get("devPlan").is_none()); + assert_eq!( + report["reviewWiring"], + json!({ + "bregProject": name, "caseworkProject": "casework", + "authority": authority, "action": action, "policy": policy, + "contextProvider": provider, "sourceNamespace": namespace, + "deploymentRef": "source-slot", + "contextContract": ReviewFixture::contract(name, action, namespace), + }), + ); + for value in [ + "synthetic-producer", + "synthetic-status", + "https://issuer.example.test", + "journeyFile", + ] { + assert!(!report.to_string().contains(value), "{report}"); + } + } +} + +#[test] +fn plans_one_local_review_pair_alongside_an_unrelated_external_selection() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + fixture.add_withdrawal_export("urn:synthetic:review:withdrawal-check"); + + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + report["reviewWiring"], + json!({ + "bregProject": "archive", "caseworkProject": "casework", + "authority": "signoff", "action": "amend-catalogue", "policy": "catalogue-check", + "contextProvider": "frozen-note", "sourceNamespace": "archive-series", + "deploymentRef": "source-slot", + "contextContract": ReviewFixture::contract("archive", "amend-catalogue", "archive-series"), + }), + ); + + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let dev_report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(dev_report["reviewWiring"], report["reviewWiring"]); + assert_eq!( + dev_report["devPlan"]["bindings"]["caseworkContextProvider"]["action"], + "amend-catalogue", + ); +} + +#[test] +fn refuses_a_local_review_authority_also_used_by_an_action_with_an_external_policy() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + let breg = fixture.root().join("registry/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&breg).unwrap()).unwrap(); + report["explanation"]["actions"] + .as_array_mut() + .unwrap() + .push(json!({ + "id": "withdraw-entry", + "execution": {"mode": "proposal", "proposal": {"permissions": [], "review": { + "type": "required", "authority": "signoff", "source": "withdrawals", + "policy": {"id": "urn:synthetic:review:withdrawal-check"}, + }}}, + })); + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + + let refusal = assert_refusal( + fixture.run(&[]), + "rstack.service.review-authority-shared", + "/products/breg/projects/archive/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert_eq!( + refusal["diagnostics"][0]["suggestedAction"], + "Give the other reviewed Actions a different review authority in the BReg project.", + ); +} + +#[test] +fn plans_with_retained_paired_providers_with_distinct_local_bindings() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + let casework = fixture.root().join("casework/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&casework).unwrap()).unwrap(); + let providers = report["contextProviders"].as_array_mut().unwrap(); + let mut independent = providers[0].clone(); + independent["id"] = json!("withdrawal-details"); + independent["sourceNamespace"] = json!("withdrawals"); + independent["deploymentRef"] = json!("withdrawals-slot"); + independent["capabilities"] = json!(["human-display", "service-status", "task-grant-context"]); + independent["serviceProfiles"]["task-grant-context"] = json!("withdrawal-task-reader"); + let mut other = independent.clone(); + other["id"] = json!("withdrawal-summary"); + providers.push(independent); + providers.push(other); + fixture.write_casework(report.clone()); + + let refusal = assert_refusal( + fixture.run(&["--dev-config", "dev.yaml"]), + "rstack.service.review-retained-provider-unpaired", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(!refusal.to_string().contains("withdrawal-details")); + + let description = "context-providers/withdraw-entry.json"; + fixture.write_provider_description(description, "withdrawals", "withdraw-entry", "withdrawals"); + for index in [1, 2] { + report["contextProviders"][index]["description"] = json!(description); + } + fixture.write_casework(report.clone()); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let plan: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(plan["reviewWiring"]["contextProvider"], "frozen-note"); + assert_eq!( + plan["devPlan"]["bindings"]["caseworkContextProvider"]["deploymentRef"], + "source-slot", + ); + + report["contextProviders"][1]["deploymentRef"] = json!("source-slot"); + fixture.write_casework(report); + let refusal = assert_refusal( + fixture.run(&["--dev-config", "dev.yaml"]), + "rstack.service.review-deployment-ref-shared", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert_eq!( + refusal["diagnostics"][0]["suggestedAction"], + "Give providers that share this runtime binding distinct deploymentRef values in the Casework project.", + ); +} + +#[test] +fn refuses_a_retained_provider_at_the_default_pairing_destination() { + let fixture = strict_review_fixture(); + let mut report = fixture.read_json("casework/explanation.json"); + let description = "context-providers/job-summary.json"; + fixture.write_provider_description(description, "withdrawals", "withdraw-entry", "withdrawals"); + let mut retained = report["contextProviders"][0].clone(); + retained["id"] = json!("withdrawal-details"); + retained["sourceNamespace"] = json!("withdrawals"); + retained["deploymentRef"] = json!("withdrawals-slot"); + retained["description"] = json!(description); + report["contextProviders"] + .as_array_mut() + .unwrap() + .push(retained); + fixture.write_casework(report.clone()); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-description-shared", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert_eq!( + refusal["diagnostics"][0]["suggestedAction"], + "Copy the description to a separate file and update the retained providers that use it in the Casework project.", + ); + assert!(!refusal.to_string().contains(description)); + assert!(!refusal.to_string().contains("withdrawal-details")); + } + + let independent = "context-providers/retained/job-summary.json"; + let project = fixture.root().join("casework"); + fs::create_dir(project.join("context-providers/retained")).unwrap(); + fs::rename(project.join(description), project.join(independent)).unwrap(); + report["contextProviders"][1]["description"] = json!(independent); + fixture.write_casework(report); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let plan: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(plan["reviewWiring"]["contextProvider"], "job-summary"); +} + +#[test] +fn refuses_a_retained_provider_at_the_explicit_pairing_destination() { + let fixture = strict_review_fixture(); + let mut report = fixture.read_json("casework/explanation.json"); + let description = "context-providers/native/repair-export.json"; + fixture.write_provider_description(description, "workshop", "accept-repair", "tool-desk"); + report["contextProviders"][0]["description"] = json!(description); + // Both providers can refer to this export in the owner's offline check + // because they describe the same source namespace. + let mut retained = report["contextProviders"][0].clone(); + retained["id"] = json!("retained-summary"); + retained["deploymentRef"] = json!("retained-slot"); + report["contextProviders"] + .as_array_mut() + .unwrap() + .push(retained); + + // The owner resolves interior dot components and repeated separators when + // checking an existing description, before production package checks. + let alias = "context-providers//native/./repair-export.json"; + for path in [description, alias] { + report["contextProviders"][1]["description"] = json!(path); + fixture.write_casework(report.clone()); + let refusal = assert_refusal( + fixture.run(&[]), + "rstack.service.review-provider-description-shared", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(!refusal.to_string().contains("repair-export.json")); + } +} + +#[test] +fn refuses_local_review_wiring_for_a_provider_that_declares_task_grant_context() { + let fixture = strict_review_fixture(); + let casework = fixture.root().join("casework/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&casework).unwrap()).unwrap(); + let provider = &mut report["contextProviders"][0]; + provider["capabilities"] = json!(["human-display", "service-status", "task-grant-context"]); + provider["serviceProfiles"]["task-grant-context"] = json!("review-task-reader"); + fixture.write_casework(report); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-capability", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert!(refusal["diagnostics"][0]["message"] + .as_str() + .unwrap() + .contains("one status-reader identity")); + assert!(!refusal.to_string().contains("review-task-reader")); + } +} + +#[test] +fn refuses_local_review_wiring_for_a_description_native_pairing_rejects() { + let fixture = strict_review_fixture(); + let casework = fixture.root().join("casework/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&casework).unwrap()).unwrap(); + // The owner accepts existing descriptions below the project directory. + // This synthetic report varies their paths at the native pairing boundary. + let mut describe = |path| { + report["contextProviders"][0]["description"] = json!(path); + report["reviewPolicies"][0]["dependencies"]["contextProvider"]["description"] = json!(path); + fs::write(&casework, serde_json::to_vec(&report).unwrap()).unwrap(); + }; + for path in [ + "providers/job-summary.json", + "context-providers/job-summary..json", + "context-providers/job-summary.json/", + "context-providers/job-summary.json/.", + ] { + describe(path); + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-description", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert!(refusal["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap() + .contains("context-providers/")); + assert!(!refusal.to_string().contains(path)); + } + } + + let description = "context-providers/native/job-summary.json"; + describe(description); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let plan: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(plan["reviewWiring"]["contextProvider"], "job-summary"); + assert!(!fixture.root().join("casework/context-providers").exists()); + + fixture.write_provider_description(description, "workshop", "accept-repair", "tool-desk"); + let destination = fixture.root().join("casework").join(description); + let original = fs::read(&destination).unwrap(); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + assert_eq!(fs::read(destination).unwrap(), original); +} + +#[test] +fn refuses_an_implicit_description_over_a_casework_display_schema() { + let fixture = strict_review_fixture(); + let relative = "context-providers/job-summary.json"; + let project_file = fixture.root().join("casework/casework.yaml"); + let mut project: Value = + serde_norway::from_str(&fs::read_to_string(&project_file).unwrap()).unwrap(); + let display = &mut project["reviewPolicies"]["repair-approval"]["displaySchema"]; + let file = fixture.root().join("casework").join(relative); + fs::create_dir(file.parent().unwrap()).unwrap(); + let original = serde_json::to_vec(display).unwrap(); + fs::write(&file, &original).unwrap(); + *display = json!({"$ref": relative}); + let authored = serde_norway::to_string(&project).unwrap(); + fs::write(&project_file, &authored).unwrap(); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-description", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert!(!refusal.to_string().contains(relative)); + assert_eq!(fs::read(&file).unwrap(), original); + assert_eq!(fs::read_to_string(&project_file).unwrap(), authored); + } +} + +#[test] +fn refuses_local_review_wiring_for_an_occupied_default_description() { + let destination = "context-providers/job-summary.json"; + for (obstruction, directory) in [(destination, true), ("context-providers", false)] { + let fixture = strict_review_fixture(); + let casework = fixture.root().join("casework"); + let blocked = casework.join(obstruction); + if directory { + fs::create_dir_all(&blocked).unwrap(); + } else { + fs::write(&blocked, b"synthetic obstruction").unwrap(); + } + let original = fs::read(casework.join("casework.yaml")).unwrap(); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-description", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert!(refusal["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap() + .contains("regular file")); + assert!(!refusal.to_string().contains(destination)); + } + if directory { + assert!(blocked.is_dir()); + } else { + assert_eq!(fs::read(blocked).unwrap(), b"synthetic obstruction"); + } + assert_eq!(fs::read(casework.join("casework.yaml")).unwrap(), original); + } +} + +#[test] +fn refuses_local_review_wiring_for_symlinks_on_the_description_path() { + use std::os::unix::fs::symlink; + + let destination = "context-providers/job-summary.json"; + for link in ["context-providers", destination] { + let fixture = strict_review_fixture(); + let casework = fixture.root().join("casework"); + let link_path = casework.join(link); + let target = casework.join("synthetic-link-target"); + if link == "context-providers" { + fs::create_dir(&target).unwrap(); + } else { + fs::create_dir_all(link_path.parent().unwrap()).unwrap(); + } + symlink(&target, &link_path).unwrap(); + + let refusal = assert_refusal( + fixture.run(&[]), + "rstack.service.review-provider-description", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(!refusal.to_string().contains(destination)); + assert!(!refusal.to_string().contains("synthetic-link-target")); + assert_eq!(fs::read_link(link_path).unwrap(), target); + if link == "context-providers" { + assert!(fs::read_dir(target).unwrap().next().is_none()); + } else { + assert!(!target.exists()); + } + } +} + +#[test] +fn refuses_local_review_wiring_for_a_deployment_ref_outside_the_runtime_key_grammar() { + let fixture = strict_review_fixture(); + let mut report = fixture.read_json("casework/explanation.json"); + let overlong = "s".repeat(65); + for deployment_ref in [ + "urn:synthetic:provider-slot", + "SyntheticSlot", + overlong.as_str(), + ] { + report["contextProviders"][0]["deploymentRef"] = json!(deployment_ref); + fixture.write_casework(report.clone()); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-deployment-ref-invalid", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + let action = refusal["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap(); + assert!(action.contains("deploymentRef")); + assert!(action.contains("local identifier")); + assert!(!refusal.to_string().contains(deployment_ref)); + } + } +} + +#[test] +fn plans_without_a_local_pair_but_refuses_abbreviated_review_bindings() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + let breg = fixture.root().join("registry/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&breg).unwrap()).unwrap(); + report["explanation"]["actions"][0]["execution"]["proposal"]["review"]["policy"]["id"] = + json!("urn:synthetic:review:catalogue-check"); + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(report.get("reviewWiring").is_none(), "{report}"); + assert_refusal( + fixture.run(&["--dev-config", "dev.yaml"]), + "rstack.service.review-binding", + "/bindings", + ); +} + +#[test] +fn rejects_policy_ids_outside_the_breg_report_grammar() { + let fixture = strict_review_fixture(); + let breg = fixture.root().join("registry/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&breg).unwrap()).unwrap(); + let policy = "/explanation/actions/0/execution/proposal/review/policy/id"; + let maximum = "é".repeat(64); + *report.pointer_mut(policy).unwrap() = json!(maximum); + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + let plan: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(plan.get("reviewWiring").is_none(), "{plan}"); + + for invalid in [json!("é".repeat(65)), json!(" "), json!(42)] { + *report.pointer_mut(policy).unwrap() = invalid; + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + "/products/breg/projects/workshop/path", + ); + } +} + +#[test] +fn complete_review_bindings_project_from_service_or_legacy_dev_inventory() { + let fixture = strict_review_fixture(); + let service = fixture.root().join("service.yaml"); + let dev = fixture.root().join("dev.yaml"); + let service_contents = fs::read_to_string(&service).unwrap(); + let (envelope, inventory) = service_contents.split_once("products:").unwrap(); + let full_bindings = bind_breg_run_issuer(&fs::read_to_string(&dev).unwrap(), RUN_ISSUER_GUARD) + .replace("{producer:", "{id: committee, producer:") + .replace( + "{identity: synthetic-status}", + "{id: job-summary, action: accept-repair, identity: synthetic-status}", + ); + let standalone = fixture.run(&[]); + assert!(standalone.status.success(), "{standalone:?}"); + assert!(standalone.stderr.is_empty(), "{standalone:?}"); + let standalone: Value = serde_json::from_slice(&standalone.stdout).unwrap(); + assert_eq!(standalone["reviewWiring"]["deploymentRef"], "source-slot"); + + // Both service and legacy dev inventories can project complete bindings + // without asking Casework for an explanation. + fs::write( + fixture.root().join("caseworkctl"), + "#!/usr/bin/env bash\nexit 3\n", + ) + .unwrap(); + let plan = || { + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + serde_json::from_slice::(&output.stdout).unwrap() + }; + + fs::write(&dev, &full_bindings).unwrap(); + let authored = plan(); + assert!(authored.get("reviewWiring").is_none(), "{authored}"); + assert_eq!( + authored["devPlan"]["bindings"], + json!({ + "bregReviewAuthority": { + "id": "committee", "producer": "workshop-requester", "identity": "synthetic-producer", + "runIssuerBinding": serde_json::from_str::(RUN_ISSUER_GUARD).unwrap(), + }, + "caseworkContextProvider": {"id": "job-summary", "action": "accept-repair", "identity": "synthetic-status"}, + }), + ); + + fs::write(&service, envelope).unwrap(); + fs::write(&dev, format!("{full_bindings}products:{inventory}")).unwrap(); + let legacy = plan(); + assert!(legacy.get("reviewWiring").is_none(), "{legacy}"); + assert_eq!(legacy["devPlan"], authored["devPlan"]); +} + +#[test] +fn rejects_a_wrong_policy_pin_or_source_for_a_declared_policy() { + let fixture = strict_review_fixture(); + let breg = fixture.root().join("registry/explanation.json"); + let original: Value = serde_json::from_slice(&fs::read(&breg).unwrap()).unwrap(); + for (field, value) in [ + ("/policy/version", json!("1")), + ( + "/policy/digest", + json!(format!("sha256:{}", "0".repeat(64))), + ), + ("/source", json!("other-desk")), + ] { + let mut report = original.clone(); + let review = &mut report["explanation"]["actions"][0]["execution"]["proposal"]["review"]; + *review.pointer_mut(field).unwrap() = value; + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + assert_refusal( + fixture.run(&[]), + "rstack.service.review-unresolved", + "/products/casework/path", + ); + } +} + +#[test] +fn review_selection_requires_omission_or_a_pair_of_non_null_pins() { + let fixture = strict_review_fixture(); + let breg = fixture.root().join("registry/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&breg).unwrap()).unwrap(); + let policy = "/explanation/actions/0/execution/proposal/review/policy"; + let digest = report.pointer(policy).unwrap()["digest"].clone(); + let id = "repair-approval"; + for invalid in [ + json!({"id": id, "version": null}), + json!({"id": id, "digest": null}), + json!({"id": id, "version": null, "digest": null}), + json!({"id": id, "version": null, "digest": digest}), + json!({"id": id, "version": "2", "digest": null}), + json!({"id": id, "version": 2, "digest": digest}), + json!({"id": id, "version": "2", "digest": "sha256:invalid"}), + ] { + *report.pointer_mut(policy).unwrap() = invalid; + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + assert_plan_error( + fixture.run(&["--dev-config", "dev.yaml"]), + 3, + "rstack.service.review-inspection", + "/products/breg/projects/workshop/path", + ); + } + for partial in [ + json!({"id": id, "version": "2"}), + json!({"id": id, "digest": digest}), + ] { + *report.pointer_mut(policy).unwrap() = partial; + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + assert_refusal( + fixture.run(&["--dev-config", "dev.yaml"]), + "rstack.service.review-unresolved", + "/products/casework/path", + ); + } + + *report.pointer_mut(policy).unwrap() = json!({"id": id}); + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let plan: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(plan["reviewWiring"]["policy"], id); + assert_eq!( + plan["devPlan"]["bindings"]["bregReviewAuthority"]["id"], + "committee" + ); +} + +#[test] +fn distinguishes_missing_owner_tools_from_authored_project_refusals() { + let fixture = strict_review_fixture(); + let tool = fixture.root().join("caseworkctl"); + let backup = fixture.root().join("caseworkctl.original"); + fs::rename(&tool, &backup).unwrap(); + assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-tool-unavailable", + "/products/casework/path", + ); + fs::rename(backup, &tool).unwrap(); + + let response = json!({ + "apiVersion": "id.registrystack.org/formats/casework/report/v1", + "kind": "CaseworkReport", "command": "explain", "status": "domain-refusal", + "ok": false, "version": "0.53.0", "additionalReportDetail": "discarded-owner-detail", + "diagnostics": [{ + "severity": "error", "code": "casework.synthetic", "path": "/reviewPolicies", + "message": "discarded-owner-detail", "suggestedAction": "Correct the project." + }] + }); + fixture.replace_owner_output("casework", 1, &response); + let refusal = assert_refusal( + fixture.run(&[]), + "rstack.service.review-project-refused", + "/products/casework/path", + ); + assert!(!refusal.to_string().contains("discarded-owner-detail")); + + for (field, invalid) in [ + ("version", json!("")), + ("diagnostics", json!([])), + ("diagnostics", json!([{"message":"discarded-owner-detail"}])), + ( + "diagnostics", + json!([{ + "severity": "warning", "code": "casework.synthetic", "path": "", + "message": "discarded-owner-detail", "suggestedAction": "Correct the project." + }]), + ), + ] { + let mut malformed = response.clone(); + malformed[field] = invalid; + fixture.replace_owner_output("casework", 1, &malformed); + let failure = assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + "/products/casework/path", + ); + assert!(!failure.to_string().contains("discarded-owner-detail")); + } + + let mut operational = response.clone(); + operational["status"] = json!("operational-failure"); + fixture.replace_owner_output("casework", 3, &operational); + let failure = assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + "/products/casework/path", + ); + assert!(!failure.to_string().contains("discarded-owner-detail")); + let check = assert_plan_error( + fixture.run_dev("check"), + 3, + "rstack.dev.check-unavailable", + "/products/casework/path", + ); + assert_eq!(check["status"], "operational-failure"); + let start = fixture.run_dev("start"); + assert_eq!(start.status.code(), Some(3), "{start:?}"); + let report: Value = serde_json::from_slice(&start.stdout).unwrap(); + assert_eq!(report["error"]["class"], "operational"); + assert!(!report.to_string().contains("discarded-owner-detail")); + assert!(!fixture.root().join("runs").exists()); +} + +#[test] +fn breg_review_refusal_accepts_the_owners_command_and_document_diagnostics() { + let fixture = strict_review_fixture(); + let mut response = json!({ + "apiVersion": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "kind": "BRegCtlReport", "command": "explain", "status": "domain-refusal", + "ok": false, "version": "0.53.0", + "diagnostics": [{ + "severity": "error", "code": "breg.synthetic", "artifact": "registry-project", + "path": "/actions", "message": "discarded-owner-detail", + "suggestedAction": "correct-authoring-source", + "related": [{"path": "/actions/other", "message": "discarded-owner-detail"}] + }] + }); + fixture.replace_owner_output("breg", 1, &response); + let refused = assert_refusal( + fixture.run(&[]), + "rstack.service.review-project-refused", + "/products/breg/projects/workshop/path", + ); + assert!(!refused.to_string().contains("discarded-owner-detail")); + + response["diagnostics"] = json!([ + { + "severity": "warning", "code": "breg.synthetic-warning", "rank": "hygiene", + "path": "/actions", "message": "discarded-owner-detail", + "suggestedAction": "Review this finding." + }, + { + "severity": "error", "code": "breg.synthetic", "path": "/actions", + "message": "discarded-owner-detail", "suggestedAction": "Correct the project.", + "source": {"file":"registry.yaml","line":2,"column":1} + } + ]); + fixture.replace_owner_output("breg", 1, &response); + let refused = assert_refusal( + fixture.run(&[]), + "rstack.service.review-project-refused", + "/products/breg/projects/workshop/path", + ); + assert!(!refused.to_string().contains("discarded-owner-detail")); + + response["diagnostics"][0]["rank"] = json!("discarded-owner-rank"); + fixture.replace_owner_output("breg", 1, &response); + let refused = assert_refusal( + fixture.run(&[]), + "rstack.service.review-project-refused", + "/products/breg/projects/workshop/path", + ); + assert!(!refused.to_string().contains("discarded-owner-")); + + for field in ["severity", "code", "path", "message", "suggestedAction"] { + let mut malformed = response.clone(); + malformed["diagnostics"][0][field] = Value::Null; + fixture.replace_owner_output("breg", 1, &malformed); + let failure = assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + "/products/breg/projects/workshop/path", + ); + assert!(!failure.to_string().contains("discarded-owner-")); + } +} + +const RUN_ISSUER_GUARD: &str = r#"{"producer":{"expectedIssuer":"https://issuer.example.test","expectedProfile":"requester","expectedSubject":"synthetic-producer"}}"#; +const EXTERNAL_REVIEW_ISSUER: &str = "http://127.0.0.1:41400"; + +fn strict_review_fixture() -> ReviewFixture { + ReviewFixture::new( + "workshop", + "committee", + "accept-repair", + "repair-approval", + "job-summary", + "tool-desk", + ) +} + +fn bind_breg_run_issuer(settings: &str, guard: &str) -> String { + settings + .replace("issuer: https://issuer.example.test", "issuer: run") + .replace( + "identity: synthetic-producer}", + &format!("identity: synthetic-producer, runIssuerBinding: {guard}}}"), + ) +} + +fn bind_coordinator_run_issuer(settings: &str) -> String { + let settings = settings.replace("issuer: https://issuer.example.test", "issuer: run"); + format!( + "{settings} coordinatorReviewProducer:\n connection: review\n producer: workflow-requester\n identity: synthetic-workflow-producer\n completionDestination: wake-flow\n runIssuerBinding:\n producer:\n expectedIssuer: {}\n expectedProfile: requester\n expectedSubject: synthetic-workflow-producer\n", + service_review::WORKFLOW_ISSUER, + ) +} + +fn assert_review_refused_before_provisioning(fixture: &ReviewFixture, pointer: &str, reason: &str) { + let code = "rstack.service.review-binding"; + for checked in [ + fixture.run(&["--dev-config", "dev.yaml"]), + fixture.run_dev("check"), + ] { + let report = assert_refusal(checked, code, pointer); + let diagnostic = &report["diagnostics"][0]; + assert!(diagnostic["source"]["file"] + .as_str() + .unwrap() + .ends_with("dev.yaml")); + assert!(diagnostic["message"].as_str().unwrap().contains(reason)); + for issuer in [ + "https://issuer.example.test", + service_review::WORKFLOW_ISSUER, + EXTERNAL_REVIEW_ISSUER, + ] { + assert!(!report.to_string().contains(issuer)); + } + } + + let started = fixture.run_dev("start"); + assert_eq!(started.status.code(), Some(1), "{started:?}"); + assert!(started.stderr.is_empty(), "{started:?}"); + let report: Value = serde_json::from_slice(&started.stdout).unwrap(); + let message = report["error"]["message"].as_str().unwrap(); + for field in [code, "dev.yaml", pointer, reason] { + assert!(message.contains(field), "{message}"); + } + for issuer in [ + "https://issuer.example.test", + service_review::WORKFLOW_ISSUER, + EXTERNAL_REVIEW_ISSUER, + ] { + assert!(!report.to_string().contains(issuer)); + } + assert!(!fixture.root().join("runs").exists()); +} + +#[test] +fn abbreviated_review_refuses_external_keys_even_with_the_matching_producer_issuer() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + fixture.set_producer_issuer(EXTERNAL_REVIEW_ISSUER); + let dev = fixture.root().join("dev.yaml"); + let jwks = format!("{EXTERNAL_REVIEW_ISSUER}/keys"); + let external = fs::read_to_string(&dev).unwrap().replace( + "issuer: https://issuer.example.test", + &format!("issuer: {EXTERNAL_REVIEW_ISSUER}\nexternalJwksUri: {jwks}"), + ); + fs::write(&dev, &external).unwrap(); + + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let metadata: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(metadata["reviewWiring"]["authority"], "signoff"); + assert!(metadata.get("devPlan").is_none()); + assert_review_refused_before_provisioning(&fixture, "/externalJwksUri", "run's own key set"); + + let explicit = external + .replace("{producer:", "{id: signoff, producer:") + .replace( + "{identity: synthetic-status}", + "{id: frozen-note, action: amend-catalogue, identity: synthetic-status}", + ); + let project = |settings: &str| { + fs::write(&dev, settings).unwrap(); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let plan: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(plan["devPlan"]["externalJwksUri"], jwks); + plan["devPlan"].clone() + }; + let projected = project(&explicit); + let service = fixture.root().join("service.yaml"); + let authored = fs::read_to_string(&service).unwrap(); + let (envelope, inventory) = authored.split_once("products:").unwrap(); + fs::write(&service, envelope).unwrap(); + assert_eq!( + project(&format!("{explicit}products:{inventory}")), + projected + ); +} + +#[test] +fn abbreviated_review_refuses_rebinding_either_guarded_producer_in_the_policy_digest() { + let fixture = strict_review_fixture(); + fixture.add_coordinator("repair-approval"); + + let dev = fixture.root().join("dev.yaml"); + let authored = fs::read_to_string(&dev).unwrap(); + for (settings, pointer) in [ + ( + bind_breg_run_issuer(&authored, RUN_ISSUER_GUARD), + "/bindings/bregReviewAuthority/runIssuerBinding", + ), + ( + bind_coordinator_run_issuer(&authored), + "/bindings/coordinatorReviewProducer/runIssuerBinding", + ), + ] { + fs::write(&dev, settings).unwrap(); + assert_review_refused_before_provisioning(&fixture, pointer, "digest"); + } + + fs::write( + &dev, + authored.replace( + "identity: synthetic-producer}", + "identity: synthetic-producer, runIssuerBinding: null}", + ), + ) + .unwrap(); + assert_refusal( + fixture.run_dev("check"), + "config.null-value", + "/bindings/bregReviewAuthority/runIssuerBinding", + ); +} + +#[test] +fn abbreviated_review_requires_the_fixed_issuer_of_the_selected_producer() { + let fixture = strict_review_fixture(); + fixture.add_coordinator("repair-approval"); + let dev = fixture.root().join("dev.yaml"); + let authored = fs::read_to_string(&dev).unwrap(); + let alternate_issuer = authored.replace( + "https://issuer.example.test", + service_review::WORKFLOW_ISSUER, + ); + fs::write(&dev, &alternate_issuer).unwrap(); + assert_review_refused_before_provisioning(&fixture, "/issuer", "selected Casework producer"); + + fs::write( + &dev, + alternate_issuer.replace( + "producer: workshop-requester, identity: synthetic-producer", + "producer: workflow-requester, identity: synthetic-workflow-producer", + ), + ) + .unwrap(); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + report["devPlan"]["bindings"]["bregReviewAuthority"]["producer"], + "workflow-requester" + ); +} + +#[test] +fn abbreviated_review_requires_a_breg_run_guard_even_with_a_coordinator_guard() { + let fixture = strict_review_fixture(); + fixture.add_coordinator("other-approval"); + + let dev = fixture.root().join("dev.yaml"); + let authored = fs::read_to_string(&dev).unwrap(); + for settings in [ + authored.replace("issuer: https://issuer.example.test", "issuer: run"), + bind_coordinator_run_issuer(&authored), + ] { + fs::write(&dev, settings).unwrap(); + assert_review_refused_before_provisioning( + &fixture, + "/bindings/bregReviewAuthority", + "own runIssuerBinding", + ); + } + + let project = |settings| { + fs::write(&dev, settings).unwrap(); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + report["devPlan"]["bindings"]["bregReviewAuthority"]["id"], + "committee" + ); + report["devPlan"]["bindings"].clone() + }; + project(authored.clone()); + let null_guard = bind_breg_run_issuer(&authored, "null") + .replace("issuer: run", "issuer: https://issuer.example.test"); + assert_eq!( + project(null_guard)["bregReviewAuthority"].get("runIssuerBinding"), + Some(&Value::Null) + ); + let breg = fixture.root().join("registry/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&breg).unwrap()).unwrap(); + report["explanation"]["actions"][0]["execution"]["proposal"]["review"]["policy"] = + json!({"id": "repair-approval"}); + fs::write(&breg, serde_json::to_vec(&report).unwrap()).unwrap(); + let breg_only = bind_breg_run_issuer(&authored, RUN_ISSUER_GUARD); + assert!(project(breg_only.clone())["bregReviewAuthority"]["runIssuerBinding"].is_object()); + let paired = project(bind_coordinator_run_issuer(&breg_only)); + assert!(paired["bregReviewAuthority"]["runIssuerBinding"].is_object()); + assert!(paired["coordinatorReviewProducer"]["runIssuerBinding"].is_object()); +} + +#[test] +fn local_settings_supply_only_the_review_identities_and_producer() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + let output = fixture.run(&["--dev-config", "dev.yaml"]); + assert!(output.status.success(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + report["devPlan"]["bindings"], + json!({ + "bregReviewAuthority": {"id": "signoff", "producer": "archive-requester", "identity": "synthetic-producer"}, + "caseworkContextProvider": {"id": "frozen-note", "action": "amend-catalogue", "identity": "synthetic-status", "deploymentRef": "source-slot"}, + }), + ); + assert_eq!(report["devPlan"]["journeyFile"], "dev-journeys.yaml"); + + let dev = fixture.root().join("dev.yaml"); + let authored = fs::read_to_string(&dev).unwrap(); + fs::write( + &dev, + authored.replace("archive-requester", "another-producer"), + ) + .unwrap(); + assert_refusal( + fixture.run(&["--dev-config", "dev.yaml"]), + "rstack.service.review-binding", + "/bindings/bregReviewAuthority/producer", + ); +} + +#[test] +fn review_wiring_refuses_a_stale_contract_and_two_independent_pairs() { + let fixture = ReviewFixture::new( + "archive", + "signoff", + "amend-catalogue", + "catalogue-check", + "frozen-note", + "archive-series", + ); + let casework = fixture.root().join("casework/explanation.json"); + let mut report: Value = serde_json::from_slice(&fs::read(&casework).unwrap()).unwrap(); + let exact = report["reviewPolicies"][0]["context"]["contract"]["schemaDigest"].clone(); + report["reviewPolicies"][0]["context"]["contract"]["schemaDigest"] = + json!(format!("sha256:{}", "0".repeat(64))); + fs::write(&casework, serde_json::to_vec(&report).unwrap()).unwrap(); + assert_refusal( + fixture.run(&[]), + "rstack.service.review-contract", + "/products/casework/path", + ); + report["reviewPolicies"][0]["context"]["contract"]["schemaDigest"] = exact; + let mut conflicting = report["reviewPolicies"][0].clone(); + conflicting["binding"]["id"] = json!("secondary-catalogue-check"); + conflicting["context"]["contract"]["schemaDigest"] = + json!(format!("sha256:{}", "0".repeat(64))); + report["reviewPolicies"] + .as_array_mut() + .unwrap() + .push(conflicting); + fs::write(&casework, serde_json::to_vec(&report).unwrap()).unwrap(); + assert_refusal( + fixture.run(&[]), + "rstack.service.review-contract", + "/products/casework/path", + ); + report["reviewPolicies"] + .as_array_mut() + .unwrap() + .pop() + .unwrap(); + fixture.add_second_pair(report); + assert_refusal( + fixture.run(&[]), + "rstack.service.review-ambiguous", + "/products", + ); + + let mut report = fixture.read_json("casework/explanation.json"); + let description = "context-providers/frozen-note.json"; + fixture.write_provider_description(description, "withdrawals", "withdraw-entry", "withdrawals"); + report["contextProviders"][1]["description"] = json!(description); + fixture.write_casework(report); + assert_refusal( + fixture.run(&[]), + "rstack.service.review-ambiguous", + "/products", + ); + + let mut report = fixture.read_json("casework/explanation.json"); + report["contextProviders"][0]["deploymentRef"] = json!("urn:synthetic:provider-slot"); + report["contextProviders"][1] + .as_object_mut() + .unwrap() + .remove("description") + .unwrap(); + fixture.write_casework(report); + fs::create_dir( + fixture + .root() + .join("casework/context-providers/withdrawal-details.json"), + ) + .unwrap(); + assert_refusal( + fixture.run(&[]), + "rstack.service.review-ambiguous", + "/products", + ); +} + +#[test] +fn review_preflight_requires_the_same_build_in_all_owner_reports() { + let fixture = strict_review_fixture(); + let build = "0.53.0-nightly.20990101.synthetic"; + for file in [ + "casework/explanation.json", + "registry/explanation.json", + "registry/generation.json", + ] { + let mut report = fixture.read_json(file); + report["version"] = json!(build); + fixture.write_json(file, &report); + } + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + + for (file, pointer) in [ + ("casework/explanation.json", "/products/casework/path"), + ( + "registry/explanation.json", + "/products/breg/projects/workshop/path", + ), + ( + "registry/generation.json", + "/products/breg/projects/workshop/path", + ), + ] { + let mut report = fixture.read_json(file); + report.as_object_mut().unwrap().remove("version"); + fixture.write_json(file, &report); + assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + pointer, + ); + report["version"] = json!(build); + fixture.write_json(file, &report); + } + + for file in ["registry/explanation.json", "registry/generation.json"] { + let mut report = fixture.read_json(file); + let mismatched = "0.53.0-nightly.20990101.mismatched-canary"; + report["version"] = json!(mismatched); + fixture.write_json(file, &report); + let failure = assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + "/products/breg/projects/workshop/path", + ); + assert!(!failure.to_string().contains(build)); + assert!(!failure.to_string().contains(mismatched)); + let start = fixture.run_dev("start"); + assert_eq!(start.status.code(), Some(3), "{start:?}"); + assert!(!fixture.root().join("runs").exists()); + report["version"] = json!(build); + fixture.write_json(file, &report); + } +} + +#[test] +fn review_preflight_requires_human_submit_for_an_initiator_excluding_stage() { + let fixture = strict_review_fixture(); + let breg_facts = "registry/explanation.json"; + let mut breg = fixture.read_json(breg_facts); + const PERMISSIONS: &str = "/explanation/actions/0/execution/proposal/permissions"; + let grants = json!([ + {"profileId": "machine-submitter", "actorKind": "service", "operations": ["submit"]}, + {"profileId": "human-reader", "actorKind": "human", "operations": ["get"]}, + ]); + *breg.pointer_mut(PERMISSIONS).unwrap() = grants; + fixture.write_json(breg_facts, &breg); + + let mut casework = fixture.read_json("casework/explanation.json"); + let mut other_policy = casework["reviewPolicies"][0].clone(); + other_policy["binding"]["id"] = json!("separate-approval"); + other_policy["stages"][0]["excludeInitiator"] = json!(true); + casework["reviewPolicies"] + .as_array_mut() + .unwrap() + .push(other_policy); + fixture.write_casework(casework.clone()); + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + + casework["reviewPolicies"][0]["stages"] = json!([ + {"excludeInitiator": false}, {"excludeInitiator": true}, + ]); + let producer = &mut casework["trustedProducers"][0]; + producer["trustedInitiatorIssuer"] = producer["issuer"].clone(); + producer["trustedInitiatorPrincipalClaim"] = json!("registry_principal"); + fixture.write_casework(casework); + + let refusal = assert_refusal( + fixture.run(&[]), + "rstack.service.review-human-submit-required", + "/products/breg/projects/workshop/path", + ); + assert!(!refusal.to_string().contains("machine-submitter")); + + for actor_kind in [json!("human"), Value::Null] { + breg.pointer_mut(PERMISSIONS).unwrap()[0]["actorKind"] = actor_kind; + fixture.write_json(breg_facts, &breg); + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + } +} + +#[test] +fn review_preflight_validates_the_generated_schema_bytes_before_local_preparation() { + const SCHEMA_LIMIT: usize = 1024 * 1024; + let fixture = strict_review_fixture(); + let action = "accept-repair"; + let original = fixture.context_schema_bytes(action); + let check_refused = || { + assert_plan_error( + fixture.run(&[]), + 3, + "rstack.service.review-inspection", + "/products/breg/projects/workshop/path", + ); + assert!(!fixture.root().join("casework/context-providers").exists()); + assert!(!fixture.root().join("runs").exists()); + }; + + let mut changed_bytes = original.clone(); + changed_bytes.push(b'\n'); + fixture.replace_context_schema(action, &changed_bytes, false); + check_refused(); + assert_plan_error( + fixture.run_dev("check"), + 3, + "rstack.dev.check-unavailable", + "/products/breg/projects/workshop/path", + ); + let start = fixture.run_dev("start"); + assert_eq!(start.status.code(), Some(3), "{start:?}"); + assert!(!fixture.root().join("runs").exists()); + + fixture.replace_context_schema(action, b"not-json", true); + check_refused(); + + let mut changed_schema: Value = serde_json::from_slice(&original).unwrap(); + changed_schema["properties"]["summary"]["maxLength"] = json!(159); + fixture.replace_context_schema(action, &serde_json::to_vec(&changed_schema).unwrap(), true); + check_refused(); + + let mut oversized = original.clone(); + oversized.resize(SCHEMA_LIMIT + 1, b' '); + fixture.replace_context_schema(action, &oversized, true); + check_refused(); + + fixture.replace_context_schema(action, &original, true); + fixture.replace_context_index_path(action, "generated/review-context-schemas/missing.json"); + check_refused(); + fixture.replace_context_index_path( + action, + "generated/review-context-schemas/../review-context-schemas/accept-repair.schema.json", + ); + check_refused(); + + fs::write( + fixture + .root() + .join("registry/context-schemas/named-export.schema.json"), + &original, + ) + .unwrap(); + fixture.replace_context_index_path( + action, + "generated/review-context-schemas/named-export.schema.json", + ); + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); + + fixture.replace_context_index_path( + action, + "generated/review-context-schemas/accept-repair.schema.json", + ); + oversized.truncate(SCHEMA_LIMIT); + fixture.replace_context_schema(action, &oversized, true); + let output = fixture.run(&[]); + assert!(output.status.success(), "{output:?}"); +} + +#[path = "fixtures/service_review/mod.rs"] +mod service_review; +use service_review::ReviewFixture; + #[test] fn client_generate_refuses_session_with_or_without_checked_routes() { let fixture = Fixture::new(); diff --git a/deploy/README.md b/deploy/README.md index e15a811c45..58973e9412 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -321,6 +321,7 @@ The `[[ ... ]]` line fails unless the host computes the bundle digest the export Generate the Session runtime file and its gateway from the Compose source with the matching `registry-session`, together with the chart's copies of the Compose BReg runtime file and identity deployment. The ingress controller terminates TLS, so generate without TLS and with the public HTTPS origin. If you already ran this for [Prepare and start BReg](#prepare-and-start-breg), reuse that `one-host/`: the command refuses an existing output directory. ```bash +umask 077 python3 "$RELEASE/deploy/one_host_config.py" --session-bin /path/to/registry-session \ --source "$RELEASE/deploy/examples/business-registration/session.yaml" \ --breg-runtime "$RELEASE/deploy/examples/business-registration/breg-runtime.yaml" \ diff --git a/deploy/helm/registry-stack/README.md b/deploy/helm/registry-stack/README.md index d2a077bbd1..09ce84f0bb 100644 --- a/deploy/helm/registry-stack/README.md +++ b/deploy/helm/registry-stack/README.md @@ -412,6 +412,7 @@ deployment. Use the `bregctl` and `rstack` of that same commit or release with them: v0.52.0's BReg tools refuse this `v1` BReg runtime file. ```bash +umask 077 python3 deploy/one_host_config.py --session-bin /path/to/registry-session \ --source deploy/examples/business-registration/session.yaml \ --breg-runtime deploy/examples/business-registration/breg-runtime.yaml \ diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index def16178ff..d90e983b7a 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -864,7 +864,46 @@ tokens under the issuer's own policy. ### Native review handoff -For a native review handoff, `bindings.bregReviewAuthority` identifies the Casework producer, and `bindings.caseworkContextProvider` identifies the BReg context provider and action. +Declare the BReg and Casework projects under `products` in `service.yaml`. +With the matching `bregctl` and `caseworkctl` tools installed, inspect the reusable review wiring: + +```sh +rstack service plan service.yaml --format json +``` + +The `reviewWiring` output names the BReg Action, the Casework policy and provider, and their exact context contract. +The planner matches Actions to policies declared by the service's Casework project. +Use `bregctl` and `caseworkctl` from the same build. +Use a separate service per local review pair. The development runner has one authority and one provider slot. +Choose a provider with `human-display` and `service-status` for this pair. If it declares a `description`, use a path under `context-providers/`. +If you omit `description`, leave its default destination `context-providers/.json` unused. +Give every other Casework provider its own description file when you [pair its export](../casework/#pair-and-verify-the-export). +Set deployment URLs and credential references in each product's runtime configuration. +In `casework.yaml`, `trustedProducers` pins each producer's issuer, access profile and subject. +Set any initiator trust and requester-read rules in the same Casework policy. +If a selected review stage excludes the initiator, the BReg Action must grant Proposal Submit to a profile that can admit a human. + +In `dev.yaml`, keep the issuer, audiences, test people and journey file. The two bindings choose the Casework producer and the local identities: + +```yaml title="dev.yaml" +bindings: + bregReviewAuthority: + producer: review-producer + identity: review-requester + caseworkContextProvider: + identity: source-status +``` + +Choose a `trustedProducers` entry that admits the authored policy and source namespace. +Use that producer's exact issuer or set `issuer: run` with `runIssuerBinding` on `bregReviewAuthority`. +Use the same fixed issuer in the plan and the producer when retaining active reviews across starts. Each run with `issuer: run` chooses an ephemeral issuer URL. Casework keeps the original producer issuer on active reviews. +Omit `externalJwksUri` with abbreviated review bindings so both products trust the key that signs the run's machine tokens. +Set each `identity` to a test person whose role grants the matching access profile. +The BReg review binding's test person must also use the subject pinned by the selected Casework producer. +If the producer pins the human initiator, use the same issuer as BReg and its selected principal claim. Include an initiator guard in `runIssuerBinding` when using `issuer: run`. +You can also keep an existing `dev.yaml` with its own `products` and complete explicit bindings. +When upgrading a policy that sets `trustedInitiatorIssuer`, read BReg's principal claim from `bregctl explain access --format json PROJECT`. +Use the same claim in the Casework producer's `trustedInitiatorPrincipalClaim` and [all human Casework access profiles](../casework/#read-the-review-policy-and-its-producer). `rstack dev check` refuses a binding that names a review authority or action the BReg project does not declare, or a producer or context provider the Casework project does not declare. `start` refuses it before it provisions anything. `check` also writes each binding's product configuration exactly as `start` does. @@ -884,7 +923,15 @@ Authored journey steps that call Casework with `Registry-Source-Profile` automat The retired `caseworkContext` key on a person is refused with migration guidance. The native review example at `products/breg/acceptance/reviewed-evidence-journey/dev.yaml` shows this layout. -{/* Evidence: crates/registry-rstack-dev/src/products.rs service-status; +{/* Evidence: crates/registry-platform-config/src/service_authoring.rs usable_pair_description; + crates/registry-casework/src/pinned_work.rs compare_pinned_work. */} + +{/* Evidence: crates/registry-platform-config/src/service_authoring.rs inspect_review; + crates/registry-platform-config/src/service_compiler.rs connect_review; + crates/registry-breg/src/runtime_config.rs ReviewAuthorityConfig; + crates/registry-casework-breg/src/config.rs BregBinding; + crates/registry-casework-core/src/config.rs ReviewProducerPolicy; + crates/registry-rstack-dev/src/products.rs service-status; crates/registry-rstack-dev/src/bindings.rs bregReviewAuthority, caseworkContextProvider, humanSourceAuthentication; crates/registry-rstack-dev/src/plan.rs caseworkContext; products/breg/acceptance/reviewed-evidence-journey/dev.yaml. */} @@ -1155,8 +1202,13 @@ Each start allocates a reservation and signing key and prepares and packages the The kernel may later recycle a port; that does not reuse an old key or run. Fixed HTTPS product-only plans remain unchanged. -An authored exact Casework policy version or digest selection is never rewritten by source binding. -If the newly packaged policy no longer matches that selection, the ordinary product refusal remains authoritative. +A strict BReg policy selection pins both the version and the digest. +The compiled digest includes every trusted producer that lists the policy. +Changing either issuer field on one of those producers changes the digest and leaves the BReg pin intact. +With abbreviated review bindings, `check` and `start` refuse such a `runIssuerBinding` before provisioning. +To keep the pin, use a fixed issuer and omit `runIssuerBinding` for the policy's producers. +To bind one of those producers to the run issuer, select the policy by ID alone. +Casework refuses a new review request when its pin differs from the active policy. Without `application`, the exact paired binding starts only product APIs. It requires no application root, Node, or host build and admits no browser client. @@ -1168,6 +1220,12 @@ The worker holds the reservation until cleanup. {/* Evidence: crates/registry-rstack-dev/src/bindings.rs runIssuerBinding, run-test-people; crates/registry-rstack-dev/src/plan.rs runIssuerBinding; crates/registry-rstack-dev/src/lib.rs casework-bound; + crates/registry-rstack-dev/src/products.rs bind_casework_run_issuer; + crates/registry-platform-config/src/service_compiler.rs connect_review; + crates/registry-casework-core/src/config.rs policy_dependencies; + crates/registry-casework-core/src/review.rs digest_with; + crates/registry-casework/src/review.rs ReviewRuntimeError::PolicyMismatch; + crates/registry-review-protocol/src/lib.rs PolicySelection::matches; crates/registry-rstack/tests/dev_run.rs casework_run_issuer_mismatch_names_the_dev_yaml_pointer. */} ### Bind the Coordinator as a Casework review producer diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 3651a1281d..977ace8857 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -7122,7 +7122,7 @@ "description": "rstack error report JSON Schema.", "source": { "path": "crates/registry-rstack/src/cli.rs", - "sha256": "978bdd66d8f286fef29057ffce9bf9cb3f64dc55ecefed2dcb66c25ecf4d6313" + "sha256": "cf73e55a8b1497e0115021d747ccf2d2bfbed389fa108184d38590cb0fd6140a" }, "artifact": { "path": "products/platform/schemas/rstack-dev-error.v1.schema.json", @@ -7270,7 +7270,7 @@ }, "artifact": { "path": "products/platform/generated/dev/dev.v1alpha1.schema.json", - "sha256": "a5fe26d9a001472e4e3a3a2574b80df8fca2d3bcd4efa55fde2f371a1ec8a109", + "sha256": "9a7e2b98ae00a38f34d32dd6df245d3e8e64278aed3c4603ab02b4e01c073f39", "mediaType": "application/schema+json" } }, diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index a93e6c1717..123642c280 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- `rstack service plan` reports a native BReg and Casework review pair from the + projects in `service.yaml`. The report includes the exact context contract. + The development plan can reuse the authority, Action and provider from that + pair. Keep its producer selection and local identities in `dev.yaml`. + Existing development plans with full bindings remain supported. + - Update Wasmtime LTS to 48.0.11 in the platform executor and BReg handler SDK for RUSTSEC-2026-0633 to RUSTSEC-2026-0643 and RUSTSEC-2026-0646 to RUSTSEC-2026-0648. diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index 2a1af75983..30d862b681 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -317,7 +317,7 @@ "properties": { "id": { "$ref": "#/$defs/LocalId", - "description": "Local identifier of the review authority." + "description": "Local identifier of the review authority. Omit it to use the exact review wiring of the sibling service." }, "identity": { "$ref": "#/$defs/LocalId", @@ -333,7 +333,6 @@ } }, "required": [ - "id", "producer", "identity" ], @@ -345,11 +344,11 @@ "properties": { "action": { "$ref": "#/$defs/LocalId", - "description": "Local identifier of the BReg action that the provider pairs with." + "description": "Local identifier of the BReg Action that the provider pairs with. Omit it to use the exact review wiring of the sibling service." }, "id": { "$ref": "#/$defs/LocalId", - "description": "Local identifier of the context provider." + "description": "Local identifier of the context provider. Omit it to use the exact review wiring of the sibling service." }, "identity": { "$ref": "#/$defs/LocalId", @@ -357,9 +356,7 @@ } }, "required": [ - "id", - "identity", - "action" + "identity" ], "type": "object" }, diff --git a/products/platform/scripts/test-rstack-dev.py b/products/platform/scripts/test-rstack-dev.py index ef58824a4c..14fd395a35 100644 --- a/products/platform/scripts/test-rstack-dev.py +++ b/products/platform/scripts/test-rstack-dev.py @@ -1276,18 +1276,40 @@ def verify_native_handoff(root, bin_dir, env): shutil.copyfile( NATIVE_REVIEW / "dev-journeys.yaml", checkout / "dev-journeys.yaml" ) - before = files(checkout) - report = dev(bin_dir, env, checkout, "start", ".") - try: - [scenario] = report["scenarios"] - assert scenario["id"] == "native-review-ask-answer-handoff" - assert scenario["result"] == "passed" - assert files(checkout) == before - print( - "Native review handoff, Ask and Answer exchange, and separately authorized BReg apply passed" - ) - finally: - dev(bin_dir, env, checkout, "stop", report["run_id"]) + for form in ("explicit", "abbreviated"): + if form == "abbreviated": + service_path = checkout / "service.yaml" + dev_path = checkout / "dev.yaml" + casework_path = checkout / "casework" / "casework.yaml" + service = yaml.safe_load(service_path.read_text()) + plan = yaml.safe_load(dev_path.read_text()) + casework = yaml.safe_load(casework_path.read_text()) + service["products"] = plan.pop("products") + plan["bindings"]["bregReviewAuthority"].pop("id") + selected = plan["bindings"]["caseworkContextProvider"] + provider_id = selected.pop("id") + selected.pop("action") + casework["contextProviders"][provider_id]["deploymentRef"] = "review-runtime" + for path, contents in ( + (service_path, service), (dev_path, plan), (casework_path, casework), + ): + path.write_text(yaml.safe_dump(contents, sort_keys=False)) + + before = files(checkout) + report = dev(bin_dir, env, checkout, "start", ".") + try: + [scenario] = report["scenarios"] + assert scenario["id"] == "native-review-ask-answer-handoff" + assert scenario["result"] == "passed" + if form == "abbreviated": + run_root = Path(env["RSTACK_DEV_STATE_DIR"]) / report["run_id"] + runtime = run_root / "casework-runtime.yaml" + providers = yaml.safe_load(runtime.read_text())["contextProviders"] + assert set(providers) == {"review-runtime"} + assert files(checkout) == before + print(f"Native review handoff passed with {form} bindings") + finally: + assert dev(bin_dir, env, checkout, "stop", report["run_id"])["status"] == "stopped" def spatial_project(root, name): From 0d0f705fc3ec0084da12823b11c54b260c6efb26 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 07:44:51 +0000 Subject: [PATCH 02/18] fix(rstack): prepare paired Casework before changing managed state Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/lib.rs | 2 +- crates/registry-rstack-dev/src/products.rs | 70 ++++++++++++---------- crates/registry-rstack/tests/dev_run.rs | 59 ++++++++++++++---- 3 files changed, 89 insertions(+), 42 deletions(-) diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index dc74900c77..5085095a44 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -1748,7 +1748,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { let prepared = catch_startup(|| { products.capture_preview_project()?; products.check()?; - products.prepare_casework_run_issuer()?; + products.prepare_casework()?; if let Some(artifact) = &preview_artifact { products.build_preview(artifact)?; } diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 2a41d17222..2b8005df50 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -399,7 +399,7 @@ pub(super) struct ProductRunner<'a> { input: Arc, root: &'a Path, preview_project: Option, - bound_casework_project: Option, + prepared_casework_project: Option, terminate: &'a AtomicBool, deadline: Instant, runtime: tokio::runtime::Runtime, @@ -441,7 +441,7 @@ impl<'a> ProductRunner<'a> { input, root, preview_project: None, - bound_casework_project: None, + prepared_casework_project: None, terminate, deadline: Instant::now() + Duration::from_secs(300), runtime: tokio::runtime::Builder::new_current_thread() @@ -542,8 +542,8 @@ impl<'a> ProductRunner<'a> { if entry.product == Product::Casework && self.input.plan.bindings.casework_context_provider.is_some() { - // The owning tool validates the paired provider export before - // packaging; the published source is left intact. + // Inspection checks the authored policy. The owning tool + // checks the imported provider export after pairing. continue; } let project = self.product_project(entry); @@ -586,22 +586,37 @@ impl<'a> ProductRunner<'a> { Ok(()) } - pub(super) fn prepare_casework_run_issuer(&mut self) -> Result<()> { + /// Prepare the private project that activation will pair and package. + pub(super) fn prepare_casework(&mut self) -> Result<()> { let plan = &self.input.plan; - if !self.input.automatic_review || !has_run_source(plan) { + let run_issuer = has_run_source(plan); + if !run_issuer && plan.bindings.casework_context_provider.is_none() { return Ok(()); } self.ensure_active()?; let project = product_root(&self.input.project, plan, Product::Casework)? - .context("missing Casework project for automatic review")?; - let bound = SelectedProduct { + .context("missing Casework project for review")?; + let prepared = SelectedProduct { field: project.field, - root: self.root.join("casework-bound"), + root: self.root.join(if run_issuer { + "casework-bound" + } else { + "casework-paired" + }), }; - bind_casework_run_issuer(plan, &project.root, &bound.root)?; - let report = self.projected_casework_report(&bound.root); - check_projected_casework(&bound, report, stopping(self.root, self.terminate))?; - self.bound_casework_project = Some(bound.root); + if run_issuer { + bind_casework_run_issuer(plan, &project.root, &prepared.root)?; + if self.input.automatic_review { + let report = self.projected_casework_report(&prepared.root); + check_projected_casework(&prepared, report, stopping(self.root, self.terminate))?; + } else { + self.tool(Product::Casework, "check", &[prepared.root.as_os_str()])?; + } + } else { + copy_project(&project.root, &prepared.root)?; + } + self.ensure_active()?; + self.prepared_casework_project = Some(prepared.root); Ok(()) } @@ -1528,29 +1543,25 @@ impl<'a> ProductRunner<'a> { bind: &str, breg_package: Option<&Path>, ) -> Result { - let bound; - let project = if let Some(bound) = &self.bound_casework_project { - bound.as_path() - } else if has_run_source(&self.input.plan) { - bound = self.root.join("casework-bound"); - bind_casework_run_issuer(&self.input.plan, project, &bound)?; - self.tool(Product::Casework, "check", &[bound.as_os_str()])?; - bound.as_path() + let binding = self.input.plan.bindings.casework_context_provider.as_ref(); + let project = if binding.is_some() || has_run_source(&self.input.plan) { + self.prepared_casework_project + .as_deref() + .context("missing prepared Casework project")? } else { project }; - let paired; - let project = if let Some(binding) = &self.input.plan.bindings.casework_context_provider { + if let Some(binding) = binding { + // Pair against the exact package verified by BReg activation, + // including when a retained package is reused. let source = breg_package.context("the Casework context provider needs the BReg package")?; - paired = self.root.join("casework-paired"); - copy_project(project, &paired)?; self.tool( Product::Casework, "provider", &[ "pair".as_ref(), - paired.as_os_str(), + project.as_os_str(), "--provider-id".as_ref(), binding.id.as_ref(), "--breg-package".as_ref(), @@ -1562,11 +1573,8 @@ impl<'a> ProductRunner<'a> { "--apply".as_ref(), ], )?; - self.tool(Product::Casework, "check", &[paired.as_os_str()])?; - &paired - } else { - project - }; + self.tool(Product::Casework, "check", &[project.as_os_str()])?; + } let package = self.root.join("casework-package"); self.tool( Product::Casework, diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 49dfb3c544..03e5d2cb86 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -4818,14 +4818,18 @@ fn casework_run_issuer_binding_needs_no_run_source_command() { "the runner must not call generate run-source: {calls}\n{report}" ); let state = run.state.canonicalize().unwrap_or(run.state); - assert!( - calls - .lines() - .any(|line| line.starts_with("--format json check ") - && line.contains(utf8(&state)) - && line.ends_with("/casework-bound")), - "the runner checks the bound copy with the public check: {calls}\n{report}" - ); + let prepared = calls + .lines() + .filter_map(|line| line.strip_prefix("--format json check ")) + .find(|path| path.contains(utf8(&state)) && path.ends_with("/casework-bound")) + .unwrap_or_else(|| panic!("the runner did not check the bound copy: {calls}\n{report}")); + for (command, argument) in [("provider pair", "--provider-id"), ("package", "--output")] { + let invocation = format!("{command} {prepared} {argument} "); + assert!( + calls.lines().any(|line| line.starts_with(&invocation)), + "the runner did not reuse the prepared copy: {calls}\n{report}" + ); + } } #[test] @@ -4838,6 +4842,7 @@ fn refused_supervisor_startup_preserves_managed_project_state() { ("docker", true, true), ("docker", false, false), ("refusal", true, true), + ("pair-copy", true, true), ] { let scratch = tempfile::tempdir().unwrap(); let fixture = scratch.path().canonicalize().unwrap(); @@ -4861,6 +4866,15 @@ trustedProducers: ) .unwrap(); + let fixed_issuer_pair = stop_at == "pair-copy"; + if fixed_issuer_pair { + symlink( + project.join("casework/casework.yaml"), + project.join("casework/private-copy-canary"), + ) + .unwrap(); + } + let mut hash = Sha256::new(); hash.update(project.as_os_str().as_encoded_bytes()); hash.update([0]); @@ -4909,6 +4923,10 @@ printf '%s\n' '{"apiVersion":"id.registrystack.org/formats/casework/report/v1"," &docker, r#"#!/usr/bin/env bash set -euo pipefail +if [[ "$STOP_AT" == pair-copy ]]; then + printf '%s\n' "$1" >>"$FAKE_DOCKER_STATE/argv.log" + exit 1 +fi if [[ "$1" == run ]]; then printf 'unexpected managed database start\n' >&2 exit 1 @@ -4923,7 +4941,7 @@ fi for tool in [&casework, &docker] { fs::set_permissions(tool, fs::Permissions::from_mode(0o700)).unwrap(); } - let input = serde_json::json!({ + let mut input = serde_json::json!({ "run_id": RUN_ID, "project": project, "ttl_seconds": 60, "plan": { "issuer": "run", "journeyFile": "dev-journeys.yaml", @@ -4946,6 +4964,17 @@ fi "casework": {"tool": casework, "runtime": system_binary("false")} } }); + if fixed_issuer_pair { + input["plan"]["issuer"] = serde_json::json!("https://issuer.example.invalid"); + input["plan"]["bindings"] = serde_json::json!({ + "caseworkContextProvider": { + "id": "proposal-context", "identity": "producer", "action": "review-action" + } + }); + input["plan"]["people"]["producer"]["grants"]["breg"] = + serde_json::json!({"profile": "operator", "scopes": ["registry:read"]}); + input["automatic_review"] = serde_json::json!(false); + } fs::write(root.join("input.json"), input.to_string()).unwrap(); let fake_path = fake_docker_path(); @@ -4993,10 +5022,20 @@ fi !state.join("failed").exists(), "the projected stderr should be discarded" ); + } else if fixed_issuer_pair { + let error = report["error"].as_str().unwrap(); + assert!( + error.contains("Casework project contains a symlink or non-file entry"), + "{error}" + ); + assert!(!error.contains("private-copy-canary"), "{error}"); } else { assert_eq!(report["error"], "development run was stopped", "{report}"); } - assert!(fixture.join("casework-started").exists()); + assert_eq!( + fixture.join("casework-started").exists(), + !fixed_issuer_pair + ); assert!(!fixture.join("casework-finished").exists()); assert!(!root.exists(), "the stopped supervisor did not clean up"); assert_eq!(fs::read_to_string(marker).unwrap(), "fixture-generation"); From 778bb2fb37f605c3a7ed51971f729b41d59cd363 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 07:58:14 +0000 Subject: [PATCH 03/18] fix(casework): make private development copies writable Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/products.rs | 16 ++++++++++++---- crates/registry-rstack/tests/dev_run.rs | 21 +++++++++++++++------ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 2b8005df50..18202a9ad4 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -2841,7 +2841,8 @@ fn random_secret() -> Result> { /// Copies a project into the run. The copy is private to the owner whatever /// the caller's umask, because products refuse a secret directory that other -/// users can read. +/// users can read. Copied files are writable so provider pairing can update +/// them in place. fn copy_project(source: &Path, target: &Path) -> Result<()> { fn copy_dir( source: &Path, @@ -2880,7 +2881,7 @@ fn copy_project(source: &Path, target: &Path) -> Result<()> { "Casework project exceeds the copy size limit" ); fs::copy(entry.path(), &destination)?; - let owner_only = info.permissions().mode() & 0o700; + let owner_only = 0o600 | (info.permissions().mode() & 0o100); fs::set_permissions(&destination, fs::Permissions::from_mode(owner_only))?; } } @@ -5113,11 +5114,11 @@ mod tests { fs::write(source.join("keys/signing.key"), "secret").unwrap(); fs::set_permissions( source.join("keys/signing.key"), - fs::Permissions::from_mode(0o644), + fs::Permissions::from_mode(0o444), ) .unwrap(); fs::write(source.join("run.sh"), "#!/bin/sh\n").unwrap(); - fs::set_permissions(source.join("run.sh"), fs::Permissions::from_mode(0o755)).unwrap(); + fs::set_permissions(source.join("run.sh"), fs::Permissions::from_mode(0o555)).unwrap(); let target = scratch.path().join("copy"); copy_project(&source, &target).unwrap(); let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777; @@ -5125,6 +5126,13 @@ mod tests { assert_eq!(mode(&target.join("keys")), 0o700); assert_eq!(mode(&target.join("keys/signing.key")), 0o600); assert_eq!(mode(&target.join("run.sh")), 0o700); + fs::write(target.join("keys/signing.key"), "replacement").unwrap(); + assert_eq!(mode(&source.join("keys/signing.key")), 0o444); + assert_eq!(mode(&source.join("run.sh")), 0o555); + assert_eq!( + fs::read_to_string(source.join("keys/signing.key")).unwrap(), + "secret" + ); } #[test] diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 03e5d2cb86..6f93e5aedd 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -4812,22 +4812,31 @@ fn casework_run_issuer_binding_needs_no_run_source_command() { let output = run.start(&run.bin.join("bregctl"), &caseworkctl); let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); run.stop(&report); + assert!( + output.status.success(), + "native start exited with {}: {report}", + output.status + ); let calls = run.calls("caseworkctl"); assert!( !calls.contains("run-source"), "the runner must not call generate run-source: {calls}\n{report}" ); let state = run.state.canonicalize().unwrap_or(run.state); - let prepared = calls - .lines() - .filter_map(|line| line.strip_prefix("--format json check ")) - .find(|path| path.contains(utf8(&state)) && path.ends_with("/casework-bound")) + let mut invocations = calls.lines(); + let prepared = invocations + .by_ref() + .filter_map(|line| line.strip_prefix("check ")?.strip_suffix(" --format json")) + .find(|path| { + let path = std::path::Path::new(path); + path.starts_with(&state) && path.ends_with("casework-bound") + }) .unwrap_or_else(|| panic!("the runner did not check the bound copy: {calls}\n{report}")); for (command, argument) in [("provider pair", "--provider-id"), ("package", "--output")] { let invocation = format!("{command} {prepared} {argument} "); assert!( - calls.lines().any(|line| line.starts_with(&invocation)), - "the runner did not reuse the prepared copy: {calls}\n{report}" + invocations.any(|line| line.starts_with(&invocation)), + "{command} did not reuse the prepared copy: {calls}\n{report}" ); } } From 43bb468d388873461f43bb78a5732e2183a4a9ab Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:00:38 +0000 Subject: [PATCH 04/18] fix(rstack): validate paired description package paths Signed-off-by: Jeremi Joslin --- .../registry-platform-config/src/package.rs | 2 +- .../src/service_authoring.rs | 23 +++++++- crates/registry-rstack/tests/service_plan.rs | 52 +++++++++++++++++++ 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/registry-platform-config/src/package.rs b/crates/registry-platform-config/src/package.rs index 7f1678d878..0fc718b323 100644 --- a/crates/registry-platform-config/src/package.rs +++ b/crates/registry-platform-config/src/package.rs @@ -710,7 +710,7 @@ fn visit( /// A relative path the sum file can carry unescaped and every supported /// platform can store. -fn check_path(path: &str, limits: &PackageLimits) -> Result<(), PackageErrorKind> { +pub(crate) fn check_path(path: &str, limits: &PackageLimits) -> Result<(), PackageErrorKind> { if path.len() > limits.max_path_bytes { return Err(PackageErrorKind::Bound { path: Some(path.to_owned()), diff --git a/crates/registry-platform-config/src/service_authoring.rs b/crates/registry-platform-config/src/service_authoring.rs index ab2fbb7f12..050bbe87d5 100644 --- a/crates/registry-platform-config/src/service_authoring.rs +++ b/crates/registry-platform-config/src/service_authoring.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Resolve a native review pair from the products' offline compiler reports. +use crate::package::{check_path, PackageLimits}; use crate::service_compiler::{Product, ReviewContextContract, ReviewWiring}; use crate::sha256_uri; use registry_platform_canonical_json::{ @@ -377,7 +378,7 @@ pub fn inspect_review( )); } let cases = casework_facts.expect("the Casework project was inspected"); - let mut retained = cases + let retained = cases .context_providers .iter() .filter(|provider| provider.id != pair.context_provider); @@ -413,13 +414,31 @@ pub fn inspect_review( } // Pairing supplies only the selected description. Casework's production // package check requires one for every provider in the project. - if retained.any(|provider| provider.description.is_none()) { + if retained + .clone() + .any(|provider| provider.description.is_none()) + { return Err(problem( service, "rstack.service.review-retained-provider-unpaired", casework.source_pointer(), "A retained Casework context provider has no paired description required by the production package check.", "Run caseworkctl provider pair for the remaining providers before planning this local pair.", )); } + // Casework narrows the per-file size but uses the default package path limits. + let limits = PackageLimits::default(); + if std::iter::once(description) + .chain(retained.filter_map(|provider| provider.description.as_deref())) + .any(|path| check_path(path, &limits).is_err()) + { + return Err(problem( + service, "rstack.service.review-provider-description", casework.source_pointer(), + "A Casework provider description path cannot be included in the package.", + &format!( + "Use a project-relative description path of at most {} bytes and {} components. Use single slash separators and remove dot components, backslashes, and control characters.", + limits.max_path_bytes, limits.max_depth, + ), + )); + } Ok(Some(pair)) } diff --git a/crates/registry-rstack/tests/service_plan.rs b/crates/registry-rstack/tests/service_plan.rs index abc340b65c..b3e38886dc 100644 --- a/crates/registry-rstack/tests/service_plan.rs +++ b/crates/registry-rstack/tests/service_plan.rs @@ -718,6 +718,58 @@ fn refuses_local_review_wiring_for_a_description_native_pairing_rejects() { assert_eq!(fs::read(destination).unwrap(), original); } +#[test] +fn refuses_review_descriptions_that_cannot_be_packaged() { + let paths = [ + "context-providers/unportable\\export.json".to_owned(), + "context-providers/unportable\texport.json".to_owned(), + "context-providers//unportable-export.json".to_owned(), + format!("context-providers/{}deep-export.json", "nested/".repeat(15)), + format!( + "context-providers/{}/{}/long-export.json", + "a".repeat(240), + "b".repeat(240), + ), + ]; + for selected in [true, false] { + let fixture = strict_review_fixture(); + let mut report = fixture.read_json("casework/explanation.json"); + let index: usize = if selected { + 0 + } else { + let mut retained = report["contextProviders"][0].clone(); + retained["id"] = json!("retained-summary"); + retained["deploymentRef"] = json!("retained-slot"); + report["contextProviders"] + .as_array_mut() + .unwrap() + .push(retained); + 1 + }; + for path in &paths { + fixture.write_provider_description(path, "workshop", "accept-repair", "tool-desk"); + report["contextProviders"][index]["description"] = json!(path); + fixture.write_casework(report.clone()); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-description", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert!(refusal["diagnostics"][0]["suggestedAction"] + .as_str() + .unwrap() + .contains("project-relative")); + let encoded_path = json!(path).to_string(); + assert!(!refusal.to_string().contains(encoded_path.trim_matches('"'))); + } + } + } +} + #[test] fn refuses_an_implicit_description_over_a_casework_display_schema() { let fixture = strict_review_fixture(); From 84819b8701254a4ab0ebb17dbfc9645de002a585 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:24:51 +0000 Subject: [PATCH 05/18] fix(rstack): protect managed state from invalid Casework packages Signed-off-by: Jeremi Joslin --- crates/registry-caseworkctl/src/lib.rs | 6 + crates/registry-caseworkctl/src/project.rs | 103 +++++++- .../registry-caseworkctl/src/provider_pair.rs | 221 ++++++++++++++++-- .../registry-platform-config/src/package.rs | 43 +++- .../src/service_authoring.rs | 68 +++--- crates/registry-rstack-dev/src/products.rs | 59 +++-- crates/registry-rstack/tests/dev_run.rs | 51 +++- .../tests/fixtures/service_review/mod.rs | 25 +- crates/registry-rstack/tests/service_plan.rs | 76 +++++- .../run-a-project-with-rstack-dev.mdx | 4 +- 10 files changed, 567 insertions(+), 89 deletions(-) diff --git a/crates/registry-caseworkctl/src/lib.rs b/crates/registry-caseworkctl/src/lib.rs index abdd29197a..12c6e54380 100644 --- a/crates/registry-caseworkctl/src/lib.rs +++ b/crates/registry-caseworkctl/src/lib.rs @@ -301,6 +301,9 @@ struct CheckArgs { /// Resolve configured environment substitutions while checking the runtime file. #[arg(long, requires = "runtime_config")] environment: bool, + /// Internal local review preflight, before BReg activation supplies the export. + #[arg(long, hide = true, conflicts_with_all = ["runtime_config", "against_breg_package", "production", "require_package_closure", "deny_warnings"])] + review_package_provider: Option, } pub fn command() -> clap::Command { Cli::command() @@ -822,6 +825,9 @@ fn run(command: Command, posture: Option) -> Result { project, template, .. } => project::init(&project, &template), Command::Check(args) => { + if let Some(provider) = args.review_package_provider.as_deref() { + return project::check_review_package(&args.project, provider); + } let require_package_closure = args.require_package_closure || args.production; let mut result = if args.runtime_config.is_some() { project::check(&args.project, require_package_closure, false) diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index 5088445977..9ebf299602 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -9,8 +9,8 @@ use registry_casework_core::{ ReviewContextProviderPolicy, }; use registry_platform_config::{ - plan_package, write_package, DeclaredPosture, DevelopmentWitness, LoadedRuntimeConfig, Posture, - SecretResolver, + package::file_destination_available, plan_package, write_package, DeclaredPosture, + DevelopmentWitness, LoadedRuntimeConfig, Posture, SecretResolver, }; use registry_platform_yaml::{Decoded, Diagnostic, Expect, Reader, Report, Severity, Source}; use serde_json::{json, Value}; @@ -35,6 +35,7 @@ pub(crate) enum ProjectRefusal { ProjectInputPathInvalid, ProjectInputOutside, PackageInputInvalid, + ReviewPackageDestination, ContextSchemaTooDeep, ProviderExportInvalid, ProviderNamespaceMismatch, @@ -70,6 +71,9 @@ impl std::fmt::Display for ProjectRefusal { Self::PackageInputInvalid => { formatter.write_str("input must be a regular file of at most one MiB") } + Self::ReviewPackageDestination => { + formatter.write_str("the provider description destination is occupied or shared") + } Self::ContextSchemaTooDeep => { formatter.write_str("context schema type nesting exceeds 16") } @@ -891,24 +895,113 @@ pub(crate) fn package_contents(project: &Path) -> Result, + pending_description: Option<&str>, +) -> Result>> { + let mut paths = registry_casework::package_inputs(policy, &policy_bytes)?; paths.remove(registry_casework::POLICY_FILE); let mut inputs = BTreeMap::from([(registry_casework::POLICY_FILE.to_owned(), policy_bytes)]); for path in paths { - let bytes = read_package_input(&project_input_path(project, &path)?)?; + // Native pairing supplies this file after BReg verifies the exact + // activated package. Reserve its name in the planned closure now. + let bytes = if pending_description == Some(path.as_str()) { + Vec::new() + } else { + read_package_input(&project_input_path(project, &path)?)? + }; inputs.insert(path, bytes); } for provider in &policy.context_providers { if let Some(description) = &provider.description { + if pending_description == Some(description.as_str()) { + continue; + } let bytes = inputs .get(description) .ok_or(ProjectRefusal::PackageInputInvalid)?; let export = decode_context_export(description, bytes)?; - check_provider_export(&policy, provider, &export)?; + check_provider_export(policy, provider, &export)?; } } Ok(inputs) } + +/// Plan the Casework side of a review package before the producer package is +/// available. The final package command checks the supplied description bytes. +pub(super) fn check_review_package(project: &Path, id: &str) -> Result { + let refused = || -> anyhow::Error { + Report::new(vec![Diagnostic::error( + "caseworkctl.refused", + "runtime", + "The prospective Casework package inputs cannot be packaged.", + "Correct the Casework package inputs and resolve authoring warnings, then retry.", + )]) + .into() + }; + let report = check(project, false, true).map_err(|error| { + // A warnings-only package refusal still needs an error diagnostic + // for the runner to recognize the owner report as a domain refusal. + if crate::configuration_report(&error).is_some_and(|report| !report.has_errors()) { + refused() + } else { + error + } + })?; + let policy_file = project.join(registry_casework::POLICY_FILE); + let original = read_package_input(&policy_file)?; + let name = policy_file.display().to_string(); + let decoded = CaseworkProject::read(&name, &original)?; + let provider = decoded + .value + .context_providers + .iter() + .find(|provider| provider.id == id) + .ok_or(crate::provider_pair::PairingFailure::ProviderNotDeclared)?; + let relative = crate::provider_pair::pairing_description(provider)?; + let destination = Path::new(&relative); + if decoded.value.context_providers.iter().any(|other| { + other.id != provider.id && other.description.as_deref().map(Path::new) == Some(destination) + }) { + return Err(ProjectRefusal::ReviewPackageDestination.into()); + } + // The projected export is its own package input. A display schema at + // this destination would be overwritten by the producer export envelope. + if CaseworkProject::schema_references(&name, &original)? + .iter() + .any(|path| Path::new(path) == destination) + { + return Err(ProjectRefusal::ReviewPackageDestination.into()); + } + let declared = provider.description.is_some(); + let (policy, bytes) = if declared { + (decoded.value, original) + } else { + let bytes = crate::provider_pair::policy_with_description( + decoded.document.to_json_value(), + &original, + id, + &relative, + )?; + let projected = CaseworkProject::read(&name, &bytes)?; + if registry_platform_config::has_denied_warnings(&projected.document.warnings()) { + return Err(refused()); + } + (projected.value, bytes) + }; + let inputs = capture_package_inputs(project, &policy, bytes, Some(&relative))?; + plan_package(project, &inputs, None, &package_limits(), PACKAGE_COMMAND) + .map_err(|_| refused())?; + if !file_destination_available(project, destination, declared) { + return Err(ProjectRefusal::ReviewPackageDestination.into()); + } + Ok(report) +} pub(super) fn package(project: &Path, output: &Path, revision: Option<&str>) -> Result { let inputs = package_contents(project)?; let written = write_package( diff --git a/crates/registry-caseworkctl/src/provider_pair.rs b/crates/registry-caseworkctl/src/provider_pair.rs index 6ea1061ce4..f3bd661018 100644 --- a/crates/registry-caseworkctl/src/provider_pair.rs +++ b/crates/registry-caseworkctl/src/provider_pair.rs @@ -235,6 +235,39 @@ pub(super) fn compare( json!({"package":package,"packageDigest":verified.digest(),"agreements":compared,"networkAccess":false,"databaseAccess":false}), ) } +pub(super) fn pairing_description( + provider: ®istry_casework_core::ReviewContextProviderPolicy, +) -> Result { + let relative = provider + .description + .clone() + .unwrap_or_else(|| format!("context-providers/{}.json", provider.id)); + if !relative.starts_with("context-providers/") || relative.contains("..") { + return Err(PairingFailure::DescriptionPathInvalid { + path: format!("/contextProviders/{}/description", provider.id), + } + .into()); + } + Ok(relative) +} + +pub(super) fn policy_with_description( + mut document: Value, + original: &[u8], + id: &str, + relative: &str, +) -> Result> { + let providers = document["contextProviders"] + .as_object_mut() + .context("contextProviders is required")?; + providers.get_mut(id).context("provider disappeared")?["description"] = json!(relative); + let header: String = std::str::from_utf8(original)? + .split_inclusive('\n') + .take_while(|line| line.trim().is_empty() || line.trim_start().starts_with('#')) + .collect(); + Ok(format!("{header}{}", serde_norway::to_string(&document)?).into_bytes()) +} + pub(super) fn pair( project: &Path, id: &str, @@ -275,26 +308,13 @@ pub(super) fn pair( } .into()); } - let relative = provider - .description - .clone() - .unwrap_or_else(|| format!("context-providers/{id}.json")); + let relative = pairing_description(provider)?; let file = project.join(&relative); - if !relative.starts_with("context-providers/") || relative.contains("..") { - return Err(PairingFailure::DescriptionPathInvalid { - path: format!("/contextProviders/{}/description", provider.id), - } - .into()); - } if apply { fs::create_dir_all(file.parent().context("export path has no parent")?)?; - let mut document = crate::project::read_project(project)? + let document = crate::project::read_project(project)? .document .to_json_value(); - let providers = document["contextProviders"] - .as_object_mut() - .context("contextProviders is required")?; - providers.get_mut(id).context("provider disappeared")?["description"] = json!(relative); let bytes = serde_json::to_vec_pretty(&export)?; // Both replacements are prepared before mutation and never change BReg inputs. // An existing description already names this exact destination. Leave @@ -304,11 +324,7 @@ pub(super) fn pair( None } else { let original = crate::project::read_package_input(&project.join("casework.yaml"))?; - let header: String = std::str::from_utf8(&original)? - .split_inclusive('\n') - .take_while(|line| line.trim().is_empty() || line.trim_start().starts_with('#')) - .collect(); - let policy_bytes = format!("{header}{}", serde_norway::to_string(&document)?); + let policy_bytes = policy_with_description(document, &original, id, &relative)?; let staged = tempfile::NamedTempFile::new_in(project)?; fs::write(staged.path(), policy_bytes)?; Some(staged) @@ -334,6 +350,171 @@ pub(super) fn pair( #[cfg(test)] mod tests { use super::*; + + #[test] + fn prospective_pair_checks_the_owner_package_namespace() { + let temporary = crate::canonical_tempdir(); + let project = temporary.path().join("review"); + crate::project::init(&project, "canonical-review").unwrap(); + let policy = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + let provider = "facility-proposal-context"; + let directory = "context-providers"; + let schema_bytes = fs::read(project.join("schemas/correct-address.schema.json")).unwrap(); + let schema: Value = serde_json::from_slice(&schema_bytes).unwrap(); + let export = serde_json::to_vec(&json!({ + "apiVersion": DESCRIPTION_API_VERSION, "kind": DESCRIPTION_KIND, + "sourceNamespace": "facility-registry", "actionId": "correct-address", + "contextId": "facility-address-context", + "contract": {"id": schema["$id"], "revision": schema["x-registry-definition-revision"], + "schemaDigest": sha256_uri(&schema_bytes)}, + "schema": schema, "schemaBytes": std::str::from_utf8(&schema_bytes).unwrap(), + })) + .unwrap(); + + for (description, display, allowed) in [ + ("REVISION", None, false), + ("REVISION/provider.json", None, false), + ("SHA256SUMS", None, false), + ("SHA256SUMS/provider.json", None, false), + ( + "context-providers/Facility-proposal-context.json", + None, + false, + ), + ("Context-Providers/independent.json", None, false), + ( + "retained.json", + Some("Context-Providers/display.json"), + false, + ), + ( + "context-providers/Ordinary name, résumés.json", + Some("schemas/display.json"), + true, + ), + ] { + // Use a fresh project so that differently cased directory names are + // never materialized together, even on a case-insensitive host. + let scratch = tempfile::tempdir_in(temporary.path()).unwrap(); + let project = scratch.path().join("project"); + crate::project::init(&project, "canonical-review").unwrap(); + let mut authored = policy.clone(); + let mut retained = authored["contextProviders"][provider].clone(); + retained["description"] = json!(description); + retained["deploymentRef"] = json!("retained-slot"); + authored["contextProviders"]["retained"] = retained; + let path = project.join(description); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, &export).unwrap(); + if let Some(display) = display { + let path = project.join(display); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, &schema_bytes).unwrap(); + authored["reviewPolicies"]["facility-address-review"]["displaySchema"] = + json!({"$ref": display}); + } + let bytes = serde_norway::to_string(&authored).unwrap(); + let policy_file = project.join("casework.yaml"); + fs::write(&policy_file, &bytes).unwrap(); + crate::project::check(&project, false, false).unwrap(); + let result = crate::project::check_review_package(&project, provider); + if allowed { + result.unwrap(); + } else { + let error = result.unwrap_err(); + let report = crate::configuration_report(&error).expect("package refusal report"); + assert_eq!( + report.diagnostics()[0].message, + "The prospective Casework package inputs cannot be packaged.", + "{description}" + ); + } + assert_eq!(fs::read_to_string(&policy_file).unwrap(), bytes); + assert_eq!(fs::read(path).unwrap(), export); + if allowed { + let relative = format!("{directory}/{provider}.json"); + let selected = project.join(&relative); + assert!(!selected.exists()); + fs::write(&selected, &export).unwrap(); + let paired = + policy_with_description(authored, bytes.as_bytes(), provider, &relative) + .unwrap(); + fs::write(&policy_file, paired).unwrap(); + let packaged = crate::project::package_dry_run(&project, None).unwrap(); + let mut expected = [ + "casework.yaml", + description, + display.unwrap(), + relative.as_str(), + ]; + expected.sort_unstable(); + assert_eq!(packaged["files"], json!(expected)); + } + } + } + + #[test] + fn prospective_pair_refuses_to_replace_a_display_schema() { + let temporary = crate::canonical_tempdir(); + let project = temporary.path().join("review"); + crate::project::init(&project, "canonical-review").unwrap(); + let provider = "facility-proposal-context"; + let relative = "context-providers/facility-proposal-context.json"; + let mut policy = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + let display = project.join(relative); + fs::create_dir_all(display.parent().unwrap()).unwrap(); + let schema = fs::read(project.join("schemas/correct-address.schema.json")).unwrap(); + fs::write(&display, &schema).unwrap(); + policy["reviewPolicies"]["facility-address-review"]["displaySchema"] = + json!({"$ref": relative}); + fs::write( + project.join("casework.yaml"), + serde_norway::to_string(&policy).unwrap(), + ) + .unwrap(); + crate::project::check(&project, false, false).unwrap(); + + let error = crate::project::check_review_package(&project, provider).unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(crate::project::ProjectRefusal::ReviewPackageDestination) + )); + assert_eq!(fs::read(display).unwrap(), schema); + } + + #[test] + fn prospective_pair_reports_package_warnings_as_a_domain_refusal() { + let temporary = crate::canonical_tempdir(); + let project = temporary.path().join("review"); + crate::project::init(&project, "canonical-review").unwrap(); + let policy_file = project.join("casework.yaml"); + let mut policy = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + policy["queues"]["decisions"]["label"] = + policy["queues"]["facility-addresses"]["label"].clone(); + fs::write(&policy_file, serde_norway::to_string(&policy).unwrap()).unwrap(); + let unpaired = crate::project::check(&project, false, false).unwrap(); + assert!(unpaired["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|entry| entry["severity"] == "warning")); + + let error = crate::project::check_review_package(&project, "facility-proposal-context") + .unwrap_err(); + let report = crate::configuration_report(&error).unwrap(); + assert!(report.has_errors()); + assert_eq!(report.diagnostics()[0].code, "caseworkctl.refused"); + } + #[test] fn pairing_preserves_schema_header_exact_pins_and_existing_description_bytes() { let temporary = crate::canonical_tempdir(); diff --git a/crates/registry-platform-config/src/package.rs b/crates/registry-platform-config/src/package.rs index 0fc718b323..0b8cad165f 100644 --- a/crates/registry-platform-config/src/package.rs +++ b/crates/registry-platform-config/src/package.rs @@ -109,6 +109,45 @@ pub fn is_envelope_file(path: &str) -> bool { path == SUM_FILE || path == REVISION_FILE } +/// Whether a project-relative file can be created below `root`, allowing +/// missing parent directories and optionally replacing an existing file. +/// Inspects the destination and its parents without following symbolic links. +#[cfg(unix)] +pub fn file_destination_available(root: &Path, relative: &Path, replace: bool) -> bool { + use rustix::fs::{open, openat, statat, AtFlags, FileType, Mode, OFlags}; + use rustix::io::Errno; + use std::path::Component; + + let mut components = relative.components(); + let Some(Component::Normal(filename)) = components.next_back() else { + return false; + }; + if components + .clone() + .any(|component| !matches!(component, Component::Normal(_))) + { + return false; + } + let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC; + let Ok(mut directory) = open(root, flags, Mode::empty()) else { + return false; + }; + for component in components { + match openat(&directory, component.as_os_str(), flags, Mode::empty()) { + Ok(child) => directory = child, + Err(Errno::NOENT) => return true, + Err(_) => return false, + } + } + match statat(&directory, filename, AtFlags::SYMLINK_NOFOLLOW) { + Ok(metadata) => { + replace && FileType::from_raw_mode(metadata.st_mode) == FileType::RegularFile + } + Err(Errno::NOENT) => true, + Err(_) => false, + } +} + /// A revision is one printable line of at most [`MAX_REVISION_BYTES`] bytes /// without leading or trailing whitespace. pub fn check_revision(revision: &str) -> Result<(), &'static str> { @@ -310,7 +349,9 @@ fn plan_sum_file( let mut entries = BTreeMap::new(); let mut folded = BTreeMap::new(); for (path, bytes) in files { - if is_envelope_file(path) { + // The writer reserves these root entries before writing either + // envelope file. A directory at either name also occupies the entry. + if path.split('/').next().is_some_and(is_envelope_file) { return Err(PackageErrorKind::Reserved { path: path.clone() }); } entries.insert(path.as_str(), bytes.as_slice()); diff --git a/crates/registry-platform-config/src/service_authoring.rs b/crates/registry-platform-config/src/service_authoring.rs index 050bbe87d5..5d92a7ffac 100644 --- a/crates/registry-platform-config/src/service_authoring.rs +++ b/crates/registry-platform-config/src/service_authoring.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Resolve a native review pair from the products' offline compiler reports. -use crate::package::{check_path, PackageLimits}; +use crate::package::{check_path, file_destination_available, PackageLimits}; use crate::service_compiler::{Product, ReviewContextContract, ReviewWiring}; use crate::sha256_uri; use registry_platform_canonical_json::{ @@ -12,8 +12,7 @@ use registry_platform_yaml::{ MAXIMUM_DOCUMENT_BYTES, }; use rustix::{ - fs::{fcntl_getfl, fcntl_setfl, open, openat, statat, AtFlags, FileType, Mode, OFlags}, - io::Errno, + fs::{fcntl_getfl, fcntl_setfl, openat, Mode, OFlags}, process::{kill_process_group, waitid, Pid, Signal, WaitId, WaitIdOptions}, }; use serde::{Deserialize, Deserializer}; @@ -47,6 +46,7 @@ const TOOL_POLL: Duration = Duration::from_millis(10); const TOOL_UNAVAILABLE: &str = "rstack.service.review-tool-unavailable"; const TOOL_FAILED: &str = "rstack.service.review-inspection"; const TOOL_INTERRUPTED: &str = "rstack.service.review-interrupted"; +pub const REVIEW_PACKAGE_PROVIDER_ARG: &str = "--review-package-provider"; pub enum ReviewToolFailure { Unavailable, @@ -439,6 +439,36 @@ pub fn inspect_review( ), )); } + let package = owner_report( + &run, + casework, + &[ + "check".as_ref(), + casework.project.as_os_str(), + REVIEW_PACKAGE_PROVIDER_ARG.as_ref(), + pair.context_provider.as_str().as_ref(), + ], + ); + match package { + Ok(report) if report["version"] == cases.version => {} + Err(ReviewToolFailure::Refused) => { + return Err(problem( + service, + "rstack.service.review-provider-description", + casework.source_pointer(), + "Casework refused the prospective review package.", + "Correct the Casework package inputs and retry planning the review pair.", + )) + } + Ok(_) => { + return Err(inspection_error( + service, + casework, + ReviewToolFailure::Failed, + )) + } + Err(failure) => return Err(inspection_error(service, casework, failure)), + } Ok(Some(pair)) } @@ -453,35 +483,9 @@ fn usable_pair_description(project: &Path, relative: &str, description_is_declar { return false; } - let mut components = Path::new(relative).components(); - let Some(Component::Normal(filename)) = components.next_back() else { - return false; - }; - let Ok(mut directory) = open(project, NOFOLLOW_DIR_FLAGS, Mode::empty()) else { - return false; - }; - // The runner copies only files and directories. Inspect the selected path - // without following links and let native pairing create missing parents. - for component in components { - let Component::Normal(name) = component else { - return false; - }; - match openat(&directory, name, NOFOLLOW_DIR_FLAGS, Mode::empty()) { - Ok(child) => directory = child, - Err(Errno::NOENT) => return true, - Err(_) => return false, - } - } - match statat(&directory, filename, AtFlags::SYMLINK_NOFOLLOW) { - // Pairing can replace the selected provider's declared description. - // An existing file at an implicit destination could be a project input. - Ok(metadata) => { - description_is_declared - && FileType::from_raw_mode(metadata.st_mode) == FileType::RegularFile - } - Err(Errno::NOENT) => true, - Err(_) => false, - } + // Pairing can replace the selected provider's declared description. An + // existing file at an implicit destination could be a project input. + file_destination_available(project, Path::new(relative), description_is_declared) } fn has_review_authority(service: &Document, product: &Product) -> Result { diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 18202a9ad4..79d30f5c3a 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -607,20 +607,33 @@ impl<'a> ProductRunner<'a> { if run_issuer { bind_casework_run_issuer(plan, &project.root, &prepared.root)?; if self.input.automatic_review { - let report = self.projected_casework_report(&prepared.root); - check_projected_casework(&prepared, report, stopping(self.root, self.terminate))?; + let report = self.prepared_casework_report(&prepared.root, None); + check_prepared_casework( + &prepared, + report, + stopping(self.root, self.terminate), + false, + )?; } else { self.tool(Product::Casework, "check", &[prepared.root.as_os_str()])?; } } else { copy_project(&project.root, &prepared.root)?; } + if let Some(binding) = &plan.bindings.casework_context_provider { + let report = self.prepared_casework_report(&prepared.root, Some(&binding.id)); + check_prepared_casework(&prepared, report, stopping(self.root, self.terminate), true)?; + } self.ensure_active()?; self.prepared_casework_project = Some(prepared.root); Ok(()) } - fn projected_casework_report(&self, project: &Path) -> Result<(ExitStatus, Value)> { + fn prepared_casework_report( + &self, + project: &Path, + provider: Option<&str>, + ) -> Result<(ExitStatus, Value)> { self.ensure_active()?; // Drain the report while polling the guard so a blocked pipe cannot // delay the supervisor's response to a stop request. @@ -641,14 +654,19 @@ impl<'a> ProductRunner<'a> { ); Ok(()) }; + let mut args = vec![ + "--format".as_ref(), + "json".as_ref(), + "check".as_ref(), + project.as_os_str(), + ]; + if let Some(provider) = provider { + use registry_platform_config::service_authoring::REVIEW_PACKAGE_PROVIDER_ARG; + args.extend([REVIEW_PACKAGE_PROVIDER_ARG.as_ref(), provider.as_ref()]); + } let mut child = spawn_guarded_tool( &self.input.binaries[&Product::Casework].tool, - &[ - "--format".as_ref(), - "json".as_ref(), - "check".as_ref(), - project.as_os_str(), - ], + &args, self.root, ("caseworkctl", "check"), stdout.into(), @@ -4520,15 +4538,16 @@ fn inspect_projected_casework( &[project.root.as_os_str()], terminate, ); - check_projected_casework(project, report, terminate.load(Ordering::Relaxed)) + check_prepared_casework(project, report, terminate.load(Ordering::Relaxed), false) } -/// Reuse Casework's project authority checks after rebinding. Report the -/// native refusal class at its plan field without carrying producer values. -fn check_projected_casework( +/// Report the Casework refusal class at its plan field without carrying +/// authored paths or producer values from the owner report. +fn check_prepared_casework( project: &SelectedProduct, report: Result<(ExitStatus, Value)>, interrupted: bool, + package: bool, ) -> Result<()> { let unavailable = |error| { if interrupted { @@ -4537,7 +4556,11 @@ fn check_projected_casework( inspection_unavailable( Product::Casework, &project.field, - "check the Casework project with the run issuer", + if package { + "check the prospective Casework review package" + } else { + "check the Casework project with the run issuer" + }, error, ) }; @@ -4552,6 +4575,14 @@ fn check_projected_casework( return Ok(()); } if status.code() == Some(1) && casework_domain_refusal(&report, "check") { + if package { + return Err(plan::SemanticRefusal::new( + &project.field, + "Casework refused the prospective review package.", + "Correct the Casework package inputs and retry the development run.", + ) + .into()); + } let duplicate = report["diagnostics"] .as_array() .into_iter() diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 6f93e5aedd..ea60d24b71 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -4852,6 +4852,8 @@ fn refused_supervisor_startup_preserves_managed_project_state() { ("docker", false, false), ("refusal", true, true), ("pair-copy", true, true), + ("fixed-package", true, true), + ("run-package", true, true), ] { let scratch = tempfile::tempdir().unwrap(); let fixture = scratch.path().canonicalize().unwrap(); @@ -4871,17 +4873,19 @@ accessProfiles: requester: {requiredScopes: [review.write]} trustedProducers: registry: {issuer: https://issuer.example.invalid, profile: requester, subject: producer} +contextProviders: + proposal-context: {} + retained: {description: retained-provider.json} "#, ) .unwrap(); - let fixed_issuer_pair = stop_at == "pair-copy"; - if fixed_issuer_pair { - symlink( - project.join("casework/casework.yaml"), - project.join("casework/private-copy-canary"), - ) - .unwrap(); + let fixed_issuer_pair = matches!(stop_at, "pair-copy" | "fixed-package"); + let package_refusal = matches!(stop_at, "fixed-package" | "run-package"); + if stop_at == "pair-copy" { + let export = project.join("casework/in-tree-export.json"); + fs::write(&export, "{}\n").unwrap(); + symlink(export, project.join("casework/retained-provider.json")).unwrap(); } let mut hash = Sha256::new(); @@ -4907,7 +4911,16 @@ trustedProducers: &casework, r#"#!/usr/bin/env bash set -euo pipefail -if [[ $# == 4 && "$1 $2 $3" == '--format json check' && "$4" == "$RUN_ROOT/casework-bound" ]]; then +if [[ $# == 6 && "$1 $2 $3" == '--format json check' && "$5 $6" == '--review-package-provider proposal-context' ]]; then + case "$STOP_AT:$4" in + "fixed-package:$RUN_ROOT/casework-paired" | "run-package:$RUN_ROOT/casework-bound") ;; + *) exit 2 ;; + esac + : >"$FIXTURE/package-started" + printf 'package-stderr-canary\n' >&2 + printf '%s\n' '{"apiVersion":"id.registrystack.org/formats/casework/report/v1","kind":"CaseworkReport","command":"check","status":"domain-refusal","ok":false,"version":"0.53.0-dev","diagnostics":[{"severity":"error","code":"config.package.unsafe-entry","path":"/package-path-canary","message":"package-diagnostic-canary","suggestedAction":"Correct it."}]}' + exit 1 +elif [[ $# == 4 && "$1 $2 $3" == '--format json check' && "$4" == "$RUN_ROOT/casework-bound" ]]; then : >"$FIXTURE/casework-started" if [[ "$STOP_AT" == casework ]]; then : >"$RUN_ROOT/stop" @@ -4932,7 +4945,7 @@ printf '%s\n' '{"apiVersion":"id.registrystack.org/formats/casework/report/v1"," &docker, r#"#!/usr/bin/env bash set -euo pipefail -if [[ "$STOP_AT" == pair-copy ]]; then +if [[ "$STOP_AT" == pair-copy || "$STOP_AT" == *-package ]]; then printf '%s\n' "$1" >>"$FAKE_DOCKER_STATE/argv.log" exit 1 fi @@ -4983,6 +4996,10 @@ fi input["plan"]["people"]["producer"]["grants"]["breg"] = serde_json::json!({"profile": "operator", "scopes": ["registry:read"]}); input["automatic_review"] = serde_json::json!(false); + } else if package_refusal { + input["plan"]["bindings"]["caseworkContextProvider"] = serde_json::json!({ + "id": "proposal-context", "identity": "producer", "action": "review-action" + }); } fs::write(root.join("input.json"), input.to_string()).unwrap(); @@ -5031,13 +5048,24 @@ fi !state.join("failed").exists(), "the projected stderr should be discarded" ); - } else if fixed_issuer_pair { + } else if stop_at == "pair-copy" { let error = report["error"].as_str().unwrap(); assert!( error.contains("Casework project contains a symlink or non-file entry"), "{error}" ); - assert!(!error.contains("private-copy-canary"), "{error}"); + assert!(!error.contains("retained-provider.json"), "{error}"); + } else if package_refusal { + let error = report["error"].as_str().unwrap(); + assert!( + error.contains("Casework refused the prospective review package"), + "{error}" + ); + assert!(!error.contains("canary"), "{error}"); + assert!( + !state.join("failed").exists(), + "package preflight must discard stderr" + ); } else { assert_eq!(report["error"], "development run was stopped", "{report}"); } @@ -5045,6 +5073,7 @@ fi fixture.join("casework-started").exists(), !fixed_issuer_pair ); + assert_eq!(fixture.join("package-started").exists(), package_refusal); assert!(!fixture.join("casework-finished").exists()); assert!(!root.exists(), "the stopped supervisor did not clean up"); assert_eq!(fs::read_to_string(marker).unwrap(), "fixture-generation"); diff --git a/crates/registry-rstack/tests/fixtures/service_review/mod.rs b/crates/registry-rstack/tests/fixtures/service_review/mod.rs index 09bdca1d91..f5266e62bb 100644 --- a/crates/registry-rstack/tests/fixtures/service_review/mod.rs +++ b/crates/registry-rstack/tests/fixtures/service_review/mod.rs @@ -49,8 +49,17 @@ esac const CASEWORK_TOOL: &str = r#"#!/usr/bin/env bash set -euo pipefail -[[ "$3" == explain ]] -cat -- "$4/explanation.json" +case "$3" in + explain) cat -- "$4/explanation.json" ;; + check) + [[ "$5" == --review-package-provider ]] + if [[ -f "$(dirname -- "$0")/native-package-check" ]]; then + exec "$RSTACK_TEST_CASEWORKCTL_HOST" "$@" + fi + cat -- "$4/package-check.json" + ;; + *) exit 2 ;; +esac "#; pub(super) struct ReviewFixture { @@ -194,7 +203,11 @@ impl ReviewFixture { "missing-bins", ]) .env("RSTACK_BREGCTL_BIN", self.root().join("bregctl")) - .env("RSTACK_CASEWORKCTL_BIN", self.root().join("caseworkctl")); + .env("RSTACK_CASEWORKCTL_BIN", self.root().join("caseworkctl")) + .env( + "RSTACK_TEST_CASEWORKCTL_HOST", + Path::new(env!("CARGO_BIN_EXE_rstack")).with_file_name("caseworkctl"), + ); command } @@ -419,6 +432,12 @@ impl ReviewFixture { pub(super) fn write_json(&self, file: &str, value: &Value) { fs::write(self.root().join(file), serde_json::to_vec(value).unwrap()).unwrap(); + if file == "casework/explanation.json" { + self.write_json("casework/package-check.json", &json!({ + "apiVersion": value["apiVersion"], "kind": value["kind"], "version": value["version"], + "command": "check", "status": "complete", "ok": true, + })); + } } pub(super) fn read_json(&self, file: &str) -> Value { diff --git a/crates/registry-rstack/tests/service_plan.rs b/crates/registry-rstack/tests/service_plan.rs index b3e38886dc..f1140f3274 100644 --- a/crates/registry-rstack/tests/service_plan.rs +++ b/crates/registry-rstack/tests/service_plan.rs @@ -770,6 +770,68 @@ fn refuses_review_descriptions_that_cannot_be_packaged() { } } +#[test] +fn refuses_a_casework_schema_that_collides_with_the_projected_package() { + let fixture = strict_review_fixture(); + fs::write(fixture.root().join("native-package-check"), "").unwrap(); + let version = + Command::new(Path::new(env!("CARGO_BIN_EXE_rstack")).with_file_name("caseworkctl")) + .arg("--version") + .output() + .unwrap(); + assert!(version.status.success(), "{version:?}"); + let version = std::str::from_utf8(&version.stdout) + .unwrap() + .trim() + .strip_prefix("caseworkctl ") + .unwrap(); + for file in [ + "casework/explanation.json", + "registry/explanation.json", + "registry/generation.json", + ] { + let mut report = fixture.read_json(file); + report["version"] = json!(version); + fixture.write_json(file, &report); + } + let healthy = fixture.run(&[]); + assert!( + healthy.status.success() && healthy.stderr.is_empty(), + "{healthy:?}" + ); + let project = fixture.root().join("casework"); + let project_file = project.join("casework.yaml"); + let mut authored: Value = + serde_norway::from_str(&fs::read_to_string(&project_file).unwrap()).unwrap(); + let display = &mut authored["reviewPolicies"]["repair-approval"]["displaySchema"]; + let obstruction = "Context-Providers/retained-schema.json"; + fs::create_dir(project.join("Context-Providers")).unwrap(); + fs::write( + project.join(obstruction), + serde_json::to_vec(display).unwrap(), + ) + .unwrap(); + *display = json!({"$ref": obstruction}); + let bytes = serde_norway::to_string(&authored).unwrap(); + fs::write(&project_file, &bytes).unwrap(); + + for settings in [&[][..], &["--dev-config", "dev.yaml"][..]] { + let refusal = assert_refusal( + fixture.run(settings), + "rstack.service.review-provider-description", + "/products/casework/path", + ); + assert!(refusal.get("reviewWiring").is_none(), "{refusal}"); + assert!(refusal.get("devPlan").is_none(), "{refusal}"); + assert_eq!( + refusal["diagnostics"][0]["message"], + "Casework refused the prospective review package." + ); + assert!(!refusal.to_string().contains(obstruction), "{refusal}"); + } + assert_eq!(fs::read_to_string(project_file).unwrap(), bytes); +} + #[test] fn refuses_an_implicit_description_over_a_casework_display_schema() { let fixture = strict_review_fixture(); @@ -1630,7 +1692,17 @@ fn review_preflight_requires_the_same_build_in_all_owner_reports() { fixture.write_json(file, &report); } - for file in ["registry/explanation.json", "registry/generation.json"] { + for (file, pointer) in [ + ( + "registry/explanation.json", + "/products/breg/projects/workshop/path", + ), + ( + "registry/generation.json", + "/products/breg/projects/workshop/path", + ), + ("casework/package-check.json", "/products/casework/path"), + ] { let mut report = fixture.read_json(file); let mismatched = "0.53.0-nightly.20990101.mismatched-canary"; report["version"] = json!(mismatched); @@ -1639,7 +1711,7 @@ fn review_preflight_requires_the_same_build_in_all_owner_reports() { fixture.run(&[]), 3, "rstack.service.review-inspection", - "/products/breg/projects/workshop/path", + pointer, ); assert!(!failure.to_string().contains(build)); assert!(!failure.to_string().contains(mismatched)); diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index d90e983b7a..c992f4a5db 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -187,16 +187,18 @@ pairs are sorted by the bytes of the path. Two exports of the same source give t wherever the project and the state directory are, so a deployment can pin the bundle digest. The [business registration reference host](https://github.com/registrystack/registry-stack/tree/main/deploy/examples/business-registration) serves an exported bundle under that pin. +The reference host serves only the example registration function, and `rstack dev` runs the declared `defineFunction` handlers you select. {/* Evidence: crates/registry-rstack/src/cli.rs; crates/registry-rstack-dev/src/preview.rs; crates/registry-rstack-dev/src/preview_export.rs; - deploy/examples/business-registration/host.mjs, bundleDigest; + deploy/examples/business-registration/host.mjs, bundleDigest, registrationBinding; crates/registry-platform-config/src/service_roles.rs, roles_from_document(); crates/registry-rstack-dev/src/products.rs; clients/typescript/preview/build.mjs; clients/typescript/preview/gateway.mjs; clients/typescript/preview/source-pair.mjs; + clients/typescript/preview/run.mjs, defineFunction; clients/typescript/preview/tests/source-pair.test.mjs; clients/typescript/preview/host.mjs, functionHostAuthorizer, startFunctionHost; clients/typescript/preview/run.mjs; From dc2b41ad9e4da959663f8e875fa572c82c63ec8a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:27:40 +0000 Subject: [PATCH 06/18] test(rstack): project the run issuer from parsed YAML Signed-off-by: Jeremi Joslin --- crates/registry-rstack/tests/dev_run.rs | 37 +++++++++++++++---------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index ea60d24b71..4811c9fcda 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -4705,8 +4705,6 @@ struct AcceptanceRun { } impl AcceptanceRun { - const ISSUER_BINDING: &'static str = "bindings:\n bregReviewAuthority: {id: casework, producer: registry, identity: producer, runIssuerBinding: {producer: {expectedIssuer: \"https://issuer.example.test\", expectedProfile: requester, expectedSubject: SUBJECT}, initiator: {expectedIssuer: \"https://issuer.example.test\", trust: run-test-people}}}\n"; - fn new(root: &std::path::Path, expected_subject: &str) -> Self { fn copy(source: &std::path::Path, target: &std::path::Path) { fs::create_dir_all(target).unwrap(); @@ -4726,19 +4724,30 @@ impl AcceptanceRun { .join("../../products/breg/acceptance/reviewed-evidence-journey"), &project, ); - let dev = fs::read_to_string(project.join("dev.yaml")).unwrap(); - let (_, rest) = dev - .split_once( - " bregReviewAuthority: {id: casework, producer: registry, identity: producer}\n", - ) + let plan_path = project.join("dev.yaml"); + let mut plan: serde_json::Value = + serde_norway::from_str(&fs::read_to_string(&plan_path).unwrap()).unwrap(); + let expected_issuer = plan["issuer"].as_str().unwrap().to_owned(); + plan["issuer"] = serde_json::json!("run"); + let authority = plan + .pointer_mut("/bindings/bregReviewAuthority") + .and_then(serde_json::Value::as_object_mut) .expect("the acceptance dev.yaml binds the review authority"); - let head = dev - .split("bindings:\n") - .next() - .unwrap() - .replace("issuer: https://issuer.example.test", "issuer: run"); - let binding = Self::ISSUER_BINDING.replace("SUBJECT", expected_subject); - fs::write(project.join("dev.yaml"), format!("{head}{binding}{rest}")).unwrap(); + authority.insert( + "runIssuerBinding".to_owned(), + serde_json::json!({ + "producer": { + "expectedIssuer": expected_issuer, + "expectedProfile": "requester", + "expectedSubject": expected_subject, + }, + "initiator": { + "expectedIssuer": expected_issuer, + "trust": "run-test-people", + }, + }), + ); + fs::write(plan_path, serde_norway::to_string(&plan).unwrap()).unwrap(); let bin = std::path::Path::new(env!("CARGO_BIN_EXE_rstack")) .parent() .unwrap() From 673dd19da930e2e7e92111b7a7eb8eae00c0699a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:28:54 +0000 Subject: [PATCH 07/18] test(rstack): use the selected issuer for review staff Signed-off-by: Jeremi Joslin --- .../breg/acceptance/reviewed-evidence-journey/dev-journeys.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/breg/acceptance/reviewed-evidence-journey/dev-journeys.yaml b/products/breg/acceptance/reviewed-evidence-journey/dev-journeys.yaml index bb21026057..662ecfe162 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/dev-journeys.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/dev-journeys.yaml @@ -15,7 +15,7 @@ journeys: body: teamId: reviewers staff: - - issuer: https://issuer.example.test + - issuer: "{{run.issuer}}" subject: staff supervisors: [] queueId: reviews From b353d39d526bb978736f07f4e71b4b4fbad2cb97 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:34:54 +0000 Subject: [PATCH 08/18] fix(rstack): type the Casework preflight arguments Signed-off-by: Jeremi Joslin --- crates/registry-rstack-dev/src/products.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 79d30f5c3a..bbdd7fba47 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -662,7 +662,7 @@ impl<'a> ProductRunner<'a> { ]; if let Some(provider) = provider { use registry_platform_config::service_authoring::REVIEW_PACKAGE_PROVIDER_ARG; - args.extend([REVIEW_PACKAGE_PROVIDER_ARG.as_ref(), provider.as_ref()]); + args.extend([REVIEW_PACKAGE_PROVIDER_ARG, provider].map(std::ffi::OsStr::new)); } let mut child = spawn_guarded_tool( &self.input.binaries[&Product::Casework].tool, From 1881ed35a297cb9865e11ee4fb06b22cdc2f93bb Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:37:14 +0000 Subject: [PATCH 09/18] fix(rstack): preserve portable review package inputs Signed-off-by: Jeremi Joslin --- crates/registry-caseworkctl/src/project.rs | 8 ++------ crates/registry-caseworkctl/src/provider_pair.rs | 16 ++++++++++++++++ crates/registry-platform-config/src/package.rs | 7 ++++--- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index 9ebf299602..ddca75a749 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -965,11 +965,6 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { .ok_or(crate::provider_pair::PairingFailure::ProviderNotDeclared)?; let relative = crate::provider_pair::pairing_description(provider)?; let destination = Path::new(&relative); - if decoded.value.context_providers.iter().any(|other| { - other.id != provider.id && other.description.as_deref().map(Path::new) == Some(destination) - }) { - return Err(ProjectRefusal::ReviewPackageDestination.into()); - } // The projected export is its own package input. A display schema at // this destination would be overwritten by the producer export envelope. if CaseworkProject::schema_references(&name, &original)? @@ -994,7 +989,8 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { } (projected.value, bytes) }; - let inputs = capture_package_inputs(project, &policy, bytes, Some(&relative))?; + let pending = (!declared).then_some(relative.as_str()); + let inputs = capture_package_inputs(project, &policy, bytes, pending)?; plan_package(project, &inputs, None, &package_limits(), PACKAGE_COMMAND) .map_err(|_| refused())?; if !file_destination_available(project, destination, declared) { diff --git a/crates/registry-caseworkctl/src/provider_pair.rs b/crates/registry-caseworkctl/src/provider_pair.rs index f3bd661018..0daf379b2e 100644 --- a/crates/registry-caseworkctl/src/provider_pair.rs +++ b/crates/registry-caseworkctl/src/provider_pair.rs @@ -377,8 +377,10 @@ mod tests { for (description, display, allowed) in [ ("REVISION", None, false), ("REVISION/provider.json", None, false), + ("revision/provider.json", None, false), ("SHA256SUMS", None, false), ("SHA256SUMS/provider.json", None, false), + ("sha256sums/provider.json", None, false), ( "context-providers/Facility-proposal-context.json", None, @@ -452,6 +454,20 @@ mod tests { ]; expected.sort_unstable(); assert_eq!(packaged["files"], json!(expected)); + + // Explicit bindings may retain a single authored export used + // by two providers when the owner validates it for both. + let mut shared = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + shared["contextProviders"]["retained"]["description"] = json!(relative); + fs::write(&policy_file, serde_norway::to_string(&shared).unwrap()).unwrap(); + crate::project::check_review_package(&project, provider).unwrap(); + let packaged = crate::project::package_dry_run(&project, None).unwrap(); + let mut expected = ["casework.yaml", display.unwrap(), relative.as_str()]; + expected.sort_unstable(); + assert_eq!(packaged["files"], json!(expected)); } } } diff --git a/crates/registry-platform-config/src/package.rs b/crates/registry-platform-config/src/package.rs index 0b8cad165f..22577e3648 100644 --- a/crates/registry-platform-config/src/package.rs +++ b/crates/registry-platform-config/src/package.rs @@ -349,9 +349,10 @@ fn plan_sum_file( let mut entries = BTreeMap::new(); let mut folded = BTreeMap::new(); for (path, bytes) in files { - // The writer reserves these root entries before writing either - // envelope file. A directory at either name also occupies the entry. - if path.split('/').next().is_some_and(is_envelope_file) { + // A file or directory at either envelope name prevents the writer + // from finishing, including on a case-insensitive filesystem. + let root = path.split_once('/').map_or(path.as_str(), |(root, _)| root); + if root.eq_ignore_ascii_case(SUM_FILE) || root.eq_ignore_ascii_case(REVISION_FILE) { return Err(PackageErrorKind::Reserved { path: path.clone() }); } entries.insert(path.as_str(), bytes.as_slice()); From 5983f1c2f1cde58dbc0e0ff19aa56e92c12fa622 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:43:08 +0000 Subject: [PATCH 10/18] test(rstack): read fixtures through the platform YAML reader Signed-off-by: Jeremi Joslin --- crates/registry-rstack/tests/dev_run.rs | 7 +++++-- crates/registry-rstack/tests/service_plan.rs | 14 ++++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index 4811c9fcda..02661d5afc 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -4725,8 +4725,11 @@ impl AcceptanceRun { &project, ); let plan_path = project.join("dev.yaml"); - let mut plan: serde_json::Value = - serde_norway::from_str(&fs::read_to_string(&plan_path).unwrap()).unwrap(); + let mut plan = registry_platform_yaml::Reader::new("dev.yaml") + .scan(&fs::read(&plan_path).unwrap()) + .unwrap() + .unwrap() + .to_json_value(); let expected_issuer = plan["issuer"].as_str().unwrap().to_owned(); plan["issuer"] = serde_json::json!("run"); let authority = plan diff --git a/crates/registry-rstack/tests/service_plan.rs b/crates/registry-rstack/tests/service_plan.rs index f1140f3274..b796c2f6a3 100644 --- a/crates/registry-rstack/tests/service_plan.rs +++ b/crates/registry-rstack/tests/service_plan.rs @@ -801,8 +801,11 @@ fn refuses_a_casework_schema_that_collides_with_the_projected_package() { ); let project = fixture.root().join("casework"); let project_file = project.join("casework.yaml"); - let mut authored: Value = - serde_norway::from_str(&fs::read_to_string(&project_file).unwrap()).unwrap(); + let mut authored = registry_platform_yaml::Reader::new("casework.yaml") + .scan(&fs::read(&project_file).unwrap()) + .unwrap() + .unwrap() + .to_json_value(); let display = &mut authored["reviewPolicies"]["repair-approval"]["displaySchema"]; let obstruction = "Context-Providers/retained-schema.json"; fs::create_dir(project.join("Context-Providers")).unwrap(); @@ -837,8 +840,11 @@ fn refuses_an_implicit_description_over_a_casework_display_schema() { let fixture = strict_review_fixture(); let relative = "context-providers/job-summary.json"; let project_file = fixture.root().join("casework/casework.yaml"); - let mut project: Value = - serde_norway::from_str(&fs::read_to_string(&project_file).unwrap()).unwrap(); + let mut project = registry_platform_yaml::Reader::new("casework.yaml") + .scan(&fs::read(&project_file).unwrap()) + .unwrap() + .unwrap() + .to_json_value(); let display = &mut project["reviewPolicies"]["repair-approval"]["displaySchema"]; let file = fixture.root().join("casework").join(relative); fs::create_dir(file.parent().unwrap()).unwrap(); From d4327f4f0c361a0681d62db5d3429a14ea534256 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:45:04 +0000 Subject: [PATCH 11/18] fix(casework): check projected package warning diagnostics Signed-off-by: Jeremi Joslin --- crates/registry-caseworkctl/src/project.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index ddca75a749..ef07e0e790 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -984,7 +984,8 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { &relative, )?; let projected = CaseworkProject::read(&name, &bytes)?; - if registry_platform_config::has_denied_warnings(&projected.document.warnings()) { + let warnings = projected.document.warnings(); + if registry_platform_config::has_denied_warnings(warnings.diagnostics()) { return Err(refused()); } (projected.value, bytes) From 413df9198de6adca37aae30a87a17dd355bd77c4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:53:31 +0000 Subject: [PATCH 12/18] test(release): account for the BReg journey timeout Signed-off-by: Jeremi Joslin --- release/scripts/test_release_workflow_structure.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/release/scripts/test_release_workflow_structure.py b/release/scripts/test_release_workflow_structure.py index bb3991e46b..6a97cf6209 100644 --- a/release/scripts/test_release_workflow_structure.py +++ b/release/scripts/test_release_workflow_structure.py @@ -587,6 +587,15 @@ def test_validates_exact_main_source_ci_and_unused_destinations(self) -> None: ci_timeouts = [] for name, job in protected_workflow["jobs"].items(): timeout = job.get("timeout-minutes", 0) + if name == "breg-contracts" and isinstance(timeout, str): + # The provisioning journey has a separate budget inside this matrix. + lane_timeouts = re.fullmatch( + r"\$\{\{ matrix\.lane == 'contracts-journeys' && ([1-9][0-9]*) \|\| ([1-9][0-9]*) \}\}", + timeout, + ) + if lane_timeouts is None: + self.fail(f"Unexpected BReg contracts timeout expression: {timeout}") + timeout = max(int(lane_timeouts[1]), int(lane_timeouts[2])) self.assertIsInstance(timeout, int, name) ci_timeouts.append(timeout) longest_ci_job = max(ci_timeouts) From 929136f82036627ecbf2f1bd49d1f3f1461a0360 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:56:08 +0000 Subject: [PATCH 13/18] docs(rstack): clarify which review description must be separate Signed-off-by: Jeremi Joslin --- .../content/docs/configure/run-a-project-with-rstack-dev.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index c992f4a5db..05fca0e5fc 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -879,7 +879,7 @@ Use `bregctl` and `caseworkctl` from the same build. Use a separate service per local review pair. The development runner has one authority and one provider slot. Choose a provider with `human-display` and `service-status` for this pair. If it declares a `description`, use a path under `context-providers/`. If you omit `description`, leave its default destination `context-providers/.json` unused. -Give every other Casework provider its own description file when you [pair its export](../casework/#pair-and-verify-the-export). +[Pair an export](../casework/#pair-and-verify-the-export) for every other Casework provider, and keep the selected provider's description path separate from the retained providers' paths. Set deployment URLs and credential references in each product's runtime configuration. In `casework.yaml`, `trustedProducers` pins each producer's issuer, access profile and subject. Set any initiator trust and requester-read rules in the same Casework policy. From 0f7a878f05fb3a25b4bcb8131ea202f685002876 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 08:58:34 +0000 Subject: [PATCH 14/18] test(breg): pin the scoped provisioning timeout Signed-off-by: Jeremi Joslin --- products/breg/scripts/test_postgres_runner.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/products/breg/scripts/test_postgres_runner.py b/products/breg/scripts/test_postgres_runner.py index 45f6b5795a..8d346bae44 100644 --- a/products/breg/scripts/test_postgres_runner.py +++ b/products/breg/scripts/test_postgres_runner.py @@ -464,7 +464,10 @@ def test_ci_keeps_all_lanes_and_tls_adopter_order(self): ), ci_changes.BREG_CONTRACTS_LANES, ) - self.assertEqual(30, job["timeout-minutes"]) + self.assertEqual( + "${{ matrix.lane == 'contracts-journeys' && 40 || 30 }}", + job["timeout-minutes"], + ) self.assertFalse(job["strategy"]["fail-fast"]) self.assertIn("postgres", job["services"]) # Each single-copy proof is pinned to exactly one shard, balancing From 3d5aaa2f3a0c1ed0dc846e0d04cd9f3cd108117e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 09:01:33 +0000 Subject: [PATCH 15/18] test(rstack): keep the prospective display schema pin exact Signed-off-by: Jeremi Joslin --- crates/registry-rstack/tests/service_plan.rs | 27 +++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/registry-rstack/tests/service_plan.rs b/crates/registry-rstack/tests/service_plan.rs index b796c2f6a3..6f56a3c380 100644 --- a/crates/registry-rstack/tests/service_plan.rs +++ b/crates/registry-rstack/tests/service_plan.rs @@ -794,11 +794,6 @@ fn refuses_a_casework_schema_that_collides_with_the_projected_package() { report["version"] = json!(version); fixture.write_json(file, &report); } - let healthy = fixture.run(&[]); - assert!( - healthy.status.success() && healthy.stderr.is_empty(), - "{healthy:?}" - ); let project = fixture.root().join("casework"); let project_file = project.join("casework.yaml"); let mut authored = registry_platform_yaml::Reader::new("casework.yaml") @@ -806,15 +801,23 @@ fn refuses_a_casework_schema_that_collides_with_the_projected_package() { .unwrap() .unwrap() .to_json_value(); - let display = &mut authored["reviewPolicies"]["repair-approval"]["displaySchema"]; + let display = fixture.context_schema_bytes("accept-repair"); + let valid_path = "schemas/review-display.json"; + fs::create_dir(project.join("schemas")).unwrap(); + fs::write(project.join(valid_path), &display).unwrap(); + authored["reviewPolicies"]["repair-approval"]["displaySchema"] = json!({"$ref": valid_path}); + fs::write(&project_file, serde_norway::to_string(&authored).unwrap()).unwrap(); + + let healthy = fixture.run(&[]); + assert!( + healthy.status.success() && healthy.stderr.is_empty(), + "{healthy:?}" + ); + let obstruction = "Context-Providers/retained-schema.json"; fs::create_dir(project.join("Context-Providers")).unwrap(); - fs::write( - project.join(obstruction), - serde_json::to_vec(display).unwrap(), - ) - .unwrap(); - *display = json!({"$ref": obstruction}); + fs::write(project.join(obstruction), &display).unwrap(); + authored["reviewPolicies"]["repair-approval"]["displaySchema"] = json!({"$ref": obstruction}); let bytes = serde_norway::to_string(&authored).unwrap(); fs::write(&project_file, &bytes).unwrap(); From 8e3c7a73724ee99711bb7e348d510ac98f6b2824 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 09:17:36 +0000 Subject: [PATCH 16/18] fix(casework): size the native review export before wiring Signed-off-by: Jeremi Joslin --- Cargo.lock | 1 + crates/registry-caseworkctl/Cargo.toml | 1 + crates/registry-caseworkctl/src/project.rs | 71 +++++-- .../registry-caseworkctl/src/provider_pair.rs | 197 ++++++++++++++++-- 4 files changed, 237 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ef189615db..1a4ffc479c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6588,6 +6588,7 @@ dependencies = [ "registry-cli-api", "registry-cli-report", "registry-platform-buildinfo", + "registry-platform-canonical-json", "registry-platform-config", "registry-platform-provision", "registry-platform-yaml", diff --git a/crates/registry-caseworkctl/Cargo.toml b/crates/registry-caseworkctl/Cargo.toml index 9208d10618..2227bba184 100644 --- a/crates/registry-caseworkctl/Cargo.toml +++ b/crates/registry-caseworkctl/Cargo.toml @@ -32,6 +32,7 @@ anyhow.workspace = true clap.workspace = true jsonschema.workspace = true registry-platform-buildinfo.workspace = true +registry-platform-canonical-json.workspace = true registry-platform-config.workspace = true registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index ef07e0e790..a35a0e8106 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -8,6 +8,7 @@ use registry_casework_core::{ CaseworkActsAs, CaseworkProject, ClockPolicy, ConfigLoadError, ReviewContextPolicy, ReviewContextProviderPolicy, }; +use registry_platform_canonical_json::canonicalize_json; use registry_platform_config::{ package::file_destination_available, plan_package, write_package, DeclaredPosture, DevelopmentWitness, LoadedRuntimeConfig, Posture, SecretResolver, @@ -885,7 +886,7 @@ pub(crate) fn project_input_path(project: &Path, relative: &str) -> Result Result> { let meta = fs::symlink_metadata(path)?; - if !meta.file_type().is_file() || meta.len() > 1024 * 1024 { + if !meta.file_type().is_file() || meta.len() > package_limits().max_file_bytes { return Err(ProjectRefusal::PackageInputInvalid.into()); } Ok(fs::read(path)?) @@ -895,7 +896,9 @@ pub(crate) fn package_contents(project: &Path) -> Result, pending_description: Option<&str>, ) -> Result>> { - let mut paths = registry_casework::package_inputs(policy, &policy_bytes)?; - paths.remove(registry_casework::POLICY_FILE); + let paths = registry_casework::package_inputs(policy, &policy_bytes)?; let mut inputs = BTreeMap::from([(registry_casework::POLICY_FILE.to_owned(), policy_bytes)]); for path in paths { - // Native pairing supplies this file after BReg verifies the exact - // activated package. Reserve its name in the planned closure now. - let bytes = if pending_description == Some(path.as_str()) { - Vec::new() - } else { - read_package_input(&project_input_path(project, &path)?)? - }; + if path == registry_casework::POLICY_FILE || pending_description == Some(path.as_str()) { + continue; + } + let bytes = read_package_input(&project_input_path(project, &path)?)?; inputs.insert(path, bytes); } + Ok(inputs) +} + +fn check_package_exports( + policy: &CaseworkProject, + inputs: &BTreeMap>, +) -> Result<()> { for provider in &policy.context_providers { if let Some(description) = &provider.description { - if pending_description == Some(description.as_str()) { - continue; - } let bytes = inputs .get(description) .ok_or(ProjectRefusal::PackageInputInvalid)?; @@ -929,11 +932,11 @@ fn capture_package_inputs( check_provider_export(policy, provider, &export)?; } } - Ok(inputs) + Ok(()) } -/// Plan the Casework side of a review package before the producer package is -/// available. The final package command checks the supplied description bytes. +/// Plan the Casework side of a review package using the producer-pinned display +/// schema. Pairing itself still imports from the verified producer package. pub(super) fn check_review_package(project: &Path, id: &str) -> Result { let refused = || -> anyhow::Error { Report::new(vec![Diagnostic::error( @@ -973,12 +976,14 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { { return Err(ProjectRefusal::ReviewPackageDestination.into()); } + let document = decoded.document.to_json_value(); let declared = provider.description.is_some(); + let namespace = provider.source_namespace.clone(); let (policy, bytes) = if declared { (decoded.value, original) } else { let bytes = crate::provider_pair::policy_with_description( - decoded.document.to_json_value(), + document.clone(), &original, id, &relative, @@ -990,10 +995,36 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { } (projected.value, bytes) }; - let pending = (!declared).then_some(relative.as_str()); - let inputs = capture_package_inputs(project, &policy, bytes, pending)?; + let mut inputs = capture_package_inputs(project, &policy, bytes, Some(&relative))?; + let (review, contract) = policy + .review_policies + .iter() + .find_map(|review| match &review.context { + ReviewContextPolicy::CurrentSource { provider, contract } if provider == id => { + Some((review, contract)) + } + _ => None, + }) + .ok_or_else(refused)?; + let action = review.display_schema["x-registry-review-context"]["actionId"] + .as_str() + .ok_or_else(refused)?; + let authored_schema = &document["reviewPolicies"][&review.id]["displaySchema"]; + let schema_bytes = if let Some(reference) = authored_schema["$ref"].as_str() { + inputs.get(reference).ok_or_else(refused)?.clone() + } else { + canonicalize_json(authored_schema).map_err(|_| refused())? + }; + let export = + crate::provider_pair::context_export(schema_bytes, contract.clone(), &namespace, action) + .map_err(|_| refused())?; + inputs.insert( + relative.clone(), + crate::provider_pair::encode_export(&export)?, + ); plan_package(project, &inputs, None, &package_limits(), PACKAGE_COMMAND) .map_err(|_| refused())?; + check_package_exports(&policy, &inputs)?; if !file_destination_available(project, destination, declared) { return Err(ProjectRefusal::ReviewPackageDestination.into()); } diff --git a/crates/registry-caseworkctl/src/provider_pair.rs b/crates/registry-caseworkctl/src/provider_pair.rs index 0daf379b2e..ee77bb04cd 100644 --- a/crates/registry-caseworkctl/src/provider_pair.rs +++ b/crates/registry-caseworkctl/src/provider_pair.rs @@ -146,18 +146,9 @@ fn native_export( let path = contract["path"] .as_str() .context("native action exports no review-context schema")?; - let schema_bytes = String::from_utf8(captured_native_file(package, verified, path)?)?; - let schema: Value = serde_json::from_str(&schema_bytes)?; - let export = BregContextExport { - api_version: DESCRIPTION_API_VERSION.into(), - kind: DESCRIPTION_KIND.into(), - source_namespace: namespace.into(), - action_id: action.into(), - context_id: schema["x-registry-review-context"]["contextId"] - .as_str() - .context("native schema lacks context ID")? - .into(), - contract: ReviewContextContract { + context_export( + captured_native_file(package, verified, path)?, + ReviewContextContract { id: contract["id"] .as_str() .context("native schema lacks contract ID")? @@ -173,12 +164,40 @@ fn native_export( .context("native schema lacks digest")?, )?, }, + namespace, + action, + ) +} + +pub(super) fn context_export( + schema_bytes: Vec, + contract: ReviewContextContract, + namespace: &str, + action: &str, +) -> Result { + let schema_bytes = String::from_utf8(schema_bytes)?; + let schema: Value = serde_json::from_str(&schema_bytes)?; + let export = BregContextExport { + api_version: DESCRIPTION_API_VERSION.into(), + kind: DESCRIPTION_KIND.into(), + source_namespace: namespace.into(), + action_id: action.into(), + context_id: schema["x-registry-review-context"]["contextId"] + .as_str() + .context("native schema lacks context ID")? + .into(), + contract, schema, schema_bytes, }; export.check()?; Ok(export) } + +pub(super) fn encode_export(export: &BregContextExport) -> serde_json::Result> { + serde_json::to_vec_pretty(export) +} + pub(super) fn compare( project: &Path, package: &Path, @@ -315,7 +334,7 @@ pub(super) fn pair( let document = crate::project::read_project(project)? .document .to_json_value(); - let bytes = serde_json::to_vec_pretty(&export)?; + let bytes = encode_export(&export)?; // Both replacements are prepared before mutation and never change BReg inputs. // An existing description already names this exact destination. Leave // authored bytes untouched in that common re-pairing case. Otherwise @@ -351,6 +370,158 @@ pub(super) fn pair( mod tests { use super::*; + #[test] + fn prospective_pair_checks_the_generated_export_against_the_package_file_limit() { + use registry_breg::{ + compiler::{compile_project_with_assets, CompileProfile}, + contract::{parse_project_json, ModuleAssetSource}, + }; + + const INDEX: &str = "generated/review-context-schemas/index.json"; + const SCHEMA: &str = "generated/review-context-schemas/correct-address.schema.json"; + const PROVIDER: &str = "facility-proposal-context"; + const DESCRIPTION: &str = "context-providers/facility-proposal-context.json"; + let authored = include_bytes!("../../../products/breg/examples/facility/registry.yaml"); + let breg = registry_platform_yaml::Reader::new("registry.yaml") + .scan(authored) + .unwrap() + .unwrap() + .to_json_value(); + let assets = [ModuleAssetSource { + module: None, + path: "plans/correct-address.rhai".into(), + bytes: include_bytes!( + "../../../products/breg/examples/facility/plans/correct-address.rhai" + ) + .to_vec(), + }]; + + for (items, fits) in [(14_300, true), (14_500, false)] { + let mut annotation = json!(vec![0; items]); + // Both the projection and its binding carry this schema. The + // binding's deepest array items are at Casework's depth limit. + for _ in 0..8 { + annotation = json!([annotation]); + } + let mut breg = breg.clone(); + let action = &mut breg["actions"]["correct-address"]; + action["inputs"].as_array_mut().unwrap().push(json!({ + "id": "details", "type": "structured", "maximumBytes": 64, + "classification": "internal", + "schema": {"type": "object", "additionalProperties": false, "x-annotation": annotation}, + })); + action["execution"]["proposal"]["reviewContext"]["fields"]["details"] = + json!({"type": "input", "input": "details"}); + let profiles = &mut breg["accessProfiles"]; + profiles["facility-correction-author"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("details")); + profiles["proposal-reviewer"]["permissions"]["proposals"][0]["readableContextFields"] + .as_array_mut() + .unwrap() + .push(json!("details")); + let source = parse_project_json(&serde_json::to_vec(&breg).unwrap()).unwrap(); + let compiled = + compile_project_with_assets(&source, &[], &assets, CompileProfile::Production) + .unwrap(); + let artifacts = compiled.artifacts(); + let producer_inputs = [INDEX, SCHEMA] + .into_iter() + .map(|path| (path.to_owned(), artifacts.get(path).unwrap().bytes.clone())) + .collect(); + let scratch = crate::canonical_tempdir(); + let native = scratch.path().join("producer"); + let verified = registry_platform_config::write_package( + &native, + &producer_inputs, + None, + &PackageLimits::default(), + "test producer package", + ) + .unwrap(); + let export = + native_export(&native, "correct-address", "facility-registry", &verified).unwrap(); + let encoded = serde_json::to_vec_pretty(&export).unwrap(); + assert!(export.schema_bytes.len() <= 64 * 1024); + assert_eq!( + encoded.len() as u64 <= registry_casework::package_limits().max_file_bytes, + fits + ); + + let project = scratch.path().join("review"); + crate::project::init(&project, "canonical-review").unwrap(); + let policy_file = project.join("casework.yaml"); + let mut policy = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + policy["reviewPolicies"]["facility-address-review"]["context"]["contract"] = + json!(export.contract); + fs::write( + project.join("schemas/correct-address.schema.json"), + &export.schema_bytes, + ) + .unwrap(); + let authored = serde_norway::to_string(&policy).unwrap(); + fs::write(&policy_file, &authored).unwrap(); + crate::project::check(&project, false, true).unwrap(); + + let description_file = project.join(DESCRIPTION); + let preflight = crate::project::check_review_package(&project, PROVIDER); + assert_eq!(fs::read_to_string(&policy_file).unwrap(), authored); + assert!(!description_file.exists()); + + let paired = + policy_with_description(policy, authored.as_bytes(), PROVIDER, DESCRIPTION) + .unwrap(); + fs::create_dir(description_file.parent().unwrap()).unwrap(); + fs::write(&policy_file, &paired).unwrap(); + // A valid compact description can already be present. Automatic + // pairing will replace it with the bytes of its own encoder. + let existing = serde_json::to_vec(&export).unwrap(); + fs::write(&description_file, &existing).unwrap(); + let replacement = crate::project::check_review_package(&project, PROVIDER); + assert_eq!(fs::read(&description_file).unwrap(), existing); + assert_eq!(fs::read(&policy_file).unwrap(), paired); + + fs::write(&description_file, &encoded).unwrap(); + let packaged = crate::project::package_dry_run(&project, None); + assert_eq!(packaged.is_ok(), fits, "{packaged:?}"); + for result in [preflight, replacement] { + if fits { + result.unwrap(); + } else { + let error = result.unwrap_err(); + let report = crate::configuration_report(&error).unwrap(); + assert_eq!(report.diagnostics()[0].code, "caseworkctl.refused"); + } + } + } + } + + #[test] + fn prospective_pair_accepts_the_exact_pinned_inline_display_schema() { + let scratch = crate::canonical_tempdir(); + let project = scratch.path().join("review"); + crate::project::init(&project, "canonical-review").unwrap(); + let mut policy = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + let schema = fs::read(project.join("schemas/correct-address.schema.json")).unwrap(); + policy["reviewPolicies"]["facility-address-review"]["displaySchema"] = + serde_json::from_slice(&schema).unwrap(); + fs::write( + project.join("casework.yaml"), + serde_norway::to_string(&policy).unwrap(), + ) + .unwrap(); + + crate::project::check_review_package(&project, "facility-proposal-context").unwrap(); + assert!(!project.join("context-providers").exists()); + } + #[test] fn prospective_pair_checks_the_owner_package_namespace() { let temporary = crate::canonical_tempdir(); From 87526bb5f1e4357585cddace4d22f5a89f92a2cf Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Sat, 5 Dec 2026 09:11:56 +0000 Subject: [PATCH 17/18] docs(rstack): place initiator trust on the Casework producer Signed-off-by: Jeremi Joslin --- .../content/docs/configure/run-a-project-with-rstack-dev.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx index 05fca0e5fc..c63b3695b1 100644 --- a/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx +++ b/docs/site/src/content/docs/configure/run-a-project-with-rstack-dev.mdx @@ -882,7 +882,7 @@ If you omit `description`, leave its default destination `context-providers/ Date: Sat, 5 Dec 2026 09:27:16 +0000 Subject: [PATCH 18/18] fix(casework): restore preflight for unpinned providers Signed-off-by: Jeremi Joslin --- crates/registry-caseworkctl/src/project.rs | 69 ++++++++++++------- .../registry-caseworkctl/src/provider_pair.rs | 65 +++++++++++++++++ 2 files changed, 108 insertions(+), 26 deletions(-) diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index a35a0e8106..21ec27033d 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -897,7 +897,7 @@ pub(crate) fn package_contents(project: &Path) -> Result>, + pending_description: Option<&str>, ) -> Result<()> { for provider in &policy.context_providers { if let Some(description) = &provider.description { + if pending_description == Some(description.as_str()) { + continue; + } let bytes = inputs .get(description) .ok_or(ProjectRefusal::PackageInputInvalid)?; @@ -935,8 +944,9 @@ fn check_package_exports( Ok(()) } -/// Plan the Casework side of a review package using the producer-pinned display -/// schema. Pairing itself still imports from the verified producer package. +/// Plan the Casework side of a review package before native pairing. A pinned +/// display schema gives the exact export size. Pairing itself still imports +/// from the verified producer package. pub(super) fn check_review_package(project: &Path, id: &str) -> Result { let refused = || -> anyhow::Error { Report::new(vec![Diagnostic::error( @@ -995,8 +1005,7 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { } (projected.value, bytes) }; - let mut inputs = capture_package_inputs(project, &policy, bytes, Some(&relative))?; - let (review, contract) = policy + let pinned = policy .review_policies .iter() .find_map(|review| match &review.context { @@ -1004,27 +1013,35 @@ pub(super) fn check_review_package(project: &Path, id: &str) -> Result { Some((review, contract)) } _ => None, - }) - .ok_or_else(refused)?; - let action = review.display_schema["x-registry-review-context"]["actionId"] - .as_str() - .ok_or_else(refused)?; - let authored_schema = &document["reviewPolicies"][&review.id]["displaySchema"]; - let schema_bytes = if let Some(reference) = authored_schema["$ref"].as_str() { - inputs.get(reference).ok_or_else(refused)?.clone() - } else { - canonicalize_json(authored_schema).map_err(|_| refused())? - }; - let export = - crate::provider_pair::context_export(schema_bytes, contract.clone(), &namespace, action) - .map_err(|_| refused())?; - inputs.insert( - relative.clone(), - crate::provider_pair::encode_export(&export)?, - ); + }); + let replacement = (!declared || pinned.is_some()).then_some(relative.as_str()); + let mut inputs = capture_package_inputs(project, &policy, bytes, replacement)?; + if let Some((review, contract)) = pinned { + let action = review.display_schema["x-registry-review-context"]["actionId"] + .as_str() + .ok_or_else(refused)?; + let authored_schema = &document["reviewPolicies"][&review.id]["displaySchema"]; + let schema_bytes = if let Some(reference) = authored_schema["$ref"].as_str() { + inputs.get(reference).ok_or_else(refused)?.clone() + } else { + canonicalize_json(authored_schema).map_err(|_| refused())? + }; + let export = crate::provider_pair::context_export( + schema_bytes, + contract.clone(), + &namespace, + action, + ) + .map_err(|_| refused())?; + inputs.insert( + relative.clone(), + crate::provider_pair::encode_export(&export)?, + ); + } plan_package(project, &inputs, None, &package_limits(), PACKAGE_COMMAND) .map_err(|_| refused())?; - check_package_exports(&policy, &inputs)?; + let pending = (!declared && pinned.is_none()).then_some(relative.as_str()); + check_package_exports(&policy, &inputs, pending)?; if !file_destination_available(project, destination, declared) { return Err(ProjectRefusal::ReviewPackageDestination.into()); } diff --git a/crates/registry-caseworkctl/src/provider_pair.rs b/crates/registry-caseworkctl/src/provider_pair.rs index ee77bb04cd..faaedec0a2 100644 --- a/crates/registry-caseworkctl/src/provider_pair.rs +++ b/crates/registry-caseworkctl/src/provider_pair.rs @@ -522,6 +522,71 @@ mod tests { assert!(!project.join("context-providers").exists()); } + #[test] + fn prospective_pair_accepts_a_provider_without_a_review_pin() { + const PROVIDER: &str = "facility-proposal-context"; + const DESCRIPTION: &str = "context-providers/facility-proposal-context.json"; + let scratch = crate::canonical_tempdir(); + let project = scratch.path().join("review"); + crate::project::init(&project, "canonical-review").unwrap(); + let mut policy = crate::project::read_project(&project) + .unwrap() + .document + .to_json_value(); + let review = policy["reviewPolicies"] + .as_object_mut() + .unwrap() + .remove("facility-address-review") + .unwrap(); + policy["trustedProducers"] + .as_object_mut() + .unwrap() + .remove("facility-registry") + .unwrap(); + let policy_file = project.join("casework.yaml"); + let authored = serde_norway::to_string(&policy).unwrap(); + fs::write(&policy_file, &authored).unwrap(); + + let default = crate::project::check_review_package(&project, PROVIDER).unwrap(); + assert_eq!(default["policyBindings"].as_array().unwrap().len(), 1); + assert_eq!(default["policyBindings"][0]["id"], "decision"); + assert_eq!(default["networkAccess"], false); + assert_eq!(default["databaseAccess"], false); + assert_eq!(fs::read_to_string(&policy_file).unwrap(), authored); + assert!(!project.join("context-providers").exists()); + + let export = context_export( + fs::read(project.join("schemas/correct-address.schema.json")).unwrap(), + serde_json::from_value(review["context"]["contract"].clone()).unwrap(), + "facility-registry", + "correct-address", + ) + .unwrap(); + let export = serde_json::to_vec(&export).unwrap(); + let description = project.join(DESCRIPTION); + fs::create_dir(description.parent().unwrap()).unwrap(); + fs::write(&description, &export).unwrap(); + let collision = crate::project::check_review_package(&project, PROVIDER).unwrap_err(); + assert!(matches!( + collision.downcast_ref::(), + Some(crate::project::ProjectRefusal::ReviewPackageDestination) + )); + assert_eq!(fs::read(&description).unwrap(), export); + assert_eq!(fs::read_to_string(&policy_file).unwrap(), authored); + + let paired = + policy_with_description(policy, authored.as_bytes(), PROVIDER, DESCRIPTION).unwrap(); + fs::write(&policy_file, &paired).unwrap(); + let declared = crate::project::check_review_package(&project, PROVIDER).unwrap(); + assert_eq!(declared["policyBindings"], default["policyBindings"]); + assert_eq!(declared["networkAccess"], false); + assert_eq!(declared["databaseAccess"], false); + let package = crate::project::package_dry_run(&project, None).unwrap(); + assert_eq!(package["files"], json!(["casework.yaml", DESCRIPTION])); + assert_eq!(fs::read(&description).unwrap(), export); + assert_eq!(fs::read(&policy_file).unwrap(), paired); + } + #[test] fn prospective_pair_checks_the_owner_package_namespace() { let temporary = crate::canonical_tempdir();