diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 870a0ef228..b127f88f4a 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -169,6 +169,15 @@ # The BReg harnesses and the Adapter GovStack journey start their services with # `rstack dev`, so a change to it runs them. RSTACK_DEV_HARNESS_PACKAGES = frozenset({"registry-rstack", "registry-rstack-dev"}) +# The service previews start these products: BReg in every example, and +# Casework and the Coordinator in permit-review. +SERVICE_PREVIEW_PRODUCT_PACKAGES = frozenset({ + "registry-breg", + "registry-bregctl", + "registry-casework", + "registry-caseworkctl", + "registry-coordinator", +}) # The shared dependency gate owns the list of development runner hosts. _dev_runner_gate = runpy.run_path(str( Path(__file__).resolve().parents[2] / "products/platform/scripts/check_dev_runner_reach.py" @@ -658,17 +667,25 @@ "registry-caseworkctl", "registry-coordinator", "registry-documentsctl", + "registry-evidencectl", "registry-messagingctl", "registry-schedulingctl", ) PROVISION_JOURNEY_INPUTS = ( - *(f"crates/{package}/src/provision.rs" for package in PROVISION_JOURNEY_PACKAGES), + *( + f"crates/{package}/src/provision.rs" + for package in PROVISION_JOURNEY_PACKAGES + if package != "registry-evidencectl" + ), # Each journey's test file. The database-free `provision_cli.rs` stays out. *( f"crates/{package}/tests/provision_postgres.rs" for package in PROVISION_JOURNEY_PACKAGES - if package != "registry-caseworkctl" + if package not in ("registry-caseworkctl", "registry-evidencectl") ), + # Evidence provisions its held stores and serves nothing. + "crates/registry-evidencectl/src/store_provision.rs", + "crates/registry-evidencectl/tests/store_provision.rs", "crates/registry-adapterctl/src/job_provision.rs", "crates/registry-adapterctl/tests/job_provision_postgres.rs", "crates/registry-adapter-job/src/main.rs", @@ -1817,7 +1834,7 @@ def classify( service_previews = ( complete - or bool(affected & (RSTACK_DEV_HARNESS_PACKAGES | {"registry-breg", "registry-bregctl"})) + or bool(affected & (RSTACK_DEV_HARNESS_PACKAGES | SERVICE_PREVIEW_PRODUCT_PACKAGES)) or any(matches(path, *SERVICE_PREVIEW_INPUTS) for path in paths) ) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index e6b2b3fba3..b5ac222fa9 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -3882,6 +3882,10 @@ def test_service_preview_inputs_select_installed_browser_proof(self) -> None: "clients/typescript/preview/host.mjs", "products/platform/examples/service-previews/medical-renewal/dev.yaml", "products/platform/scripts/test-service-previews.mjs", + # permit-review starts Casework and the Coordinator. + "crates/registry-casework/src/lib.rs", + "crates/registry-caseworkctl/src/main.rs", + "crates/registry-coordinator/src/lib.rs", ): with self.subTest(path=path): outputs = classify(self.workspace, (path,)) @@ -3892,6 +3896,32 @@ def test_service_preview_inputs_select_installed_browser_proof(self) -> None: browser = next(step for step in steps if step.get("name") == "Run installed service previews in Chromium") self.assertIn("needs.changes.outputs.service_previews", browser["if"]) self.assertIn("test-service-previews.mjs", browser["run"]) + build = next(step for step in steps if step.get("name") == "Build the preview launcher and product tools") + for package in ("registry-casework", "registry-caseworkctl", "registry-coordinator"): + self.assertIn(f"-p {package}", build["run"]) + for name in ("CASEWORK", "CASEWORKCTL", "COORDINATOR", "COORDINATORCTL"): + self.assertIn(f"RSTACK_{name}_BIN", browser["env"]) + # A candidate whose release ships the Coordinator installs it and must + # pass permit-review; only one without it may skip, through the roster. + candidate = yaml.safe_load(Path(".github/workflows/release-candidate.yml").read_text()) + runs = [ + step.get("run", "") + for job in candidate["jobs"].values() + for step in job.get("steps", []) + ] + install = next(run for run in runs if "rstack-${tag}-install.sh" in run) + self.assertIn("coordinator-binaries-in-release", install) + self.assertIn("components+=(casework coordinator)", install) + smoke = next(run for run in runs if "test-service-previews.mjs" in run) + self.assertIn("coordinator-binaries-in-release", smoke) + self.assertIn("RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release", smoke) + # A roster failure fails the step: its output is assigned first, never + # read inside [[ ]], where set -e does not stop a failed substitution. + for run in (install, smoke): + self.assertIn('coordinator_in_release="$(python3 release/scripts/release_roster.py', run) + self.assertNotRegex(run, r'\$\(python3 release/scripts/release_roster\.py\s*\\?\s*coordinator-binaries-in-release[^)]*\)"\s*[!=]=') + self.assertIn('for component in casework coordinator; do', install) + self.assertIn('"${component}ctl ${version}"', install) def test_development_schema_drift_runs_in_the_conformance_job(self) -> None: for path in ( @@ -4736,7 +4766,13 @@ def test_product_provisioning_changes_select_the_tls_postgres_lane(self) -> None self.assertEqual(set(PROVISION_JOURNEY_PACKAGES), set(journeys)) edgeless = Workspace(without_dependency_edges(self.metadata)) paths = [ - *(f"crates/{package}/src/provision.rs" for package in journeys), + # A journey test target names its source: `provision_postgres.rs` + # and `provision.rs` test `provision.rs`, `store_provision.rs` + # tests `store_provision.rs`. + *( + f"crates/{package}/src/{target.removesuffix('_postgres')}.rs" + for package, (target, _) in journeys.items() + ), *(f"crates/{package}/tests/{target}.rs" for package, (target, _) in journeys.items()), "crates/registry-adapterctl/src/job_provision.rs", "crates/registry-adapterctl/tests/job_provision_postgres.rs", @@ -4848,11 +4884,58 @@ def test_contracts_journeys_lane_runs_each_product_provisioning_journey( '"${log}"', command, ) + # Each log needs its journey's own line. A journey that serves + # matches the shared serve pattern, and one that only provisions, + # such as the Evidence stores, names its exact test. + serve = re.compile(r"provision_then_(apply_then_)?serve_with_[a-z_]+") self.assertIn( - "grep -Eq '^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ " - "\\.\\.\\. ok$' \"${log}\"", + "*) journey='^test ([a-z_]+::)?provision_then_(apply_then_)?serve_with_[a-z_]+ " + "\\.\\.\\. ok$' ;;", command, ) + for package, (_, tests) in journeys.items(): + if any(serve.fullmatch(test) for test in tests): + continue + with self.subTest(package=package): + self.assertEqual(1, len(tests), "a provision-only journey names one test") + self.assertIn( + f"{package}) journey='^test {tests[0]} \\.\\.\\. ok$' ;;", + command, + ) + self.assertIn('grep -Eq "${journey}" "${log}"', command) + # The case holds exactly one arm per provision-only journey and the + # shared default, so no arm can override a serving journey's check. + case = re.search(r'case "\$\{package\}" in (.*?) esac', command) + self.assertIsNotNone(case) + arms = re.findall(r"(?:^|;;)\s*([^\s;)]+)\) journey=", case.group(1)) + provision_only = { + package + for package, (_, tests) in journeys.items() + if not any(serve.fullmatch(test) for test in tests) + } + self.assertEqual(sorted(provision_only | {"*"}), sorted(arms)) + + def test_every_workflow_roster_call_is_a_plain_assignment(self) -> None: + # Inside [[ ]], [ ] or test, set -e does not stop a failed command + # substitution, so a roster error would read as "not in release". + # Every roster call assigns its answer to a variable first, so the + # failure stops the step. + assignment = re.compile( + r'^\s*[A-Za-z_][A-Za-z0-9_]*="\$\((?:python3 )?\S*release_roster\.py [^()]*\)"\s*$' + ) + checked = 0 + for workflow in sorted(Path(".github/workflows").glob("*.yml")): + jobs = yaml.safe_load(workflow.read_text(encoding="utf-8"))["jobs"] + for job_name, job in jobs.items(): + for step in job.get("steps", []): + logical = re.sub(r"\\\n\s*", " ", step.get("run", "")) + for line in logical.splitlines(): + if not re.search(r"(?- + cargo build --locked --bins --features registry-breg/runtime + -p registry-rstack -p registry-breg -p registry-bregctl + -p registry-casework -p registry-caseworkctl -p registry-coordinator - name: Install Chromium for previews if: needs.changes.outputs.service_previews == 'true' @@ -4169,10 +4181,14 @@ jobs: - name: Run installed service previews in Chromium if: needs.changes.outputs.service_previews == 'true' - timeout-minutes: 15 + timeout-minutes: 20 env: RSTACK_BREG_BIN: ${{ github.workspace }}/target/debug/breg RSTACK_BREGCTL_BIN: ${{ github.workspace }}/target/debug/bregctl + RSTACK_CASEWORK_BIN: ${{ github.workspace }}/target/debug/casework + RSTACK_CASEWORKCTL_BIN: ${{ github.workspace }}/target/debug/caseworkctl + RSTACK_COORDINATOR_BIN: ${{ github.workspace }}/target/debug/coordinator + RSTACK_COORDINATORCTL_BIN: ${{ github.workspace }}/target/debug/coordinatorctl run: | set -euo pipefail client_dir="${GITHUB_WORKSPACE}/clients/typescript" diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index 1969730087..f065943eab 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -546,7 +546,9 @@ jobs: "coordinator ${{ needs.validate.outputs.version }}" test "$("dist/bin/coordinatorctl-${{ needs.validate.outputs.tag }}-linux-amd64" --version)" = \ "coordinatorctl ${{ needs.validate.outputs.version }}" - if [[ "$(python3 release/scripts/release_roster.py coordinator-in-release "${{ needs.validate.outputs.version }}")" == true ]]; then + coordinator_image_in_release="$(python3 release/scripts/release_roster.py \ + coordinator-in-release "${{ needs.validate.outputs.version }}")" + if [[ "${coordinator_image_in_release}" == true ]]; then test "$(dist/image-bin/coordinator --version)" = \ "coordinator ${{ needs.validate.outputs.version }}" test "$(dist/image-bin/coordinatorctl --version)" = \ @@ -2314,8 +2316,9 @@ jobs: "${binary} ${{ needs.validate.outputs.version }}" done rm candidate/bundle-root/SHA256SUMS - if [[ "$(python3 release/scripts/release_roster.py \ - rstack-in-release "${version}")" == true ]]; then + rstack_in_release="$(python3 release/scripts/release_roster.py \ + rstack-in-release "${version}")" + if [[ "${rstack_in_release}" == true ]]; then rstack_installer="rstack-${{ needs.validate.outputs.tag }}-install.sh" awk -v version="${{ needs.validate.outputs.tag }}" ' $0 == "default_version=\"\"" { @@ -2428,9 +2431,10 @@ jobs: done | jq -s . )" rstack_components=null + rstack_in_release="$(python3 release/scripts/release_roster.py \ + rstack-in-release "${version}")" if [[ "${{ needs.validate.outputs.unit }}" == stack && - "$(python3 release/scripts/release_roster.py \ - rstack-in-release "${version}")" == true ]]; then + "${rstack_in_release}" == true ]]; then rstack_components="$(printf '%s' "${payloads}" \ | python3 release/scripts/rstack_components.py --version "${version}")" fi @@ -2546,8 +2550,9 @@ jobs: run: | set -euo pipefail version="${{ needs.validate.outputs.version }}" - if [[ "$(python3 release/scripts/release_roster.py \ - rstack-in-release "${version}")" != true ]]; then + rstack_in_release="$(python3 release/scripts/release_roster.py \ + rstack-in-release "${version}")" + if [[ "${rstack_in_release}" != true ]]; then exit 0 fi tag="${{ needs.validate.outputs.tag }}" @@ -2559,11 +2564,21 @@ jobs: sha256sum -- * > SHA256SUMS ) destination="${RUNNER_TEMP}/rstack-install-smoke" + components=(breg evidence) + # The permit-review preview also needs Casework and the Coordinator. + # A release that ships them must install and pass it; the preview + # smoke skips it only for a release without the Coordinator. The + # assignment fails the step when the roster itself fails. + coordinator_in_release="$(python3 release/scripts/release_roster.py \ + coordinator-binaries-in-release "${version}")" + if [[ "${coordinator_in_release}" == true ]]; then + components+=(casework coordinator) + fi bash "${assets}/rstack-${tag}-install.sh" \ --asset-dir "${assets}" \ --bin-dir "${destination}/bin" \ --install-root "${destination}/lib" \ - breg evidence + "${components[@]}" test -L "${destination}/bin/rstack" test "$(find "${destination}/bin" -mindepth 1 -maxdepth 1 | wc -l)" -eq 1 rstack=("${destination}/bin/rstack" @@ -2578,6 +2593,15 @@ jobs: >/dev/null test "$("${rstack[@]}" breg --version)" = "bregctl ${version}" test "$("${rstack[@]}" evidence --version)" = "evidencectl ${version}" + if [[ "${coordinator_in_release}" == true ]]; then + for component in casework coordinator; do + "${rstack[@]}" components list --format json \ + | jq -e --arg name "${component}" \ + '.components | any(.name == $name and .installed == true)' \ + >/dev/null + test "$("${rstack[@]}" "${component}" --version)" = "${component}ctl ${version}" + done + fi - name: Install Node for the installed service preview smoke if: needs.validate.outputs.unit == 'stack' @@ -2585,7 +2609,7 @@ jobs: with: node-version: 24.11.0 - - name: Smoke both role-backed previews with installed candidate artifacts + - name: Smoke the role-backed previews with installed candidate artifacts if: needs.validate.outputs.unit == 'stack' shell: bash env: @@ -2603,6 +2627,11 @@ jobs: export RSTACK_PREVIEW_INSTALL_ROOT="${destination}/lib" export RSTACK_PREVIEW_BIN_DIR="${destination}/bin" export RSTACK_PREVIEW_EXAMPLES_DIR="${RUNNER_TEMP}/candidate-service-previews" + coordinator_in_release="$(python3 release/scripts/release_roster.py \ + coordinator-binaries-in-release "${CANDIDATE_PREVIEW_VERSION}")" + if [[ "${coordinator_in_release}" != true ]]; then + export RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release + fi cp -R products/platform/examples/service-previews "${RSTACK_PREVIEW_EXAMPLES_DIR}" node "${GITHUB_WORKSPACE}/products/platform/scripts/prepare-service-preview-locks.mjs" \ "${assets}/${web_package}" "${RSTACK_PREVIEW_EXAMPLES_DIR}" diff --git a/AGENTS.md b/AGENTS.md index 7f18798c38..fff41273da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -362,8 +362,9 @@ Envoy gateway. It holds a person's tokens in memory and answers the gateway's per-call check. It issues no token and adds no product authority. Among workspace crates it depends on `registry-platform-*` only, and no product crate depends on it. It runs as one replica, with a check listener private to -the gateway. It is held out of releases while `SESSION_FIRST_RELEASE` in -`release/scripts/release_roster.py` is unset. +the gateway. Numbered releases ship its binary from v0.51.0, as +`SESSION_FIRST_RELEASE` in `release/scripts/release_roster.py` sets. `rstack` +does not install it. The adopter demo is maintained separately in [`registrystack/solmara-lab`](https://github.com/registrystack/solmara-lab). diff --git a/Cargo.lock b/Cargo.lock index 276ad7859e..a2a6c18d68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7359,6 +7359,7 @@ dependencies = [ "inquire", "jsonschema", "p256", + "percent-encoding", "pkcs1", "pkcs8 0.10.2", "rand 0.9.5", @@ -7377,6 +7378,7 @@ dependencies = [ "registry-platform-crypto", "registry-platform-httpsec", "registry-platform-loopback", + "registry-platform-provision", "registry-platform-yaml", "registry-rstack-dev", "registry-thunderid-tooling", @@ -8399,8 +8401,10 @@ dependencies = [ "rcgen", "registry-cli-report", "registry-platform-buildinfo", + "registry-platform-canonical-json", "registry-platform-config", "registry-platform-crypto", + "registry-platform-hooks", "registry-platform-httputil", "registry-platform-postgres", "registry-platform-provision", @@ -8558,6 +8562,7 @@ version = "0.50.0" dependencies = [ "anyhow", "chrono", + "chrono-tz", "clap", "registry-cli-api", "registry-cli-report", diff --git a/clients/typescript/README.md b/clients/typescript/README.md index 50d531777a..9bae833896 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -344,6 +344,47 @@ with the service before trying it again. The client provides explicit JSON calls for initialization, listing and invocation. Streaming, server-initiated requests, automatic retries and running tool sequences are outside this API. +## Invoke a holder-authorized Action from a trusted host + +Use `@registrystack/client/holder-function` on a trusted host that receives a +signed-in person's bearer on one private, gateway-only route. This entry point +is pre-1.0 and may change. + +`createHolderActionHandler(binding, prepare)` returns a Fetch handler for one +declared function path. The host owns the binding: its `kind`, the exact path, +a preparation deadline, the submission and preparation parsers, and `invoke`, +which calls one generated BReg Action with one fixed access profile and the +caller's bearer. A `target` binding acts on one existing Record and needs its +reviewed condition. A `create` binding makes one new Record and takes no +target. `prepare` is the declared function. It receives only the projected +value the submission parser returns and a signal, never the Request, a +header, the bearer or a product client. Its result passes the preparation +parser, so it cannot select another product, Action, access profile, target, +owner or attempt key. + +The binding minimises arguments. It does not isolate the function: `prepare` +runs in the host's process and can reach whatever that process can, including +the next caller's request. Use it only for trusted, reviewed function code, +and run unreviewed functions outside the host's process. Who owns a created +Record comes from the host's preparation parser, which admits only the +Action's inputs, and the BReg Action's own plan and row boundaries, not from +this handler. BReg scopes attempt keys per issuer, subject and key. Bind +`create` only to an Action that inserts a Record. Bound to one that patches, +BReg refuses the unconditioned patch under the default `condition-required` +concurrency, and the handler relays that refusal. Under `current-revision` the +patch commits with no condition and every answer is unresolved. + +The handler checks only the bearer's shape. BReg verifies the bearer when the +Action is called, after `prepare` has run, so serve the handler only behind the +Session gateway, on a listener nothing else can reach. The binding's path is +the browser-facing `/api/functions/`. If your gateway relays to +`/functions/`, hand the handler a request with the browser-facing path. + +An answer with code `holder-action.outcome-unresolved` means BReg may have +acted. Keep the original attempt key and body until a matching receipt +arrives, including through an ordinary refusal of a retry such as an expired +sign-in. A new key can create a second Record. + ## Generate a service Install the package in your application with Node 24. diff --git a/clients/typescript/generate-service.ts b/clients/typescript/generate-service.ts index 41f7d0237f..cf17029ce2 100644 --- a/clients/typescript/generate-service.ts +++ b/clients/typescript/generate-service.ts @@ -388,7 +388,14 @@ export function generatePreviewFunctionBinding(productId: string, member: string ' })', ' }', ' const client = createRegistryServerClient({ baseUrl, token: () => credential })[' + key + ']', - ' return handle(request, client)', + ' // The client carries the caller credential, so the handler gets a copy without credentials.', + ' // A fresh native request also leaves out a host\'s own request object and its raw headers.', + ' const headers = new Headers(request.headers)', + ' for (const name of ["authorization", "cookie", "proxy-authorization"]) headers.delete(name)', + ' const copy = new Request(request.url, {', + ' method: request.method, headers, body: request.body, duplex: "half", signal: request.signal,', + ' } as RequestInit)', + ' return handle(copy, client)', ' }', '}', '', diff --git a/clients/typescript/generate.ts b/clients/typescript/generate.ts index 0ad6eba692..d976d9e134 100644 --- a/clients/typescript/generate.ts +++ b/clients/typescript/generate.ts @@ -154,20 +154,25 @@ const record = '[a-z0-9][a-z0-9-]*' const bregRoutes = [ 'records/' + record + '(?::(?:lookup|batch|snapshot|current|as-of)|/ingestion-runs' + '(?:/\\{run_id\\}(?:/(?:cancel|chunks(?:/\\{chunk_index\\}/receipt)?))?)?|/\\{record_id\\}' + - '(?:/(?:' + record + '|attachments/' + record + '))?)?', + '(?:/(?:' + record + '|attachments/' + record + '|revisions/\\{revision\\}))?)?', 'actions/' + record + '(?:/(?:proposals|availability|target-conditions))?', 'proposals(?:/review-context|/\\{proposal_id\\}(?:/(?:apply|cancel|edit|rebase|retry|revise|review-context|' + - 'review-status|task-grant-context|submit|submissions/\\{submission_version\\}|attachments/' + record + '))?)?', + 'review-status|task-grant-context|submit|submissions/\\{submission_version\\}|attachments/' + record + + '|additions/(?:' + record + '|\\{addition_id\\})|asks/\\{ask_id\\}/answer))?)?', 'statistics/' + record + '(?::(?:live|exact)|/releases(?::series|/\\{period\\}' + - '(?:/versions(?::dry-run|/\\{version\\}(?:/withdrawal)?))?)?)', + '(?:/versions(?::dry-run|/\\{version\\}(?:/withdrawal)?)?)?)?)', + 'external-views/' + record + '/' + record + '/records(?:/\\{root\\}(?:/refresh)?)?', + 'external-refresh-plans/\\{plan\\}/source-changes', 'review-completions', ] const bregRoute = new RegExp('^/v1/(?:' + bregRoutes.join('|') + ')$') -// A record patch can target fields of different types, so BReg leaves its value open. +// BReg leaves patch values open because they can target fields of different types. const bregPatchValue = new RegExp( - '^/paths/~1v1~1records~1' + record + '~1\\{record_id\\}/patch/requestBody/content/' + - 'application~1json-patch\\+json/schema/items/properties/value$', + '^/paths/~1v1~1records~1' + record + + '(?:~1\\{record_id\\}/patch/requestBody/content/application~1json-patch\\+json/schema/items' + + '|:batch/post/requestBody/content/application~1json/schema/properties/items/items/oneOf/1/properties/patch/items)' + + '/properties/value$', 'u', ) @@ -756,7 +761,8 @@ export function generate(source: string, settings: Settings = {}): string { mode = 'json' validationRoots.add(schemaAt) } - else if (media === 'application/dc+sd-jwt' || media.endsWith('+jwt')) mode = 'text' + else if (media === 'application/dc+sd-jwt' || media.endsWith('+jwt') + || (breg && method === 'get' && path.startsWith('/v1/statistics/') && media === 'text/csv')) mode = 'text' else if (media === '*/*' || media === 'application/octet-stream' || media === 'application/pdf') mode = 'binary' else mode = fail(schemaAt, 'unsupported success media') responseMedia.add(media) diff --git a/clients/typescript/generated/coordinator.ts b/clients/typescript/generated/coordinator.ts index ad11e93780..09874f473c 100644 --- a/clients/typescript/generated/coordinator.ts +++ b/clients/typescript/generated/coordinator.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.50.0, client version 0.50.0. -// Source SHA-256 f329e651d18e54a7409383f43a7eff83463c9fbfacf5c072eeb15cc035311e68 +// Source SHA-256 2e480154f09b6a6df9cba0be8e049690f37e69003b55000c30295540fc7eba28 // Unconstrained JSON /components/schemas/HookEnvelope/properties/data // Unconstrained JSON /components/schemas/RunStatus/properties/output // Unconstrained JSON /components/schemas/Start/properties/input @@ -20,7 +20,7 @@ export type Schema_HeldRun = ({ "advice": (string); "findingCode": (string); "re export type Schema_HeldRuns = (Array) export type Schema_Hold = ({ "restoreHold": (boolean) }) export type Schema_HookEnvelope = ({ "causation": ({ "hop": (number); "parent"?: (string); "root": (string) }); "data": JsonValue; "dataschema": (string); "id": (string); "source": (string); "subject": (({ "recordReference": (string); "recordRevision": (number) }) | ({ "proposalReference": (string); "proposalRevision": (number) })); "time": (string); "type": (string) }) -export type Schema_OperationIdentity = ({ "effect": ("read" | "mutation" | "evaluation") & (string); "id": ("breg.read-record/v1" | "messaging.submit-message/v1" | "scheduling.read-service/v1" | "scheduling.read-availability/v1" | "scheduling.create-appointment/v1" | "scheduling.read-appointment/v1" | "scheduling.create-hold/v1" | "scheduling.release-hold/v1" | "scheduling.confirm-hold/v1" | "scheduling.reschedule-appointment/v1" | "scheduling.cancel-appointment/v1" | "breg.invoke-action/v1" | "external.get/v1" | "evaluation.evaluate/v1" | "casework.submit-review-request/v1" | "casework.cancel-review-request/v1" | "scheduling.preview-availability/v1" | "external.command/v1" | "breg.read-in-force/v1" | "breg.read-proposal/v1" | "breg.start-proposal/v1" | "breg.submit-proposal/v1" | "breg.cancel-proposal/v1" | "breg.lookup-record/v1" | "breg.read-record/v2" | "payments.request-collection/v1" | "payments.read-collection/v1" | "payments.record-receipt/v1" | "payments.request-disbursement/v1" | "payments.read-disbursement/v1" | "payments.record-provider-confirmation/v1") & (string); "keyRequirement": ("none" | "required") & (string); "product": (string); "readReceipt": (boolean); "recovery": ("read-again" | "same-command-and-receipt" | "same-command" | "hold-after-dispatch") & (string); "requiresPreparation": (boolean); "version": (number) }) +export type Schema_OperationIdentity = ({ "effect": ("read" | "mutation" | "evaluation") & (string); "id": ("breg.read-record/v1" | "messaging.submit-message/v1" | "scheduling.read-service/v1" | "scheduling.read-availability/v1" | "scheduling.create-appointment/v1" | "scheduling.read-appointment/v1" | "scheduling.create-hold/v1" | "scheduling.release-hold/v1" | "scheduling.confirm-hold/v1" | "scheduling.reschedule-appointment/v1" | "scheduling.cancel-appointment/v1" | "breg.invoke-action/v1" | "external.get/v1" | "evaluation.evaluate/v1" | "casework.submit-review-request/v1" | "casework.cancel-review-request/v1" | "scheduling.preview-availability/v1" | "external.command/v1" | "breg.read-in-force/v1" | "breg.read-proposal/v1" | "breg.start-proposal/v1" | "breg.submit-proposal/v1" | "breg.cancel-proposal/v1" | "breg.lookup-record/v1" | "breg.read-record/v2" | "payments.request-collection/v1" | "payments.read-collection/v1" | "payments.record-receipt/v1" | "payments.request-disbursement/v1" | "payments.read-disbursement/v1" | "payments.record-provider-confirmation/v1" | "service.invoke-function/v1") & (string); "keyRequirement": ("none" | "required") & (string); "product": (string); "readReceipt": (boolean); "recovery": ("read-again" | "same-command-and-receipt" | "same-command" | "hold-after-dispatch") & (string); "requiresPreparation": (boolean); "version": (number) }) export type Schema_Problem = ({ "code": ("admission.held" | "admission.recovery-only" | "audit.response-unavailable" | "authentication.refused" | "binding.conflict" | "binding.live-conflict" | "check.not-waiting" | "definition.refused" | "deployment.activation-changed" | "deployment.refused" | "evaluation.uncertain" | "event.invalid" | "event.too-large" | "event.unauthenticated" | "execution.held" | "idempotency.key-invalid" | "idempotency.key-reused" | "input.invalid" | "mutation.uncertain" | "operation.not-authorized" | "receipt.expired" | "reconcile.raced" | "reconcile.refused" | "reconcile.unsupported" | "request.body-too-large" | "request.invalid" | "request.limit-out-of-range" | "request.method-not-allowed" | "request.not-found" | "request.reason-invalid" | "request.retention-invalid" | "request.unprocessable" | "request.unsupported-media-type" | "restore.hold-required" | "restore.lease-incompatible" | "restore.review-required" | "restore.unresolved" | "retry.refused" | "run.definition-incompatible" | "run.not-visible" | "run.payload-erased" | "runtime.failure" | "service.unavailable" | "workflow.not-served" | "workflow.revision-mismatch") & (string); "detail": (string); "pointer"?: (string); "status": (number); "title": (string); "traceId": (string); "type": ("https://id.registrystack.org/problems/registry-coordinator/admission/held" | "https://id.registrystack.org/problems/registry-coordinator/admission/recovery-only" | "https://id.registrystack.org/problems/registry-coordinator/audit/response-unavailable" | "https://id.registrystack.org/problems/registry-coordinator/authentication/refused" | "https://id.registrystack.org/problems/registry-coordinator/binding/conflict" | "https://id.registrystack.org/problems/registry-coordinator/binding/live-conflict" | "https://id.registrystack.org/problems/registry-coordinator/check/not-waiting" | "https://id.registrystack.org/problems/registry-coordinator/definition/refused" | "https://id.registrystack.org/problems/registry-coordinator/deployment/activation-changed" | "https://id.registrystack.org/problems/registry-coordinator/deployment/refused" | "https://id.registrystack.org/problems/registry-coordinator/evaluation/uncertain" | "https://id.registrystack.org/problems/registry-coordinator/event/invalid" | "https://id.registrystack.org/problems/registry-coordinator/event/too-large" | "https://id.registrystack.org/problems/registry-coordinator/event/unauthenticated" | "https://id.registrystack.org/problems/registry-coordinator/execution/held" | "https://id.registrystack.org/problems/registry-coordinator/idempotency/key-invalid" | "https://id.registrystack.org/problems/registry-coordinator/idempotency/key-reused" | "https://id.registrystack.org/problems/registry-coordinator/input/invalid" | "https://id.registrystack.org/problems/registry-coordinator/mutation/uncertain" | "https://id.registrystack.org/problems/registry-coordinator/operation/not-authorized" | "https://id.registrystack.org/problems/registry-coordinator/receipt/expired" | "https://id.registrystack.org/problems/registry-coordinator/reconcile/raced" | "https://id.registrystack.org/problems/registry-coordinator/reconcile/refused" | "https://id.registrystack.org/problems/registry-coordinator/reconcile/unsupported" | "https://id.registrystack.org/problems/registry-coordinator/request/body-too-large" | "https://id.registrystack.org/problems/registry-coordinator/request/invalid" | "https://id.registrystack.org/problems/registry-coordinator/request/limit-out-of-range" | "https://id.registrystack.org/problems/registry-coordinator/request/method-not-allowed" | "https://id.registrystack.org/problems/registry-coordinator/request/not-found" | "https://id.registrystack.org/problems/registry-coordinator/request/reason-invalid" | "https://id.registrystack.org/problems/registry-coordinator/request/retention-invalid" | "https://id.registrystack.org/problems/registry-coordinator/request/unprocessable" | "https://id.registrystack.org/problems/registry-coordinator/request/unsupported-media-type" | "https://id.registrystack.org/problems/registry-coordinator/restore/hold-required" | "https://id.registrystack.org/problems/registry-coordinator/restore/lease-incompatible" | "https://id.registrystack.org/problems/registry-coordinator/restore/review-required" | "https://id.registrystack.org/problems/registry-coordinator/restore/unresolved" | "https://id.registrystack.org/problems/registry-coordinator/retry/refused" | "https://id.registrystack.org/problems/registry-coordinator/run/definition-incompatible" | "https://id.registrystack.org/problems/registry-coordinator/run/not-visible" | "https://id.registrystack.org/problems/registry-coordinator/run/payload-erased" | "https://id.registrystack.org/problems/registry-coordinator/runtime/failure" | "https://id.registrystack.org/problems/registry-coordinator/service/unavailable" | "https://id.registrystack.org/problems/registry-coordinator/workflow/not-served" | "https://id.registrystack.org/problems/registry-coordinator/workflow/revision-mismatch") & (string) }) export type Schema_ProposalWaitsByTurn = ({ "nobody": (number); "official": (number); "party": (number); "unobserved": (number) }) export type Schema_Reason = ({ "reason": (string) }) @@ -40,7 +40,7 @@ export interface Operations { "ready": { input: CallOptions & { accept?: "application/json" | "*/*" }; required: false; output: ({ "developmentSettings": (Array<({ "code": (string); "pointer": (string) })>); "posture": ("production" | "development"); "ready": (boolean); "status": "ready" }) } "completeExecutionRecovery": { input: CallOptions & ({ body: Schema_ExecutionRecovery }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_ExecutionReviewed } "doctor": { input: CallOptions & { accept?: "application/json" | "*/*" }; required: false; output: Schema_Doctor } - "admitEvent": { input: CallOptions & { path: { "workflow": (string); "trigger": (string) } } & { headers: { "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } + "admitEvent": { input: CallOptions & { path: { "workflowId": (string); "triggerId": (string) } } & { headers: { "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } "releaseAdmissionHold": { input: CallOptions & ({ body: Schema_AdmissionRelease }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_AdmissionHold } "releaseRestoreHold": { input: CallOptions & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_Hold } "restoreHold": { input: CallOptions & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_Hold } @@ -48,13 +48,13 @@ export interface Operations { "receiveReviewCompletion": { input: CallOptions & { headers: { "Registry-Recipient-Binding": (string); "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } "listRuns": { input: CallOptions & { query?: { "limit"?: (number); "cursor"?: (string); "state"?: ("running" | "finished" | "failed" | "cancelled" | "cancelled-after-effect" | "expired" | "attention" | "cancel-requested") & (string); "attention"?: (boolean); "proposal"?: (string); "turn"?: ("party" | "official" | "nobody") & (string); "outcome"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_RunList } "startRun": { input: CallOptions & ({ body: Schema_Start }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } - "runStatus": { input: CallOptions & { path: { "run": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } - "cancelRun": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } - "checkNow": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_CheckNow }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_CheckNowResult } - "inspectRun": { input: CallOptions & { path: { "run": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } - "reconcileRun": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } - "retrySame": { input: CallOptions & { path: { "run": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RetryScheduled } - "workflowContract": { input: CallOptions & { path: { "workflow": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_WorkflowContract } + "runStatus": { input: CallOptions & { path: { "runId": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } + "cancelRun": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunStatus } + "checkNow": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_CheckNow }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_CheckNowResult } + "inspectRun": { input: CallOptions & { path: { "runId": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } + "reconcileRun": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RunInspection } + "retrySame": { input: CallOptions & { path: { "runId": (string) } } & ({ body: Schema_Reason }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_RetryScheduled } + "workflowContract": { input: CallOptions & { path: { "workflowId": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: Schema_WorkflowContract } } const rules: Record = Object.fromEntries([ @@ -73,7 +73,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/HookEnvelope", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"causation\":{\"$ref\":\"/components/schemas/HookEnvelope/$defs/Causation\"},\"data\":true,\"dataschema\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subject\":{\"$ref\":\"/components/schemas/HookEnvelope/$defs/EventSubject\"},\"time\":{\"type\":\"string\"},\"type\":{\"type\":\"string\"}},\"required\":[\"id\",\"type\",\"source\",\"time\",\"subject\",\"dataschema\",\"data\",\"causation\"],\"type\":\"object\"}")], ["/components/schemas/HookEnvelope/$defs/Causation", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"hop\":{\"maximum\":8,\"minimum\":0,\"type\":\"integer\"},\"parent\":{\"type\":\"string\"},\"root\":{\"type\":\"string\"}},\"required\":[\"root\",\"hop\"],\"type\":\"object\"}")], ["/components/schemas/HookEnvelope/$defs/EventSubject", JSON.parse("{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"recordReference\":{\"type\":\"string\"},\"recordRevision\":{\"maximum\":9007199254740991,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordReference\",\"recordRevision\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"proposalReference\":{\"type\":\"string\"},\"proposalRevision\":{\"maximum\":9007199254740991,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"proposalReference\",\"proposalRevision\"],\"type\":\"object\"}]}")], - ["/components/schemas/OperationIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"effect\":{\"enum\":[\"read\",\"mutation\",\"evaluation\"],\"type\":\"string\"},\"id\":{\"enum\":[\"breg.read-record/v1\",\"messaging.submit-message/v1\",\"scheduling.read-service/v1\",\"scheduling.read-availability/v1\",\"scheduling.create-appointment/v1\",\"scheduling.read-appointment/v1\",\"scheduling.create-hold/v1\",\"scheduling.release-hold/v1\",\"scheduling.confirm-hold/v1\",\"scheduling.reschedule-appointment/v1\",\"scheduling.cancel-appointment/v1\",\"breg.invoke-action/v1\",\"external.get/v1\",\"evaluation.evaluate/v1\",\"casework.submit-review-request/v1\",\"casework.cancel-review-request/v1\",\"scheduling.preview-availability/v1\",\"external.command/v1\",\"breg.read-in-force/v1\",\"breg.read-proposal/v1\",\"breg.start-proposal/v1\",\"breg.submit-proposal/v1\",\"breg.cancel-proposal/v1\",\"breg.lookup-record/v1\",\"breg.read-record/v2\",\"payments.request-collection/v1\",\"payments.read-collection/v1\",\"payments.record-receipt/v1\",\"payments.request-disbursement/v1\",\"payments.read-disbursement/v1\",\"payments.record-provider-confirmation/v1\"],\"type\":\"string\"},\"keyRequirement\":{\"enum\":[\"none\",\"required\"],\"type\":\"string\"},\"product\":{\"type\":\"string\"},\"readReceipt\":{\"type\":\"boolean\"},\"recovery\":{\"enum\":[\"read-again\",\"same-command-and-receipt\",\"same-command\",\"hold-after-dispatch\"],\"type\":\"string\"},\"requiresPreparation\":{\"type\":\"boolean\"},\"version\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"version\",\"product\",\"effect\",\"keyRequirement\",\"requiresPreparation\",\"recovery\",\"readReceipt\"],\"type\":\"object\"}")], + ["/components/schemas/OperationIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"effect\":{\"enum\":[\"read\",\"mutation\",\"evaluation\"],\"type\":\"string\"},\"id\":{\"enum\":[\"breg.read-record/v1\",\"messaging.submit-message/v1\",\"scheduling.read-service/v1\",\"scheduling.read-availability/v1\",\"scheduling.create-appointment/v1\",\"scheduling.read-appointment/v1\",\"scheduling.create-hold/v1\",\"scheduling.release-hold/v1\",\"scheduling.confirm-hold/v1\",\"scheduling.reschedule-appointment/v1\",\"scheduling.cancel-appointment/v1\",\"breg.invoke-action/v1\",\"external.get/v1\",\"evaluation.evaluate/v1\",\"casework.submit-review-request/v1\",\"casework.cancel-review-request/v1\",\"scheduling.preview-availability/v1\",\"external.command/v1\",\"breg.read-in-force/v1\",\"breg.read-proposal/v1\",\"breg.start-proposal/v1\",\"breg.submit-proposal/v1\",\"breg.cancel-proposal/v1\",\"breg.lookup-record/v1\",\"breg.read-record/v2\",\"payments.request-collection/v1\",\"payments.read-collection/v1\",\"payments.record-receipt/v1\",\"payments.request-disbursement/v1\",\"payments.read-disbursement/v1\",\"payments.record-provider-confirmation/v1\",\"service.invoke-function/v1\"],\"type\":\"string\"},\"keyRequirement\":{\"enum\":[\"none\",\"required\"],\"type\":\"string\"},\"product\":{\"type\":\"string\"},\"readReceipt\":{\"type\":\"boolean\"},\"recovery\":{\"enum\":[\"read-again\",\"same-command-and-receipt\",\"same-command\",\"hold-after-dispatch\"],\"type\":\"string\"},\"requiresPreparation\":{\"type\":\"boolean\"},\"version\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"version\",\"product\",\"effect\",\"keyRequirement\",\"requiresPreparation\",\"recovery\",\"readReceipt\"],\"type\":\"object\"}")], ["/components/schemas/Problem", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"admission.held\",\"admission.recovery-only\",\"audit.response-unavailable\",\"authentication.refused\",\"binding.conflict\",\"binding.live-conflict\",\"check.not-waiting\",\"definition.refused\",\"deployment.activation-changed\",\"deployment.refused\",\"evaluation.uncertain\",\"event.invalid\",\"event.too-large\",\"event.unauthenticated\",\"execution.held\",\"idempotency.key-invalid\",\"idempotency.key-reused\",\"input.invalid\",\"mutation.uncertain\",\"operation.not-authorized\",\"receipt.expired\",\"reconcile.raced\",\"reconcile.refused\",\"reconcile.unsupported\",\"request.body-too-large\",\"request.invalid\",\"request.limit-out-of-range\",\"request.method-not-allowed\",\"request.not-found\",\"request.reason-invalid\",\"request.retention-invalid\",\"request.unprocessable\",\"request.unsupported-media-type\",\"restore.hold-required\",\"restore.lease-incompatible\",\"restore.review-required\",\"restore.unresolved\",\"retry.refused\",\"run.definition-incompatible\",\"run.not-visible\",\"run.payload-erased\",\"runtime.failure\",\"service.unavailable\",\"workflow.not-served\",\"workflow.revision-mismatch\"],\"type\":\"string\"},\"detail\":{\"type\":\"string\"},\"pointer\":{\"type\":\"string\"},\"status\":{\"type\":\"integer\"},\"title\":{\"type\":\"string\"},\"traceId\":{\"type\":\"string\"},\"type\":{\"enum\":[\"https://id.registrystack.org/problems/registry-coordinator/admission/held\",\"https://id.registrystack.org/problems/registry-coordinator/admission/recovery-only\",\"https://id.registrystack.org/problems/registry-coordinator/audit/response-unavailable\",\"https://id.registrystack.org/problems/registry-coordinator/authentication/refused\",\"https://id.registrystack.org/problems/registry-coordinator/binding/conflict\",\"https://id.registrystack.org/problems/registry-coordinator/binding/live-conflict\",\"https://id.registrystack.org/problems/registry-coordinator/check/not-waiting\",\"https://id.registrystack.org/problems/registry-coordinator/definition/refused\",\"https://id.registrystack.org/problems/registry-coordinator/deployment/activation-changed\",\"https://id.registrystack.org/problems/registry-coordinator/deployment/refused\",\"https://id.registrystack.org/problems/registry-coordinator/evaluation/uncertain\",\"https://id.registrystack.org/problems/registry-coordinator/event/invalid\",\"https://id.registrystack.org/problems/registry-coordinator/event/too-large\",\"https://id.registrystack.org/problems/registry-coordinator/event/unauthenticated\",\"https://id.registrystack.org/problems/registry-coordinator/execution/held\",\"https://id.registrystack.org/problems/registry-coordinator/idempotency/key-invalid\",\"https://id.registrystack.org/problems/registry-coordinator/idempotency/key-reused\",\"https://id.registrystack.org/problems/registry-coordinator/input/invalid\",\"https://id.registrystack.org/problems/registry-coordinator/mutation/uncertain\",\"https://id.registrystack.org/problems/registry-coordinator/operation/not-authorized\",\"https://id.registrystack.org/problems/registry-coordinator/receipt/expired\",\"https://id.registrystack.org/problems/registry-coordinator/reconcile/raced\",\"https://id.registrystack.org/problems/registry-coordinator/reconcile/refused\",\"https://id.registrystack.org/problems/registry-coordinator/reconcile/unsupported\",\"https://id.registrystack.org/problems/registry-coordinator/request/body-too-large\",\"https://id.registrystack.org/problems/registry-coordinator/request/invalid\",\"https://id.registrystack.org/problems/registry-coordinator/request/limit-out-of-range\",\"https://id.registrystack.org/problems/registry-coordinator/request/method-not-allowed\",\"https://id.registrystack.org/problems/registry-coordinator/request/not-found\",\"https://id.registrystack.org/problems/registry-coordinator/request/reason-invalid\",\"https://id.registrystack.org/problems/registry-coordinator/request/retention-invalid\",\"https://id.registrystack.org/problems/registry-coordinator/request/unprocessable\",\"https://id.registrystack.org/problems/registry-coordinator/request/unsupported-media-type\",\"https://id.registrystack.org/problems/registry-coordinator/restore/hold-required\",\"https://id.registrystack.org/problems/registry-coordinator/restore/lease-incompatible\",\"https://id.registrystack.org/problems/registry-coordinator/restore/review-required\",\"https://id.registrystack.org/problems/registry-coordinator/restore/unresolved\",\"https://id.registrystack.org/problems/registry-coordinator/retry/refused\",\"https://id.registrystack.org/problems/registry-coordinator/run/definition-incompatible\",\"https://id.registrystack.org/problems/registry-coordinator/run/not-visible\",\"https://id.registrystack.org/problems/registry-coordinator/run/payload-erased\",\"https://id.registrystack.org/problems/registry-coordinator/runtime/failure\",\"https://id.registrystack.org/problems/registry-coordinator/service/unavailable\",\"https://id.registrystack.org/problems/registry-coordinator/workflow/not-served\",\"https://id.registrystack.org/problems/registry-coordinator/workflow/revision-mismatch\"],\"type\":\"string\"}},\"required\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\"],\"type\":\"object\"}")], ["/components/schemas/ProposalWaitsByTurn", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"nobody\":{\"minimum\":0,\"type\":\"integer\"},\"official\":{\"minimum\":0,\"type\":\"integer\"},\"party\":{\"minimum\":0,\"type\":\"integer\"},\"unobserved\":{\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"party\",\"official\",\"nobody\",\"unobserved\"],\"type\":\"object\"}")], ["/components/schemas/Reason", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"reason\":{\"maxLength\":256,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"reason\"],\"type\":\"object\"}")], @@ -108,13 +108,13 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1doctor/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], ["/paths/~1v1~1doctor/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], ["/paths/~1v1~1doctor/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.invalid\",\"input.invalid\",\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.unauthenticated\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"admission.held\",\"admission.recovery-only\",\"binding.conflict\",\"binding.live-conflict\",\"definition.refused\",\"deployment.activation-changed\",\"deployment.refused\",\"execution.held\",\"idempotency.key-reused\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.too-large\",\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.invalid\",\"input.invalid\",\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.unauthenticated\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"admission.held\",\"admission.recovery-only\",\"binding.conflict\",\"binding.live-conflict\",\"definition.refused\",\"deployment.activation-changed\",\"deployment.refused\",\"execution.held\",\"idempotency.key-reused\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"event.too-large\",\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], ["/paths/~1v1~1release-admission-hold/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/AdmissionHold\"}")], ["/paths/~1v1~1release-admission-hold/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], ["/paths/~1v1~1release-admission-hold/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], @@ -177,75 +177,75 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1runs/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], ["/paths/~1v1~1runs/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], ["/paths/~1v1~1runs/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], - ["/paths/~1v1~1runs~1{run}/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.definition-incompatible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1cancel/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/CheckNowResult\"}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"check.not-waiting\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1check/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"run.payload-erased\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1inspect/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"reconcile.raced\",\"reconcile.refused\",\"reconcile.unsupported\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1reconcile/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RetryScheduled\"}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"evaluation.uncertain\",\"mutation.uncertain\",\"receipt.expired\",\"retry.refused\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1runs~1{run}~1retry-same/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/WorkflowContract\"}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"workflow.not-served\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"deployment.activation-changed\",\"deployment.refused\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], - ["/paths/~1v1~1workflows~1{workflow}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunStatus\"}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.definition-incompatible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1cancel/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/CheckNowResult\"}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"check.not-waiting\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1check/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"run.payload-erased\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1inspect/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RunInspection\"}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"reconcile.raced\",\"reconcile.refused\",\"reconcile.unsupported\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/RetryScheduled\"}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.invalid\",\"request.reason-invalid\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"run.not-visible\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"binding.conflict\",\"definition.refused\",\"evaluation.uncertain\",\"mutation.uncertain\",\"receipt.expired\",\"retry.refused\",\"run.definition-incompatible\",\"run.payload-erased\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.body-too-large\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.unsupported-media-type\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/WorkflowContract\"}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"operation.not-authorized\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"workflow.not-served\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/405/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.method-not-allowed\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"deployment.activation-changed\",\"deployment.refused\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/500/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"runtime.failure\"]}}}]}")], + ["/paths/~1v1~1workflows~1{workflowId}/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"audit.response-unavailable\",\"service.unavailable\"]}}}]}")], ]) const routes: Record = Object.create(null) type Definition = Omit & { problems?: Record; responses: Record> } @@ -254,7 +254,7 @@ const definitions: Record = Object.fromEntries([ ["ready", JSON.parse("{\"method\":\"GET\",\"path\":\"/ready\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1ready/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"405\":\"/paths/~1ready/get/responses/405/content/application~1problem+json/schema\"}}")], ["completeExecutionRecovery", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/complete-execution-recovery\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1complete-execution-recovery/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1complete-execution-recovery/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1complete-execution-recovery/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1complete-execution-recovery/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1complete-execution-recovery/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1complete-execution-recovery/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1complete-execution-recovery/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1complete-execution-recovery/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1complete-execution-recovery/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1complete-execution-recovery/post/responses/503/content/application~1problem+json/schema\"}}")], ["doctor", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/doctor\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1doctor/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"401\":\"/paths/~1v1~1doctor/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1doctor/get/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1doctor/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1doctor/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1doctor/get/responses/503/content/application~1problem+json/schema\"}}")], - ["admitEvent", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/events/{workflow}/{trigger}\",\"responses\":{\"204\":[{\"mode\":\"empty\"}]},\"keyed\":false,\"signed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/401/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/413/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1events~1{workflow}~1{trigger}/post/responses/503/content/application~1problem+json/schema\"}}")], + ["admitEvent", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/events/{workflowId}/{triggerId}\",\"responses\":{\"204\":[{\"mode\":\"empty\"}]},\"keyed\":false,\"signed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/401/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/413/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1events~1{workflowId}~1{triggerId}/post/responses/503/content/application~1problem+json/schema\"}}")], ["releaseAdmissionHold", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/release-admission-hold\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1release-admission-hold/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1release-admission-hold/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1release-admission-hold/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1release-admission-hold/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1release-admission-hold/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1release-admission-hold/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1release-admission-hold/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1release-admission-hold/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1release-admission-hold/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1release-admission-hold/post/responses/503/content/application~1problem+json/schema\"}}")], ["releaseRestoreHold", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/release-restore-hold\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1release-restore-hold/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1release-restore-hold/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1release-restore-hold/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1release-restore-hold/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1release-restore-hold/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1release-restore-hold/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1release-restore-hold/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1release-restore-hold/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1release-restore-hold/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1release-restore-hold/post/responses/503/content/application~1problem+json/schema\"}}")], ["restoreHold", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/restore-hold\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1restore-hold/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1restore-hold/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1restore-hold/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1restore-hold/post/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1restore-hold/post/responses/405/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1restore-hold/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1restore-hold/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1restore-hold/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1restore-hold/post/responses/503/content/application~1problem+json/schema\"}}")], @@ -262,13 +262,13 @@ const definitions: Record = Object.fromEntries([ ["receiveReviewCompletion", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/review-completions\",\"responses\":{\"204\":[{\"mode\":\"empty\"}]},\"keyed\":false,\"signed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1review-completions/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1review-completions/post/responses/401/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1review-completions/post/responses/405/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1review-completions/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1review-completions/post/responses/415/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1review-completions/post/responses/503/content/application~1problem+json/schema\"}}")], ["listRuns", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs/get/responses/403/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs/get/responses/503/content/application~1problem+json/schema\"}}")], ["startRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs/post/responses/200/content/application~1json/schema\"}]},\"keyed\":true,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs/post/responses/503/content/application~1problem+json/schema\"}}")], - ["runStatus", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{run}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}/get/responses/503/content/application~1problem+json/schema\"}}")], - ["cancelRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/cancel\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1cancel/post/responses/503/content/application~1problem+json/schema\"}}")], - ["checkNow", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/check\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1check/post/responses/503/content/application~1problem+json/schema\"}}")], - ["inspectRun", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{run}/inspect\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1inspect/get/responses/503/content/application~1problem+json/schema\"}}")], - ["reconcileRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/reconcile\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1reconcile/post/responses/503/content/application~1problem+json/schema\"}}")], - ["retrySame", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{run}/retry-same\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{run}~1retry-same/post/responses/503/content/application~1problem+json/schema\"}}")], - ["workflowContract", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/workflows/{workflow}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"401\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1workflows~1{workflow}/get/responses/503/content/application~1problem+json/schema\"}}")], + ["runStatus", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{runId}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}/get/responses/405/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}/get/responses/503/content/application~1problem+json/schema\"}}")], + ["cancelRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/cancel\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1cancel/post/responses/503/content/application~1problem+json/schema\"}}")], + ["checkNow", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/check\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1check/post/responses/503/content/application~1problem+json/schema\"}}")], + ["inspectRun", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/runs/{runId}/inspect\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1inspect/get/responses/503/content/application~1problem+json/schema\"}}")], + ["reconcileRun", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/reconcile\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1reconcile/post/responses/503/content/application~1problem+json/schema\"}}")], + ["retrySame", JSON.parse("{\"method\":\"POST\",\"path\":\"/v1/runs/{runId}/retry-same\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":true,\"requestMediaTypes\":[\"application/json\"],\"requestMediaType\":\"application/json\",\"problems\":{\"400\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/400/content/application~1problem+json/schema\",\"401\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/409/content/application~1problem+json/schema\",\"413\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/413/content/application~1problem+json/schema\",\"415\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/415/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1runs~1{runId}~1retry-same/post/responses/503/content/application~1problem+json/schema\"}}")], + ["workflowContract", JSON.parse("{\"method\":\"GET\",\"path\":\"/v1/workflows/{workflowId}\",\"responses\":{\"200\":[{\"mediaType\":\"application/json\",\"mode\":\"json\",\"rule\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/200/content/application~1json/schema\"}]},\"keyed\":false,\"mutating\":false,\"problems\":{\"401\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/401/content/application~1problem+json/schema\",\"403\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/403/content/application~1problem+json/schema\",\"404\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/404/content/application~1problem+json/schema\",\"405\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/405/content/application~1problem+json/schema\",\"409\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/409/content/application~1problem+json/schema\",\"500\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/500/content/application~1problem+json/schema\",\"503\":\"/paths/~1v1~1workflows~1{workflowId}/get/responses/503/content/application~1problem+json/schema\"}}")], ]) for (const [id, definition] of Object.entries(definitions)) { const responses: Operation["responses"] = {} diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts new file mode 100644 index 0000000000..b7ed745014 --- /dev/null +++ b/clients/typescript/holder-function.ts @@ -0,0 +1,277 @@ +import { RegistryError } from './core.ts' + +const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u +const strongTag = /^"[\x21\x23-\x7e]{1,254}"$/u +const maximumRequestBytes = 32_768 +const bodyTooLarge = Symbol('body too large') + +export interface HolderSubmission { + recordId: string + ifMatch: string + preparation: Preparation +} + +export interface HolderCommand { + recordId: string + ifMatch: string + idempotencyKey: string + input: Input + signal: AbortSignal +} + +/** Host-owned parsing and invocation for one generated BReg Action on one existing Record and its fixed access profile. */ +export interface HolderTargetBinding { + kind: 'target' + path: string + preparationTimeoutMs: number + parseSubmission: (body: unknown) => HolderSubmission | undefined + parsePreparation: (body: unknown) => Input | undefined + invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> +} + +export interface HolderCreateSubmission { + preparation: Preparation +} + +export interface HolderCreateCommand { + idempotencyKey: string + input: Input + signal: AbortSignal +} + +/** + * Host-owned parsing and invocation for one generated BReg Action that creates one new Record. + * The submission names no target and no condition. Neither the page nor the function can name + * the new Record's owner, as long as the host's preparation parser admits only the Action's + * inputs: the Action's own plan and row boundaries then decide it. Bind it only to an Action that + * inserts a Record. Bound to one that patches, BReg refuses the unconditioned patch under the + * default `condition-required` concurrency, and the handler relays that refusal. Under + * `current-revision` the patch commits with no condition and every answer is unresolved. + */ +export interface HolderCreateBinding { + kind: 'create' + path: string + preparationTimeoutMs: number + parseSubmission: (body: unknown) => HolderCreateSubmission | undefined + parsePreparation: (body: unknown) => Input | undefined + /** Returns the Record the Action created and its revision, from the generated receipt. */ + invoke: (credential: string, command: HolderCreateCommand) => Promise<{ recordId: string; revision: number }> +} + +export type HolderActionBinding = + HolderTargetBinding | HolderCreateBinding + +function reply(body: object, status: number): Response { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +function unresolvedOutcome(status = 502): Response { + return reply({ + code: 'holder-action.outcome-unresolved', + message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }, status) +} + +function parseJson(source: string): unknown { + const value: unknown = JSON.parse(source, (_key, member: unknown) => { + if (typeof member === 'number' && + (!Number.isFinite(member) || Number.isInteger(member) && !Number.isSafeInteger(member))) { + throw new SyntaxError('Unsupported JSON number.') + } + return member + }) + // On valid JSON, a quoted token followed by a colon is an object key. + // Decode the key before comparing so Unicode escapes cannot hide duplicates. + const objects: Set[] = [] + for (const [token, quoted, colon] of source.matchAll(/("(?:[^"\\]|\\.)*")(\s*:)?|[{}]/gu)) { + if (token === '{') objects.push(new Set()) + if (token === '}') objects.pop() + if (quoted && colon) { + const keys = objects.at(-1)! + const key: string = JSON.parse(quoted) + if (keys.has(key)) throw new SyntaxError('Duplicate JSON member.') + keys.add(key) + } + } + return value +} + +async function readSubmission(request: Request): Promise { + if (!request.body) return undefined + const reader = request.body.getReader() + const decoder = new TextDecoder('utf-8', { fatal: true }) + let bytes = 0 + let body = '' + try { + for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) { + bytes += chunk.value.byteLength + if (bytes > maximumRequestBytes) { + await reader.cancel() + return bodyTooLarge + } + body += decoder.decode(chunk.value, { stream: true }) + } + return parseJson(body + decoder.decode()) + } finally { + reader.releaseLock() + } +} + +async function prepareInTime(run: (signal: AbortSignal) => unknown, signal: AbortSignal, timeoutMs: number): Promise { + signal.throwIfAborted() + const deadlineAt = performance.now() + timeoutMs + const expired = new Error('The preparation deadline expired.') + let stop!: (reason: unknown) => void + const stopped = new Promise((_resolve, reject) => { stop = reject }) + const abort = () => stop(signal.reason) + signal.addEventListener('abort', abort, { once: true }) + // One timer ends the race and aborts the preparation's own signal together. + const deadline = new AbortController() + const timer = setTimeout(() => { + deadline.abort(expired) + stop(expired) + }, timeoutMs) + try { + // The preparation's own signal follows the caller and the deadline, so cooperative code + // can stop early; the race below does not depend on it. + const preparationSignal = AbortSignal.any([signal, deadline.signal]) + const result = await Promise.race([stopped, Promise.resolve().then(() => { + signal.throwIfAborted() + return run(preparationSignal) + })]) + signal.throwIfAborted() + if (performance.now() >= deadlineAt) throw expired + return result + } finally { + clearTimeout(timer) + signal.removeEventListener('abort', abort) + } +} + +/** A product's own refusal, or an unresolved answer for a spent key; undefined for anything else. */ +function productRefusal(error: unknown): Response | undefined { + if (error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown && + error.status !== undefined && error.status >= 400 && error.status < 500) { + if (error.status === 409 && error.code === 'idempotency.key-reused' || + error.status === 410 && error.code === 'idempotency.expired') return unresolvedOutcome(error.status) + return reply({ message: 'BReg refused the request.' }, error.status) + } + return undefined +} + +/** + * Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. + * + * The handler checks only the bearer's shape. BReg verifies it at dispatch, after `prepare` has run, so + * serve the handler only behind the Session gateway, on a listener nothing else can reach. The binding's + * path is the browser-facing `/api/functions/`: a gateway that relays to `/functions/` + * needs the host to hand the handler a request with the browser-facing path. + * + * The binding minimises the arguments `prepare` receives: one projected value and a signal, never the + * Request, a header, the caller's credential or a product client. It does not isolate `prepare`. The + * callback runs in the invoker's process, so code there can reach whatever that process can, including + * the next caller's request. Use it only for trusted, reviewed function code, and run unreviewed + * functions outside the invoker's process. + * + * An unresolved answer (`holder-action.outcome-unresolved`) means the product may have acted. The page + * must keep the original attempt key and body until a matching receipt arrives, even through an + * ordinary refusal of a retry such as an expired sign-in: the handler is stateless and cannot tell + * such a refusal apart from one on a fresh attempt, and a new key can create a second Record. + */ +export function createHolderActionHandler( + binding: HolderActionBinding, + prepare: (input: Preparation, options: { signal: AbortSignal }) => unknown | Promise, +): (request: Request) => Promise { + // Read the binding once: later changes to the object it came from have no effect. + const { kind, path, preparationTimeoutMs, parsePreparation } = binding + if (kind !== 'target' && kind !== 'create') throw new TypeError('Expected a target or create holder binding.') + const target = kind === 'target' ? { parseSubmission: binding.parseSubmission, invoke: binding.invoke } : undefined + const create = kind === 'create' && binding.kind === 'create' ? { parseSubmission: binding.parseSubmission, invoke: binding.invoke } : undefined + if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') + if (!Number.isSafeInteger(preparationTimeoutMs) || preparationTimeoutMs < 1 || preparationTimeoutMs > 2_147_483_647) { + throw new TypeError('Expected a bounded preparation deadline.') + } + + return async request => { + const url = new URL(request.url) + if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) { + return reply({ message: 'Unknown function route.' }, 404) + } + const credential = /^Bearer ([A-Za-z0-9._-]+)$/u.exec(request.headers.get('authorization') ?? '')?.[1] + if (!credential) return reply({ message: 'Sign in to continue.' }, 401) + + const idempotencyKey = request.headers.get('idempotency-key')?.toLowerCase() + const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() + if (!idempotencyKey || !uuid.test(idempotencyKey) || mediaType !== 'application/json') { + return reply({ message: 'Send a JSON request with its attempt key.' }, 400) + } + let body: unknown + try { + body = await readSubmission(request) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413) + + if (create) { + let created: HolderCreateSubmission | undefined + try { + if (body !== undefined) created = create.parseSubmission(body) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (!created) return reply({ message: 'Send the declared request.' }, 400) + let input: Input | undefined + try { + input = parsePreparation(await prepareInTime( + signal => prepare(created.preparation, { signal }), request.signal, preparationTimeoutMs)) + } catch { + return reply({ message: 'The function could not prepare the request.' }, 502) + } + if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + try { + const result = await create.invoke(credential, { idempotencyKey, input, signal: request.signal }) + // A receipt at revision 1 names a Record this attempt key inserted: BReg writes revision 1 + // on insert, and a same-key replay returns the stored receipt, revision 1 included, even + // after later changes. BReg's idempotency per issuer, subject and key gives the single effect. + if (typeof result.recordId === 'string' && uuid.test(result.recordId) && result.revision === 1) { + return reply({ recordId: result.recordId }, 200) + } + } catch (error) { + const refusal = productRefusal(error) + if (refusal) return refusal + } + return unresolvedOutcome() + } + + let submission: HolderSubmission | undefined + try { + if (body !== undefined) submission = target!.parseSubmission(body) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (typeof submission?.recordId !== 'string' || typeof submission.ifMatch !== 'string' || + !uuid.test(submission.recordId) || !strongTag.test(submission.ifMatch)) { + return reply({ message: 'Send a record and its reviewed condition.' }, 400) + } + const { recordId, ifMatch, preparation } = submission + + let input: Input | undefined + try { + input = parsePreparation(await prepareInTime( + signal => prepare(preparation, { signal }), request.signal, preparationTimeoutMs)) + } catch { + return reply({ message: 'The function could not prepare the request.' }, 502) + } + if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + + try { + const result = await target!.invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) + if (result.recordId === recordId) return reply({ recordId }, 200) + } catch (error) { + const refusal = productRefusal(error) + if (refusal) return refusal + } + return unresolvedOutcome() + } +} diff --git a/clients/typescript/package.json b/clients/typescript/package.json index 377f2ef535..c0b61fb3b7 100644 --- a/clients/typescript/package.json +++ b/clients/typescript/package.json @@ -34,6 +34,10 @@ "types": "./dist/mcp.d.ts", "default": "./dist/mcp.js" }, + "./holder-function": { + "types": "./dist/holder-function.d.ts", + "default": "./dist/holder-function.js" + }, "./products/*": { "types": "./dist/generated/*.d.ts", "default": "./dist/generated/*.js" diff --git a/clients/typescript/preview/build.mjs b/clients/typescript/preview/build.mjs index da94701b36..3cda37aab9 100644 --- a/clients/typescript/preview/build.mjs +++ b/clients/typescript/preview/build.mjs @@ -40,23 +40,38 @@ async function copySource(path, target, exclude) { }) } -async function runGenerator(plan, staged) { +// An actors preview names no Proposal author: each actor's gateway pins its own +// BReg profile, so no single author profile fits every actor's page. +export function generatorArguments(plan, staged) { const { id, member, profile } = plan.product const project = plan.sourceProject ?? plan.product.project + return [ + join(clientPackage, 'registry-generate.js'), + '--register', member + '=' + project, + '--route-prefix', member + '=/registry/' + id, + ...(plan.preview.actors === undefined ? ['--author-profile', member + '=' + profile] : []), + '--preview', ...plan.preview.functions.flatMap(name => ['--preview-function', name]), + '--output', join(staged, 'generated', 'service.ts'), + ] +} + +export function generationError(stderr, actors) { + const diagnostic = stderr.trim() + if (actors && /has Proposals, so the service description needs authorProfiles/u.test(diagnostic)) { + return new Error(diagnostic + '\nAn actors preview cannot start Proposals: no single actor profile authors them. Use the single-actor form for a register with Proposals.') + } + if (/cannot start Proposals/u.test(diagnostic)) { + return new Error(diagnostic + '\nSelect a preview actor whose BReg profile can start Proposals.') + } + return new Error(diagnostic || 'Preview client generation failed. Check the native project and install matching BReg tools.') +} + +async function runGenerator(plan, staged) { try { - await runFile(process.execPath, [ - join(clientPackage, 'registry-generate.js'), - '--register', member + '=' + project, - '--route-prefix', member + '=/registry/' + id, - '--author-profile', member + '=' + profile, - '--preview', ...plan.preview.functions.flatMap(name => ['--preview-function', name]), - '--output', join(staged, 'generated', 'service.ts'), - ], { cwd: staged, timeout: 90_000, maxBuffer: 1024 * 1024 }) + await runFile(process.execPath, generatorArguments(plan, staged), + { cwd: staged, timeout: 90_000, maxBuffer: 1024 * 1024 }) } catch (error) { - if (/cannot start Proposals/u.test(String(error.stderr ?? ''))) { - throw new Error('The preview actor cannot start Proposals in this project. Select a preview actor whose BReg profile can start Proposals.') - } - throw new Error('Preview client generation failed. Check the native project and install matching BReg tools.') + throw generationError(String(error.stderr ?? ''), plan.preview.actors !== undefined) } } @@ -196,6 +211,7 @@ export async function buildPreview(plan, directory) { version: versionLine, declarationDigest: plan.declarationDigest, product: plan.product, + routeProducts: plan.routeProducts ?? [], preview: plan.preview, functions: entries.map(([name]) => name), staticOutput: relative(directory, staticOutput), diff --git a/clients/typescript/preview/config.mjs b/clients/typescript/preview/config.mjs index 9202fe02f1..3b04538b4a 100644 --- a/clients/typescript/preview/config.mjs +++ b/clients/typescript/preview/config.mjs @@ -59,13 +59,68 @@ export async function prepareRuntimeConfig({ artifact, deployment, run }) { || run.preview.productId !== artifact.product.id || run.preview.profile !== artifact.product.profile) { throw new Error('The preview product or audience differs from the checked plan.') } - const { authorizationFile } = run.preview - if (typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { - throw new Error('The preview needs an owner-only run authorization file.') + const { authorizationFile, functionHost, actors } = run.preview + if (artifact.preview?.actors === undefined) { + if (actors !== undefined) throw new Error('A single-actor preview takes no actors.') + if (typeof authorizationFile !== 'string' || !isAbsolute(authorizationFile)) { + throw new Error('The preview needs an owner-only run authorization file.') + } + } else { + checkActors(artifact, run, actors) + } + const functionPort = functionHost?.port + if (!Number.isInteger(functionPort) || functionPort < 1 || functionPort > 65535 || functionPort === port + || `http://127.0.0.1:${functionPort}` === run.breg.baseUrl + || typeof functionHost.keyFile !== 'string' || !isAbsolute(functionHost.keyFile)) { + throw new Error('The preview needs the reserved function host port and owner-only host key file.') } return { schema, runId: run.runId, origin, port, breg: run.breg, preview: run.preview } } +// Each actor has its own loopback origin, and for each product it may reach +// the product's origin and audience as checked, the access profile the +// gateway pins (none for the Coordinator), and its own credential file. +function checkActors(artifact, run, actors) { + const names = Object.keys(artifact.preview.actors) + const products = new Map((artifact.routeProducts ?? []).map(product => [product.id, product])) + products.set(artifact.product.id, { id: artifact.product.id, kind: 'breg', audience: artifact.product.audience }) + if (run.preview.authorizationFile !== undefined) { + throw new Error('An actors preview takes no single authorization file.') + } + if (!Array.isArray(actors) || actors.map(actor => actor?.name).join() !== names.join()) { + throw new Error('The preview actors differ from the checked plan.') + } + const ports = new Set([run.preview.functionHost?.port, URL.parse(run.breg.baseUrl)?.port]) + actors.forEach((actor, index) => { + if (index === 0 && (actor.origin !== run.origin || actor.port !== run.port)) { + throw new Error('The first preview actor must serve the run origin.') + } + if (loopbackOrigin(actor.origin) !== `http://127.0.0.1:${actor.port}` || !Number.isInteger(actor.port) + || ports.has(actor.port) || ports.has(String(actor.port))) { + throw new Error('Each preview actor needs its own reserved loopback address.') + } + ports.add(actor.port) + const routes = artifact.preview.actors[actor.name] + const entries = typeof actor.products === 'object' && actor.products !== null ? Object.entries(actor.products) : [] + const kinds = entries.map(([id]) => products.get(id)?.kind) + if (Object.keys(routes).some(kind => !kinds.includes(kind))) { + throw new Error('A preview actor reaches a product it has no credential for.') + } + for (const [id, product] of entries) { + const checked = Object.hasOwn(Object.fromEntries(products), id) ? products.get(id) : undefined + if (!checked) throw new Error('A preview actor has a credential for a product the plan does not route.') + if (loopbackOrigin(product.baseUrl) === actor.origin) { + throw new Error("A preview actor reaches a product on the actor's own origin.") + } + if (product.audience !== checked.audience + || (checked.kind === 'coordinator' ? product.profile !== null : typeof product.profile !== 'string') + || typeof product.authorizationFile !== 'string' || !isAbsolute(product.authorizationFile)) { + throw new Error('A preview actor product differs from the checked plan.') + } + } + }) +} + async function checkCredentialPath(path, runFile) { const file = await lstat(path) if (dirname(path) !== dirname(runFile) || !file.isFile() || file.isSymbolicLink() @@ -76,7 +131,14 @@ async function checkCredentialPath(path, runFile) { export async function configure({ artifact, deployment, runFile }) { const config = await prepareRuntimeConfig({ artifact, deployment, run: await readJson(runFile) }) - await checkCredentialPath(config.preview.authorizationFile, runFile) + if (config.preview.actors === undefined) { + await checkCredentialPath(config.preview.authorizationFile, runFile) + } else { + for (const actor of config.preview.actors) { + for (const product of Object.values(actor.products)) await checkCredentialPath(product.authorizationFile, runFile) + } + } + await checkCredentialPath(config.preview.functionHost.keyFile, runFile) return config } @@ -94,6 +156,12 @@ export async function checkRuntimeConfig(configFile, artifact) { return checked } +export async function readHostKey(path) { + const key = /^([A-Za-z0-9_-]{32,256})\n?$/u.exec(await readFile(path, 'utf8'))?.[1] + if (!key) throw new Error('Expected the run function host key file.') + return key +} + export async function readAuthorization(path) { const line = await readFile(path, 'utf8') const authorization = /^Authorization: (Bearer [A-Za-z0-9._-]+)\r?\n?$/u.exec(line)?.[1] diff --git a/clients/typescript/preview/gateway.mjs b/clients/typescript/preview/gateway.mjs index 2ce51fac61..068fe6f799 100644 --- a/clients/typescript/preview/gateway.mjs +++ b/clients/typescript/preview/gateway.mjs @@ -2,7 +2,7 @@ import { constants } from 'node:fs' import { lstat, open, readdir } from 'node:fs/promises' import { createServer } from 'node:http' import { extname, join } from 'node:path' -import { healthPath, localId, loopbackOrigin } from './config.mjs' +import { healthPath, localId, loopbackOrigin, readAuthorization } from './config.mjs' import { maxRequestBodySize } from './host.mjs' const maxResponseSize = 4 * 1024 * 1024 @@ -10,6 +10,8 @@ const maxStaticSize = 32 * 1024 * 1024 const timeout = 15_000 const segment = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu +const revision = /^[1-9][0-9]{0,18}$/u +const maximumRevision = '9223372036854775807' const contentTypes = new Map([ ['.css', 'text/css; charset=utf-8'], ['.html', 'text/html; charset=utf-8'], @@ -28,17 +30,70 @@ class RequestError extends Error { } } +// A route segment that stands for one product-assigned UUID. `{revision}` +// stands for one Record revision number. +const placeholders = new Set(['{recordId}', '{record_id}', '{taskId}', '{runId}']) + function compilePaths(paths = []) { if (!Array.isArray(paths)) throw new Error('Expected a list of preview routes per method.') return paths.map((path) => { - const parts = typeof path === 'string' && path.startsWith('/v1/') ? path.slice(1).split('/') : [] - if (parts.length < 2 || parts.filter(part => part === '{recordId}').length > 1 || !parts.every(part => segment.test(part) || part === '{recordId}')) { - throw new Error('Expected an exact /v1/ preview route with {recordId} for a Record ID.') + const parts = typeof path === 'string' && path.length <= 256 && path.startsWith('/v1/') ? path.slice(1).split('/') : [] + if (parts.length < 2 || parts.filter(part => placeholders.has(part)).length > 1 + || parts.filter(part => part === '{revision}').length > 1 + || !parts.every(part => segment.test(part) || placeholders.has(part) || part === '{revision}')) { + throw new Error('Expected an exact /v1/ preview route with at most one {recordId}, {record_id}, {taskId} or {runId} and at most one {revision}.') } return parts }) } +// The exact GET and POST routes one actor may reach on one product. +export function compileRoutes(routes = {}) { + const compiled = new Map([['GET', compilePaths(routes.get)], ['POST', compilePaths(routes.post)]]) + return (method, path) => { + const parts = path.slice(1).split('/') + return Boolean(compiled.get(method)?.some(route => + route.length === parts.length && route.every((part, index) => { + const value = parts[index] + if (placeholders.has(part)) return uuid.test(value) + if (part === '{revision}') return revision.test(value) && (value.length < maximumRevision.length || value <= maximumRevision) + return part === value + }), + )) + } +} + +// The gateway options for each actor, in plan order. An actor's gateway gets +// only that actor's credential files, and for each product only the routes the +// actor declares for its kind. Functions run under the actor's own BReg +// credential, and an actor without one serves no function route. +export function actorGatewayOptions(artifact, actors) { + const policy = previewPolicy(artifact.preview) + const kinds = new Map((artifact.routeProducts ?? []).map(product => [product.id, product.kind])) + kinds.set(artifact.product.id, 'breg') + const none = compileRoutes({}) + return actors.map(actor => { + const routes = policy.actors.get(actor.name) + const products = Object.fromEntries(Object.entries(actor.products).map(([id, product]) => { + const kind = kinds.get(id) + return [id, { + origin: product.baseUrl, + profile: product.profile, + authorization: () => readAuthorization(product.authorizationFile), + allows: kind !== undefined && Object.hasOwn(routes, kind) ? routes[kind] : none, + }] + })) + const breg = Object.hasOwn(actor.products, artifact.product.id) ? actor.products[artifact.product.id] : undefined + return { + origin: actor.origin, + port: actor.port, + actor: actor.name, + products, + functionAuthorization: breg ? () => readAuthorization(breg.authorizationFile) : null, + } + }) +} + export function previewPolicy(preview) { const page = preview.page === '/' ? '/index.html' : preview.page if (typeof page !== 'string' || !/^\/(?:[A-Za-z0-9][A-Za-z0-9_-]*\/)*[A-Za-z0-9][A-Za-z0-9_-]*\.html$/u.test(page)) { @@ -48,20 +103,27 @@ export function previewPolicy(preview) { || new Set(preview.functions).size !== preview.functions.length) { throw new Error('Expected distinct preview function IDs.') } - const routes = new Map([ - ['GET', compilePaths(preview.breg.get)], - ['POST', compilePaths(preview.breg.post)], - ]) + if ((preview.actors === undefined) === (preview.breg === undefined)) { + throw new Error('Expected either one actor with BReg routes or an actors map.') + } + const actors = new Map() + if (preview.actors !== undefined) { + const entries = typeof preview.actors === 'object' && preview.actors !== null ? Object.entries(preview.actors) : [] + if (entries.length < 1 || entries.length > 8 || entries.some(([name, routes]) => !localId.test(name) + || typeof routes !== 'object' || routes === null + || Object.keys(routes).some(kind => !['breg', 'casework', 'coordinator'].includes(kind)))) { + throw new Error('Expected one to eight preview actors with breg, casework or coordinator routes.') + } + for (const [name, routes] of entries) { + actors.set(name, Object.fromEntries(Object.entries(routes).map(([kind, set]) => [kind, compileRoutes(set)]))) + } + } + const allowsBreg = preview.breg === undefined ? () => false : compileRoutes(preview.breg) return { page, functions: new Set(preview.functions), - allowsBreg(method, path) { - const parts = path.slice(1).split('/') - return routes.get(method)?.some(route => - route.length === parts.length && route.every((part, index) => - part === '{recordId}' ? uuid.test(parts[index]) : part === parts[index]), - ) - }, + actors, + allowsBreg, } } @@ -134,28 +196,52 @@ function sendError(response, status, message) { response.end(JSON.stringify({ message })) } +// The products one gateway reaches, keyed by service product ID. Each carries +// its loopback origin, the access profile the gateway pins (or null for a +// product that selects no profile by query), the routes the actor may use, +// and the actor's own credential for that product. +function gatewayProducts({ productId, profile, breg, authorization, preview, products }) { + if (products !== undefined) { + const entries = Object.entries(products) + if (!entries.length || entries.some(([id, product]) => !localId.test(id) + || typeof product.allows !== 'function' || typeof product.authorization !== 'function' + || !(product.profile === null || typeof product.profile === 'string'))) { + throw new Error('Expected preview products with routes, a profile and a credential.') + } + return new Map(entries.map(([id, product]) => [id, { ...product, origin: loopbackOrigin(product.origin) }])) + } + if (!localId.test(productId)) throw new Error('The preview needs a local product ID.') + return new Map([[productId, { + origin: loopbackOrigin(breg), profile, authorization, allows: compileRoutes(preview.breg), + }]]) +} + export async function startPreviewGateway({ origin: initialOrigin, port, productId, profile, breg, + products: declaredProducts, + actor = null, application, authorization, + functionAuthorization = authorization, publicDirectory, preview, functionKey, }) { - if (!localId.test(productId)) throw new Error('The preview needs a local product ID.') - const bregOrigin = loopbackOrigin(breg) + const products = gatewayProducts({ productId, profile, breg, authorization, preview, products: declaredProducts }) const applicationOrigin = loopbackOrigin(application) const policy = previewPolicy(preview) + if (typeof functionAuthorization !== 'function' && functionAuthorization !== null) { + throw new Error('The preview needs the actor credential for its functions, or null to serve none.') + } const files = await collectStaticFiles(publicDirectory) if (!files.has(policy.page)) throw new Error('The preview output is missing the configured HTML page.') - const registryPrefix = '/registry/' + productId let origin = initialOrigin - async function relay(request, response, target, privateFunction = false) { + async function relay(request, response, target, authorization, privateFunction = false) { const headers = new Headers({ authorization: await authorization() }) if (privateFunction && functionKey) headers.set('x-registry-preview-function', functionKey) for (const name of ['accept', 'content-type', 'if-match', 'idempotency-key']) { @@ -188,6 +274,17 @@ export async function startPreviewGateway({ response.writeHead(204, responseSecurity).end() return } + // The actor this origin serves, so one built page can show its controls. + // It carries no credential and answers only the page. + if (actor !== null && method === 'GET' && rawTarget === '/_rstack/actor') { + if (headers['registry-client'] !== 'page' || (headers.origin !== undefined && headers.origin !== origin) + || (headers['sec-fetch-site'] !== undefined && headers['sec-fetch-site'] !== 'same-origin')) { + throw new RequestError(403, 'Open the service page to make this request') + } + response.writeHead(200, { ...responseSecurity, 'content-type': 'application/json' }) + .end(JSON.stringify({ actor })) + return + } if (!rawPath.startsWith('/') || rawTarget.length > 8192 || rawTarget.includes('#') || (rawPath !== '/' && !rawPath.slice(1).split('/').every(part => segment.test(part)))) { throw new RequestError(404, 'Unknown preview route') @@ -216,23 +313,29 @@ export async function startPreviewGateway({ || (method === 'POST' && headers.origin !== origin)) { throw new RequestError(403, 'Open the service page to make this request') } - if (method === 'POST' && rawPath.startsWith('/api/functions/') && !url.search) { + if (functionAuthorization && method === 'POST' && rawPath.startsWith('/api/functions/') && !url.search) { const name = rawPath.slice('/api/functions/'.length) if (policy.functions.has(name)) { - await relay(request, response, applicationOrigin + '/functions/' + name, true) + await relay(request, response, applicationOrigin + '/functions/' + name, functionAuthorization, true) return } } - if (rawPath.startsWith(registryPrefix + '/')) { - const bregPath = rawPath.slice(registryPrefix.length) - if (policy.allowsBreg(method, bregPath)) { - const requestedProfiles = url.searchParams.getAll('accessProfile') - if (requestedProfiles.length > 1 || requestedProfiles.some(value => value !== profile)) { - throw new RequestError(403, 'The request selects another access profile') - + const [, prefix, id, ...rest] = rawPath.split('/') + const product = prefix === 'registry' ? products.get(id) : undefined + if (product && rest.length) { + const productPath = '/' + rest.join('/') + if (product.allows(method, productPath)) { + if (product.profile === null) { + // A product that selects no profile by query takes no query at all. + if (url.search) throw new RequestError(404, 'Unknown preview route') + } else { + const requestedProfiles = url.searchParams.getAll('accessProfile') + if (requestedProfiles.length > 1 || requestedProfiles.some(value => value !== product.profile)) { + throw new RequestError(403, 'The request selects another access profile') + } + url.searchParams.set('accessProfile', product.profile) } - url.searchParams.set('accessProfile', profile) - await relay(request, response, bregOrigin + bregPath + url.search) + await relay(request, response, product.origin + productPath + url.search, product.authorization) return } } diff --git a/clients/typescript/preview/host.mjs b/clients/typescript/preview/host.mjs index 1c5dc2f564..4238cdbc17 100644 --- a/clients/typescript/preview/host.mjs +++ b/clients/typescript/preview/host.mjs @@ -1,12 +1,42 @@ +import { timingSafeEqual } from 'node:crypto' import { serve } from 'srvx/node' export const maxRequestBodySize = 32_768 -export async function startFunctionHost(handlers, { authorize }) { +const hostKeyPattern = /^[A-Za-z0-9_-]{32,256}$/u + +function same(value, expected) { + const given = Buffer.from(value ?? '') + return given.length === expected.length && timingSafeEqual(given, expected) +} + +// The fixed bearer a function called by Coordinator receives in place of the +// host key. It is not a secret and no product accepts it, so the key never +// leaves the host and the function holds no record authority. +export const coordinatorBearer = 'Bearer registry-preview-coordinator-call' + +// The run's function host key admits two callers: the preview gateway, which +// relays the page's principal and names the key in its own header, and +// Coordinator, which presents the key itself as its bearer credential. The +// check answers which caller it admitted, or false. +export function functionHostAuthorizer(key) { + if (typeof key !== 'string' || !hostKeyPattern.test(key)) { + throw new TypeError('The function host needs a run host key.') + } + const relayed = Buffer.from(key) + const bearer = Buffer.from('Bearer ' + key) + return request => { + const header = request.headers.get('x-registry-preview-function') + if (header === null) return same(request.headers.get('authorization'), bearer) && 'coordinator' + return same(header, relayed) && 'gateway' + } +} + +export async function startFunctionHost(handlers, { authorize, port = 0 }) { if (typeof authorize !== 'function') throw new TypeError('The private function host requires an authorization check.') const server = serve({ hostname: '127.0.0.1', - port: 0, + port, silent: true, gracefulShutdown: false, maxRequestBodySize, @@ -20,11 +50,11 @@ export async function startFunctionHost(handlers, { authorize }) { const name = /^\/functions\/([a-z][a-z0-9_-]{0,63})$/u.exec(path)?.[1] const handler = handlers.get(name) if (request.method !== 'POST' || !handler) return new Response('Not Found', { status: 404 }) - if (!/^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '') || - !authorize(request)) { - return new Response('Caller required', { status: 401 }) - } + const caller = /^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '') && + authorize(request) + if (!caller) return new Response('Caller required', { status: 401 }) request.headers.delete('x-registry-preview-function') + if (caller === 'coordinator') request.headers.set('authorization', coordinatorBearer) return handler(request) }, }) diff --git a/clients/typescript/preview/run.mjs b/clients/typescript/preview/run.mjs index c7cae5771a..1087cb883f 100644 --- a/clients/typescript/preview/run.mjs +++ b/clients/typescript/preview/run.mjs @@ -1,15 +1,19 @@ -import { randomBytes } from 'node:crypto' import { writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization } from './config.mjs' -import { startPreviewGateway } from './gateway.mjs' -import { startFunctionHost } from './host.mjs' +import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization, readHostKey } from './config.mjs' +import { actorGatewayOptions, startPreviewGateway } from './gateway.mjs' +import { functionHostAuthorizer, startFunctionHost } from './host.mjs' async function run() { const configFile = process.env[configEnvironment] const artifact = await readArtifact() const config = await checkRuntimeConfig(configFile, artifact) - await readAuthorization(config.preview.authorizationFile) + const actors = config.preview.actors + for (const file of actors === undefined + ? [config.preview.authorizationFile] + : actors.flatMap(actor => Object.values(actor.products).map(product => product.authorizationFile))) { + await readAuthorization(file) + } const connection = Object.freeze({ ...config.breg }) const products = Object.freeze({ [artifact.product.id]: connection }) const handlers = new Map() @@ -24,34 +28,48 @@ async function run() { } } - const functionKey = randomBytes(32).toString('base64url') + const functionKey = await readHostKey(config.preview.functionHost.keyFile) const privateHost = await startFunctionHost(handlers, { - authorize: request => request.headers.get('x-registry-preview-function') === functionKey, + authorize: functionHostAuthorizer(functionKey), + port: config.preview.functionHost.port, }) - let gateway + const gateways = [] try { await writeFile(join(dirname(configFile), 'application-preview-function-origin'), privateHost.origin + '\n', { flag: 'wx', mode: 0o600 }) - gateway = await startPreviewGateway({ - origin: config.origin, - port: config.port, - productId: artifact.product.id, - profile: artifact.product.profile, - breg: config.breg.baseUrl, + const shared = { application: privateHost.origin, - authorization: () => readAuthorization(config.preview.authorizationFile), publicDirectory: join(artifactDirectory, artifact.staticOutput), preview: artifact.preview, functionKey, - }) + } + if (actors === undefined) { + gateways.push(await startPreviewGateway({ + ...shared, + origin: config.origin, + port: config.port, + productId: artifact.product.id, + profile: artifact.product.profile, + breg: config.breg.baseUrl, + authorization: () => readAuthorization(config.preview.authorizationFile), + })) + } else { + // One gateway per actor, each on its own origin over the same static + // bytes, carrying only that actor's credentials and routes. + // The run checks readiness on the first actor's origin, so that + // gateway starts last, once every other actor's gateway listens. + for (const options of actorGatewayOptions(artifact, actors).reverse()) { + gateways.push(await startPreviewGateway({ ...shared, ...options })) + } + } } catch (error) { - await privateHost.close() + await Promise.all([...gateways.map(gateway => gateway.close()), privateHost.close()]) throw error } let closing function close() { - closing ??= Promise.all([gateway.close(), privateHost.close()]).catch(() => { + closing ??= Promise.all([...gateways.map(gateway => gateway.close()), privateHost.close()]).catch(() => { console.error('Cannot close the preview listeners cleanly.') process.exitCode = 1 }) diff --git a/clients/typescript/preview/tests/preview.test.mjs b/clients/typescript/preview/tests/preview.test.mjs index 097b9a796d..b8463d59ce 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -1,15 +1,61 @@ import { strict as assert } from 'node:assert' -import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises' +import { chmod, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { createServer, request } from 'node:http' import { test } from 'node:test' -import { startFunctionHost } from '../host.mjs' -import { collectStaticFiles, startPreviewGateway } from '../gateway.mjs' -import { prepareRuntimeConfig } from '../config.mjs' -import { buildPreview } from '../build.mjs' +import { coordinatorBearer, functionHostAuthorizer, startFunctionHost } from '../host.mjs' +import { actorGatewayOptions, collectStaticFiles, compileRoutes, previewPolicy, startPreviewGateway } from '../gateway.mjs' +import { configure, prepareRuntimeConfig, readHostKey } from '../config.mjs' +import { buildPreview, generationError, generatorArguments } from '../build.mjs' import { createHash } from 'node:crypto' +test('preview policy matches both Record revision parameters without expanding methods or routes', () => { + const recordId = '00000000-0000-0000-0000-000000000001' + const root = '/v1/records/applications/' + for (const id of ['{record_id}', '{recordId}']) { + const policy = previewPolicy({ page: '/', functions: [], breg: { get: [root + id + '/revisions/{revision}'] } }) + assert.equal(policy.allowsBreg('GET', root + recordId + '/revisions/2'), true) + assert.equal(policy.allowsBreg('GET', root + recordId + '/revisions/9223372036854775807'), true) + assert.equal(policy.allowsBreg('POST', root + recordId + '/revisions/2'), false) + for (const suffix of ['0', '-1', '2%2fother', '9223372036854775808', '2/another']) { + assert.equal(policy.allowsBreg('GET', root + recordId + '/revisions/' + suffix), false) + } + assert.equal(policy.allowsBreg('GET', root + 'not-a-uuid/revisions/2'), false) + } + for (const path of [root + '{anything}', root + '{recordId}/{record_id}', root + '{recordId}/revisions/{revision}/{revision}']) { + assert.throws(() => previewPolicy({ page: '/', functions: [], breg: { get: [path] } }), /preview route/u) + } +}) + +test('preview build forwards the generator diagnostic', async (t) => { + const root = await realpath(await mkdtemp(join(tmpdir(), 'registry-preview-diagnostic-'))) + t.after(() => rm(root, { recursive: true })) + const file = join(root, 'service.yaml') + const ui = join(root, 'web') + const entry = join(root, 'functions', 'renew', 'index.ts') + const generator = join(root, 'generator') + await mkdir(ui) + await mkdir(join(root, 'functions', 'renew'), { recursive: true }) + await writeFile(file, 'fixture declaration') + await writeFile(entry, 'export default () => {}') + const diagnostic = '/paths/~1v1~1records~1fixture/get: unsupported fixture schema' + await writeFile(generator, `#!/bin/sh\nprintf '%s\\n' '${diagnostic}' >&2\nexit 1\n`, { mode: 0o700 }) + const execPath = process.execPath + process.execPath = generator + try { + await assert.rejects(buildPreview({ + file, workspaceRoot: root, declarationDigest: createHash('sha256').update('fixture declaration').digest('hex'), + product: { id: 'licenses', member: 'licenses', project: root, profile: 'holder' }, + ui: { project: ui, output: join(ui, 'dist') }, + functions: { renew: entry }, + preview: { page: '/', breg: {}, functions: ['renew'] }, + }, join(root, 'artifact')), { message: diagnostic }) + } finally { + process.execPath = execPath + } +}) + test('prepare binds the run to the declaration, product, audience and loopback address', async (t) => { const root = await mkdtemp(join(tmpdir(), 'registry-preview-test-')) t.after(() => rm(root, { recursive: true })) @@ -17,16 +63,21 @@ test('prepare binds the run to the declaration, product, audience and loopback a const authorizationFile = join(root, 'authorization') await writeFile(deployment, 'service declaration') await writeFile(authorizationFile, 'Authorization: Bearer synthetic.actor.token\n', { mode: 0o600 }) + const keyFile = join(root, 'function-host-key') const declarationDigest = createHash('sha256').update('service declaration').digest('hex') const artifact = { declarationDigest, product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' } } const run = { schema: 'registry-stack.local-service-preview/v1', runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:preview' }, - preview: { productId: 'licenses', profile: 'holder', authorizationFile, declarationDigest }, + preview: { + productId: 'licenses', profile: 'holder', authorizationFile, declarationDigest, + functionHost: { port: 45678, keyFile }, + }, } const valid = await prepareRuntimeConfig({ artifact, deployment, run }) assert.equal(valid.breg.baseUrl, run.breg.baseUrl) + assert.deepEqual(valid.preview.functionHost, { port: 45678, keyFile }) for (const invalid of [ { ...run, breg: { ...run.breg, audience: 'urn:wrong' } }, { ...run, breg: { ...run.breg, baseUrl: 'http://example.test:34567' } }, @@ -34,6 +85,11 @@ test('prepare binds the run to the declaration, product, audience and loopback a { ...run, preview: { ...run.preview, profile: 'wrong' } }, { ...run, preview: { ...run.preview, declarationDigest: 'wrong' } }, { ...run, port: 34567 }, + { ...run, preview: { ...run.preview, functionHost: undefined } }, + { ...run, preview: { ...run.preview, functionHost: { port: 23456, keyFile } } }, + { ...run, preview: { ...run.preview, functionHost: { port: 34567, keyFile } } }, + { ...run, preview: { ...run.preview, functionHost: { port: 0, keyFile } } }, + { ...run, preview: { ...run.preview, functionHost: { port: 45678, keyFile: 'relative-key' } } }, ]) { await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: invalid })) } @@ -153,3 +209,384 @@ test('build refuses a changed declaration or a linked function before staging', preview: { ...plan.preview, functions: ['linked'] }, }, join(root, 'artifact')), /source resolves outside/i) }) + +test('the function host binds its reserved port and admits only the run host key', async (t) => { + const key = 'synthetic-function-host-key-0123456789abcdefghij' + const authorize = functionHostAuthorizer(key) + const call = headers => new Request('http://127.0.0.1/functions/renew', { method: 'POST', headers }) + // The gateway relays the page's principal with the host key header. + assert.equal(authorize(call({ authorization: 'Bearer page.token', 'x-registry-preview-function': key })), 'gateway') + // Coordinator presents the host key itself as its bearer credential. + assert.equal(authorize(call({ authorization: 'Bearer ' + key })), 'coordinator') + for (const headers of [ + { authorization: 'Bearer page.token' }, + { authorization: 'Bearer ' + key + 'x' }, + { authorization: 'Bearer page.token', 'x-registry-preview-function': 'wrong' }, + { authorization: 'Bearer ' + key, 'x-registry-preview-function': 'wrong' }, + ]) { + assert.equal(authorize(call(headers)), false, JSON.stringify(headers)) + } + assert.throws(() => functionHostAuthorizer('short')) + + const reservation = createServer() + await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve)) + const { port } = reservation.address() + await new Promise(resolve => reservation.close(resolve)) + let seen + const host = await startFunctionHost(new Map([ + ['renew', async request => { + seen = request.headers.get('authorization') + return new Response('renewed') + }], + ]), { authorize, port }) + t.after(() => host.close()) + assert.equal(host.origin, 'http://127.0.0.1:' + port) + const route = host.origin + '/functions/renew' + assert.equal((await fetch(route, { method: 'POST', headers: { authorization: 'Bearer other.token' } })).status, 401) + const answer = await fetch(route, { method: 'POST', headers: { authorization: 'Bearer ' + key } }) + assert.equal(await answer.text(), 'renewed') + // The function receives a fixed placeholder, never the host key. + assert.equal(seen, coordinatorBearer) +}) + +test('the run host key file must be owner-only, in the run directory, and well formed', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-key-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'service declaration') + const declarationDigest = createHash('sha256').update('service declaration').digest('hex') + const artifact = { declarationDigest, product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' } } + const authorizationFile = join(root, 'authorization') + await writeFile(authorizationFile, 'Authorization: Bearer synthetic.actor.token\n', { mode: 0o600 }) + const keyFile = join(root, 'function-host-key') + const key = 'synthetic-function-host-key-0123456789abcdefghij' + const runFile = join(root, 'application-run.json') + await writeFile(runFile, JSON.stringify({ + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:preview' }, + preview: { + productId: 'licenses', profile: 'holder', authorizationFile, declarationDigest, + functionHost: { port: 45678, keyFile }, + }, + })) + await writeFile(keyFile, key + '\n', { mode: 0o600 }) + await configure({ artifact, deployment, runFile }) + assert.equal(await readHostKey(keyFile), key) + + await chmod(keyFile, 0o640) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) + await chmod(keyFile, 0o600) + await rm(keyFile) + await writeFile(join(root, 'elsewhere'), key, { mode: 0o600 }) + await symlink(join(root, 'elsewhere'), keyFile) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) + await rm(keyFile) + for (const malformed of ['short', key + ' extra', 'Bearer ' + key]) { + await writeFile(keyFile, malformed, { mode: 0o600 }) + await assert.rejects(readHostKey(keyFile), /host key/u) + await rm(keyFile) + } +}) + +test('an actors policy compiles per-product routes and is exclusive with the single-actor form', () => { + const actors = { + applicant: { breg: { post: ['/v1/actions/submit-application'] }, coordinator: { get: ['/v1/runs/{runId}'], post: ['/v1/runs'] } }, + officer: { casework: { get: ['/v1/review-tasks'], post: ['/v1/review-tasks/{taskId}/decisions'] } }, + } + const policy = previewPolicy({ page: '/', functions: ['assess-permit'], actors }) + assert.deepEqual([...policy.actors.keys()], ['applicant', 'officer']) + const run = '00000000-0000-4000-8000-000000000001' + assert.equal(policy.actors.get('applicant').coordinator('GET', '/v1/runs/' + run), true) + assert.equal(policy.actors.get('applicant').coordinator('GET', '/v1/runs/not-a-uuid'), false) + assert.equal(policy.actors.get('officer').casework('POST', '/v1/review-tasks/' + run + '/decisions'), true) + assert.equal(policy.actors.get('officer').breg, undefined) + assert.equal(policy.allowsBreg('GET', '/v1/records/licenses'), false) + for (const invalid of [ + { page: '/', functions: [], actors, breg: {} }, + { page: '/', functions: [] }, + { page: '/', functions: [], actors: {} }, + { page: '/', functions: [], actors: { Applicant: {} } }, + { page: '/', functions: [], actors: { applicant: { messaging: {} } } }, + { page: '/', functions: [], actors: { applicant: { coordinator: { get: ['/v1/runs/{runId}/{taskId}'] } } } }, + { page: '/', functions: [], actors: { officer: { casework: { get: ['/v1/review-tasks/{record_id}/{taskId}'] } } } }, + { page: '/', functions: [], actors: { officer: { casework: { get: ['/v1/review-tasks/{taskId}/{revision}/{revision}'] } } } }, + ]) { + assert.throws(() => previewPolicy(invalid), JSON.stringify(invalid)) + } + assert.equal(compileRoutes({ get: ['/v1/review-tasks/{taskId}'] })('GET', '/v1/review-tasks/' + run), true) + // {revision} matches one bounded revision number on any product's route. + const revisions = compileRoutes({ get: ['/v1/runs/{runId}/revisions/{revision}'] }) + assert.equal(revisions('GET', '/v1/runs/' + run + '/revisions/7'), true) + assert.equal(revisions('GET', '/v1/runs/' + run + '/revisions/0'), false) + assert.equal(revisions('GET', '/v1/runs/' + run + '/revisions/9223372036854775808'), false) +}) + +test('a gateway relays each product with its own credential, profile and routes', async (t) => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-products-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Page

') + const seen = [] + const upstream = createServer((request, response) => { + seen.push([request.headers.host.split(':')[1], request.url, request.headers.authorization]) + response.writeHead(200, { 'content-type': 'application/json' }).end('{}') + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => upstream.close(resolve))) + const other = createServer((request, response) => { + seen.push(['other', request.url, request.headers.authorization]) + response.writeHead(403, { 'content-type': 'application/json' }).end('{"code":"profile.not-authorized"}') + }) + await new Promise(resolve => other.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => other.close(resolve))) + const origin = server => 'http://127.0.0.1:' + server.address().port + const gateway = await startPreviewGateway({ + origin: null, port: 0, application: 'http://127.0.0.1:1', publicDirectory: root, + preview: { page: '/', functions: ['assess-permit'], actors: { applicant: {} } }, + actor: 'applicant', + functionAuthorization: () => 'Bearer applicant.breg', + products: { + 'permit-flow': { origin: origin(upstream), profile: null, authorization: () => 'Bearer applicant.coordinator', + allows: compileRoutes({ post: ['/v1/runs'] }) }, + 'permit-review': { origin: origin(other), profile: 'permit-requester', authorization: () => 'Bearer applicant.casework', + allows: compileRoutes({ post: ['/v1/review-tasks/{taskId}/decisions'] }) }, + }, + }) + t.after(() => gateway.close()) + const headers = { origin: gateway.origin, 'registry-client': 'page', 'content-type': 'application/json' } + const post = path => fetch(gateway.origin + path, { method: 'POST', headers, body: '{}' }) + assert.equal((await post('/registry/permit-flow/v1/runs')).status, 200) + assert.equal((await post('/registry/permit-flow/v1/runs?accessProfile=x')).status, 404) + assert.equal((await post('/registry/permit-flow/v1/other')).status, 404) + const task = '00000000-0000-4000-8000-000000000002' + const refused = await post('/registry/permit-review/v1/review-tasks/' + task + '/decisions') + // The owning product's own refusal reaches the page unchanged. + assert.equal(refused.status, 403) + assert.equal((await refused.json()).code, 'profile.not-authorized') + assert.equal((await post('/registry/permit-review/v1/review-tasks/' + task + '/decisions?accessProfile=permit-officer')).status, 403) + assert.equal((await post('/registry/unknown/v1/runs')).status, 404) + // The page learns which actor this origin serves, and nothing else. + const actor = await fetch(gateway.origin + '/_rstack/actor', { headers: { 'registry-client': 'page' } }) + assert.equal(actor.status, 200) + assert.deepEqual(await actor.json(), { actor: 'applicant' }) + assert.equal((await fetch(gateway.origin + '/_rstack/actor')).status, 403) + for (const foreign of [{ origin: 'http://127.0.0.1:1' }, { 'sec-fetch-site': 'cross-site' }]) { + const answer = await fetch(gateway.origin + '/_rstack/actor', { headers: { 'registry-client': 'page', ...foreign } }) + assert.equal(answer.status, 403, JSON.stringify(foreign)) + } + assert.deepEqual(seen.map(([, url, authorization]) => [url, authorization]), [ + ['/v1/runs', 'Bearer applicant.coordinator'], + ['/v1/review-tasks/' + task + '/decisions?accessProfile=permit-requester', 'Bearer applicant.casework'], + ]) +}) + +test('prepare checks each actor origin, product, profile and credential against the plan', async (t) => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-actors-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'service declaration') + const declarationDigest = createHash('sha256').update('service declaration').digest('hex') + const artifact = { + declarationDigest, + product: { id: 'permits', member: 'permits', audience: 'urn:permits', profile: 'permit-applicant' }, + routeProducts: [ + { id: 'casework', kind: 'casework', audience: 'urn:review' }, + { id: 'permit-flow', kind: 'coordinator', audience: 'urn:flow' }, + ], + preview: { page: '/', functions: ['assess-permit'], actors: { + applicant: { breg: { post: ['/v1/actions/submit-application'] }, coordinator: { post: ['/v1/runs'] } }, + officer: { casework: { get: ['/v1/review-tasks'] } }, + } }, + } + const file = name => join(root, name) + const run = { + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits' }, + preview: { + productId: 'permits', profile: 'permit-applicant', declarationDigest, + functionHost: { port: 45678, keyFile: file('key') }, + actors: [ + { name: 'applicant', origin: 'http://127.0.0.1:23456', port: 23456, products: { + permits: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits', profile: 'permit-applicant', authorizationFile: file('a-breg') }, + 'permit-flow': { baseUrl: 'http://127.0.0.1:34568', audience: 'urn:flow', profile: null, authorizationFile: file('a-flow') }, + } }, + { name: 'officer', origin: 'http://127.0.0.1:23457', port: 23457, products: { + permits: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits', profile: 'permit-reader', authorizationFile: file('o-breg') }, + casework: { baseUrl: 'http://127.0.0.1:34569', audience: 'urn:review', profile: 'permit-officer', authorizationFile: file('o-casework') }, + } }, + ], + }, + } + const valid = await prepareRuntimeConfig({ artifact, deployment, run }) + assert.equal(valid.preview.actors.length, 2) + const changed = change => { + const copy = structuredClone(run) + change(copy.preview.actors) + return copy + } + for (const [invalid, message] of [ + [changed(actors => actors.reverse()), /actors differ from the checked plan/u], + [changed(actors => { actors[0].port = 23458; actors[0].origin = 'http://127.0.0.1:23458' }), /first preview actor must serve the run origin/u], + [changed(actors => { actors[1].port = 23456; actors[1].origin = 'http://127.0.0.1:23456' }), /own reserved loopback address/u], + [changed(actors => { actors[1].port = 45678; actors[1].origin = 'http://127.0.0.1:45678' }), /own reserved loopback address/u], + [changed(actors => { delete actors[1].products.casework }), /reaches a product it has no credential for/u], + [changed(actors => { actors[0].products['permit-flow'].profile = 'permit-starter' }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.profile = null }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.audience = 'urn:other' }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.authorizationFile = 'relative' }), /actor product differs from the checked plan/u], + [changed(actors => { actors[1].products.casework.baseUrl = 'http://127.0.0.1:23457' }), /product on the actor's own origin/u], + [changed(actors => { actors[1].products.unknown = actors[1].products.casework }), /product the plan does not route/u], + [{ ...run, preview: { ...run.preview, authorizationFile: file('single') } }, /takes no single authorization file/u], + ]) { + await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: invalid }), message) + } + // The single-actor form takes no actors list. + const single = { ...artifact, preview: { page: '/', functions: [], breg: {} } } + await assert.rejects(prepareRuntimeConfig({ artifact: single, deployment, run }), /single-actor preview takes no actors/u) +}) + +test('configure refuses an actor credential file that is not owner-only or is a link', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-actor-files-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'service declaration') + const declarationDigest = createHash('sha256').update('service declaration').digest('hex') + const artifact = { + declarationDigest, + product: { id: 'permits', member: 'permits', audience: 'urn:permits', profile: 'permit-applicant' }, + routeProducts: [], + preview: { page: '/', functions: [], actors: { applicant: { breg: { get: ['/v1/records/permits'] } } } }, + } + const file = name => join(root, name) + const runFile = file('application-run.json') + await writeFile(runFile, JSON.stringify({ + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits' }, + preview: { + productId: 'permits', profile: 'permit-applicant', declarationDigest, + functionHost: { port: 45678, keyFile: file('key') }, + actors: [{ name: 'applicant', origin: 'http://127.0.0.1:23456', port: 23456, products: { + permits: { baseUrl: 'http://127.0.0.1:34567', audience: 'urn:permits', profile: 'permit-applicant', authorizationFile: file('a-breg') }, + } }], + }, + })) + await writeFile(file('key'), 'synthetic-function-host-key-0123456789abcdefghij\n', { mode: 0o600 }) + await writeFile(file('a-breg'), 'Authorization: Bearer applicant.permits\n', { mode: 0o600 }) + await configure({ artifact, deployment, runFile }) + await chmod(file('a-breg'), 0o640) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) + await rm(file('a-breg')) + await writeFile(file('elsewhere'), 'Authorization: Bearer applicant.permits\n', { mode: 0o600 }) + await symlink(file('elsewhere'), file('a-breg')) + await assert.rejects(configure({ artifact, deployment, runFile }), /owner-only/u) +}) + +test('each actor gateway carries only its own credentials and routes', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-isolation-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Page

') + const seen = [] + const upstream = createServer((request, response) => { + seen.push([request.url, request.headers.authorization]) + response.writeHead(200, { 'content-type': 'application/json' }).end('{}') + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => upstream.close(resolve))) + const base = 'http://127.0.0.1:' + upstream.address().port + const artifact = { + product: { id: 'permits', audience: 'urn:permits', profile: 'permit-applicant' }, + routeProducts: [ + { id: 'casework', kind: 'casework', audience: 'urn:review' }, + { id: 'permit-flow', kind: 'coordinator', audience: 'urn:flow' }, + ], + preview: { page: '/', functions: ['assess-permit'], actors: { + applicant: { breg: { post: ['/v1/actions/submit-application'] }, coordinator: { post: ['/v1/runs'] } }, + officer: { casework: { get: ['/v1/review-tasks'] } }, + } }, + } + const credential = async (name, id) => { + const path = join(root, name + '-' + id) + await writeFile(path, 'Authorization: Bearer ' + name + '.' + id + '\n', { mode: 0o600 }) + return path + } + const product = async (name, id, profile) => ({ baseUrl: base, audience: 'urn:' + id, profile, authorizationFile: await credential(name, id) }) + const actors = [ + { name: 'applicant', origin: null, port: 0, products: { + permits: await product('applicant', 'permits', 'permit-applicant'), + 'permit-flow': await product('applicant', 'permit-flow', null), + } }, + { name: 'officer', origin: null, port: 0, products: { + permits: await product('officer', 'permits', 'permit-reader'), + casework: await product('officer', 'casework', 'permit-officer'), + } }, + ] + const options = actorGatewayOptions(artifact, actors) + assert.deepEqual(options.map(option => option.actor), ['applicant', 'officer']) + const gateways = {} + for (const option of options) { + gateways[option.actor] = await startPreviewGateway({ + ...option, application: base, publicDirectory: root, preview: artifact.preview, functionKey: 'k'.repeat(32), + }) + t.after(() => gateways[option.actor].close()) + } + const call = async (name, method, path) => { + const gateway = gateways[name] + const response = await fetch(gateway.origin + path, { + method, headers: { origin: gateway.origin, 'registry-client': 'page', 'content-type': 'application/json' }, + body: method === 'POST' ? '{}' : undefined, + }) + return response.status + } + assert.equal(await call('applicant', 'POST', '/registry/permits/v1/actions/submit-application'), 200) + assert.equal(await call('applicant', 'POST', '/registry/permit-flow/v1/runs'), 200) + assert.equal(await call('applicant', 'GET', '/registry/casework/v1/review-tasks'), 404) + assert.equal(await call('applicant', 'POST', '/api/functions/assess-permit'), 200) + assert.equal(await call('officer', 'GET', '/registry/casework/v1/review-tasks'), 200) + assert.equal(await call('officer', 'POST', '/registry/permit-flow/v1/runs'), 404) + assert.equal(await call('officer', 'POST', '/registry/permits/v1/actions/submit-application'), 404) + assert.equal(await call('officer', 'POST', '/api/functions/assess-permit'), 200) + assert.deepEqual(seen, [ + ['/v1/actions/submit-application?accessProfile=permit-applicant', 'Bearer applicant.permits'], + ['/v1/runs', 'Bearer applicant.permit-flow'], + ['/functions/assess-permit', 'Bearer applicant.permits'], + ['/v1/review-tasks?accessProfile=permit-officer', 'Bearer officer.casework'], + ['/functions/assess-permit', 'Bearer officer.permits'], + ]) +}) + +test('a gateway without a function credential serves no function route', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-nofunction-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Page

') + const gateway = await startPreviewGateway({ + origin: null, port: 0, application: 'http://127.0.0.1:1', publicDirectory: root, + preview: { page: '/', functions: ['assess-permit'], actors: { officer: {} } }, + actor: 'officer', functionAuthorization: null, + products: { casework: { origin: 'http://127.0.0.1:2', profile: 'permit-officer', + authorization: () => 'Bearer officer.casework', allows: compileRoutes({}) } }, + }) + t.after(() => gateway.close()) + const answer = await fetch(gateway.origin + '/api/functions/assess-permit', { + method: 'POST', headers: { origin: gateway.origin, 'registry-client': 'page', 'content-type': 'application/json' }, body: '{}', + }) + assert.equal(answer.status, 404) +}) + +test('an actors preview names no Proposal author and refuses a register with Proposals', () => { + const product = { id: 'permits', member: 'permits', project: '/project', profile: 'permit-applicant' } + const single = generatorArguments({ product, preview: { functions: ['assess-permit'] } }, '/staged') + assert.deepEqual(single.slice(single.indexOf('--author-profile'), single.indexOf('--author-profile') + 2), + ['--author-profile', 'permits=permit-applicant']) + const actors = generatorArguments({ product, preview: { functions: ['assess-permit'], actors: { applicant: {} } } }, '/staged') + assert.equal(actors.includes('--author-profile'), false) + const proposals = generationError('The register permits has Proposals, so the service description needs authorProfiles.', true).message + // The generator's own diagnostic comes first, then the preview's hint. + assert.ok(proposals.startsWith('The register permits has Proposals'), proposals) + assert.match(proposals, /\nAn actors preview cannot start Proposals/u) + assert.match(generationError('The authorProfile "x" cannot start Proposals in permits.', false).message, + /Select a preview actor whose BReg profile can start Proposals/u) + assert.equal(generationError('generator diagnostic', true).message, 'generator diagnostic') + assert.match(generationError('', true).message, /Preview client generation failed/u) +}) diff --git a/clients/typescript/tests/generate-preview.test.ts b/clients/typescript/tests/generate-preview.test.ts index 69a74ca1fb..e9c19f0cc0 100644 --- a/clients/typescript/tests/generate-preview.test.ts +++ b/clients/typescript/tests/generate-preview.test.ts @@ -10,7 +10,7 @@ const root = fileURLToPath(new URL('../', import.meta.url)) const fixture = fileURLToPath(new URL('./fixtures/breg-list.openapi.json', import.meta.url)) const { name, version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name: string; version: string } -test('preview generation splits page and function bindings and scopes credentials to each request', t => { +test('preview generation splits page and function bindings and keeps request credentials out of handlers', t => { const dir = mkdtempSync(join(tmpdir(), 'registry-preview-generator-')) t.after(() => rmSync(dir, { recursive: true, force: true })) const compiler = join(dir, 'bregctl') @@ -43,6 +43,9 @@ test('preview generation splits page and function bindings and scopes credential const refused = generateFrom(facility, '--author-profile', 'licences=facility-reader') assert.equal(refused.status, 1) assert.match(refused.stderr, /cannot start Proposals/u) + const unnamed = generateFrom(facility) + assert.equal(unnamed.status, 1) + assert.match(unnamed.stderr, /has Proposals, so the service description needs authorProfiles/u) const duplicate = generate('--preview-function', 'renew', '--preview-function', 'renew') assert.equal(duplicate.status, 1) assert.match(duplicate.stderr, /duplicate preview function/iu) @@ -66,12 +69,15 @@ test('preview generation splits page and function bindings and scopes credential '--outDir', compiled, join(generated, 'service.ts'), join(generated, 'server.ts'), join(generated, 'routes.ts')], { encoding: 'utf8' }) assert.equal(types.status, 0, types.stdout + types.stderr) - const run = spawnSync(process.execPath, ['--input-type=module', '-', compiled], { encoding: 'utf8', input: ` + const host = join(root, 'preview', 'host.mjs') + const run = spawnSync(process.execPath, ['--input-type=module', '-', compiled, host], { encoding: 'utf8', input: ` import assert from 'node:assert/strict' import { pathToFileURL } from 'node:url' const generated = pathToFileURL(process.argv[2] + '/') +const { coordinatorBearer, functionHostAuthorizer, startFunctionHost } = await import(pathToFileURL(process.argv[3])) globalThis.location = { origin: 'http://127.0.0.1:12345' } const calls = [] +const networkFetch = globalThis.fetch globalThis.fetch = async (url, init) => { calls.push([String(url), new Headers(init.headers)]) return Response.json({ items: [], pageInfo: { nextCursor: null } }) @@ -83,22 +89,46 @@ await createRegistryClient().licences.list('licence', options) assert.equal(new URL(calls[0][0]).pathname, '/registry/licence-registry/v1/records/licences') assert.equal(calls[0][1].get('authorization'), null) assert.equal(calls[0][1].get('registry-client'), 'page') +const handled = new Map() +let completeAdmission +const bothAdmitted = new Promise(resolve => { completeAdmission = resolve }) const bind = defineFunction(async (request, licences) => { const profile = new URL(request.url).searchParams.get('profile') + assert.ok(!request.headers.has('authorization'), 'function handlers receive no Authorization header') + assert.equal(request.headers.get('cookie'), null) + assert.equal(request.headers.get('proxy-authorization'), null) + assert.equal(request.method, 'POST') + assert.equal(request.headers.get('content-type'), 'application/json') + assert.deepEqual(await request.json(), { profile }) + handled.set(profile, request.signal) + if (handled.size === 2) completeAdmission() + await bothAdmitted await licences.list('licence', profile === 'licence-holder' ? options : { accessProfile: 'licence-officer' }) return new Response(null, { status: 204 }) }) assert.throws(() => bind({ products: { licences: { baseUrl: 'http://127.0.0.1:54321' } } }), /Missing prepared BReg connection/) const handler = bind({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54321' } } }) -const request = (profile, credential) => new Request('http://127.0.0.1:6789/?profile=' + profile, - credential ? { headers: { authorization: 'Bearer ' + credential } } : {}) +const request = (profile, credential, signal) => { + const headers = { 'content-type': 'application/json', cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=' } + if (credential) headers.Authorization = 'Bearer ' + credential + return new Request('http://127.0.0.1:6789/?profile=' + profile, + { headers, method: 'POST', body: JSON.stringify({ profile }), signal }) +} assert.equal((await handler(request('licence-holder'))).status, 401) assert.equal((await handler(request('licence-holder', 'a,b'))).status, 401) assert.equal(calls.length, 1) +const holder = new AbortController() +const officer = new AbortController() +const holderRequest = request('licence-holder', 'synthetic-holder', holder.signal) +const officerRequest = request('licence-officer', 'synthetic-officer', officer.signal) await Promise.all([ - handler(request('licence-holder', 'synthetic-holder')), - handler(request('licence-officer', 'synthetic-officer')), + handler(holderRequest), + handler(officerRequest), ]) +assert.ok(holderRequest.headers.has('authorization') && officerRequest.headers.has('authorization')) +holder.abort() +assert.ok(handled.get('licence-holder').aborted) +assert.ok(!handled.get('licence-officer').aborted) assert.deepEqual(calls.slice(1).map(([url, headers]) => { const target = new URL(url) return [target.origin + target.pathname, target.searchParams.get('accessProfile'), headers.get('authorization')] @@ -106,6 +136,83 @@ assert.deepEqual(calls.slice(1).map(([url, headers]) => { ['http://127.0.0.1:54321/v1/records/licences', 'licence-holder', 'Bearer synthetic-holder'], ['http://127.0.0.1:54321/v1/records/licences', 'licence-officer', 'Bearer synthetic-officer'], ]) + +// The same binding behind the real private function host, as a preview runs it. +const hosted = [] +let hostedAdmission +const bothHosted = new Promise(resolve => { hostedAdmission = resolve }) +const hostedHandler = defineFunction(async (request, licences) => { + const profile = new URL(request.url).searchParams.get('profile') + hosted.push([profile, request.method, request.headers.has('authorization'), request.headers.get('cookie'), + request.headers.get('proxy-authorization'), request.runtime, request.headers.get('content-type'), + request.headers.get('idempotency-key'), await request.json()]) + if (hosted.length === 2) hostedAdmission() + await bothHosted + await licences.list('licence', profile === 'licence-holder' ? options : { accessProfile: 'licence-officer' }) + return new Response(null, { status: 204 }) +})({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54322' } } }) +const functionKey = 'synthetic-function-key' +const server = await startFunctionHost(new Map([['renew', hostedHandler]]), { + authorize: request => request.headers.get('x-registry-preview-function') === functionKey, +}) +try { + const post = (profile, credential) => networkFetch(server.origin + '/functions/renew?profile=' + profile, { + method: 'POST', body: JSON.stringify({ profile }), + headers: { + authorization: 'Bearer ' + credential, 'x-registry-preview-function': functionKey, + 'content-type': 'application/json', 'idempotency-key': 'key-' + profile, + cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=', + }, + }) + const statuses = await Promise.all([post('licence-holder', 'hosted-holder'), post('licence-officer', 'hosted-officer')]) + assert.deepEqual(statuses.map(response => response.status), [204, 204]) +} finally { + await server.close() +} +assert.deepEqual(hosted.sort(), [ + ['licence-holder', 'POST', false, null, null, undefined, 'application/json', 'key-licence-holder', { profile: 'licence-holder' }], + ['licence-officer', 'POST', false, null, null, undefined, 'application/json', 'key-licence-officer', { profile: 'licence-officer' }], +]) +assert.deepEqual(calls.slice(3).map(([url, headers]) => { + const target = new URL(url) + return [target.origin + target.pathname, target.searchParams.get('accessProfile'), headers.get('authorization')] +}).sort(), [ + ['http://127.0.0.1:54322/v1/records/licences', 'licence-holder', 'Bearer hosted-holder'], + ['http://127.0.0.1:54322/v1/records/licences', 'licence-officer', 'Bearer hosted-officer'], +]) + +// A Coordinator call presents the run host key as its bearer. The host admits +// it and hands the binding a fixed non-secret placeholder instead, so the key +// never leaves the host and the registry refuses the placeholder. +const hostKey = 'synthetic-run-function-host-key-0123456789' +const coordinatorHosted = [] +const coordinatorHandler = defineFunction(async (request, licences) => { + coordinatorHosted.push([request.headers.has('authorization'), request.headers.get('cookie'), + request.headers.get('proxy-authorization'), request.headers.get('idempotency-key')]) + await licences.list('licence', { accessProfile: 'licence-officer' }) + return new Response(null, { status: 204 }) +})({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54323' } } }) +const coordinatorHost = await startFunctionHost(new Map([['renew', coordinatorHandler]]), { + authorize: functionHostAuthorizer(hostKey), +}) +const before = calls.length +try { + const response = await networkFetch(coordinatorHost.origin + '/functions/renew', { + method: 'POST', body: '{}', + headers: { + authorization: 'Bearer ' + hostKey, 'content-type': 'application/json', 'idempotency-key': 'frozen-key', + cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=', + }, + }) + assert.equal(response.status, 204) +} finally { + await coordinatorHost.close() +} +assert.deepEqual(coordinatorHosted, [[false, null, null, 'frozen-key']]) +const upstream = calls.slice(before) +assert.equal(upstream.length, 1) +assert.equal(upstream[0][1].get('authorization'), coordinatorBearer) +assert.ok(!JSON.stringify(upstream.map(([url, headers]) => [url, [...headers]])).includes(hostKey)) ` }) assert.equal(run.status, 0, run.stderr) }) diff --git a/clients/typescript/tests/generator.test.ts b/clients/typescript/tests/generator.test.ts index f0ad4982b7..3d8798023a 100644 --- a/clients/typescript/tests/generator.test.ts +++ b/clients/typescript/tests/generator.test.ts @@ -26,6 +26,58 @@ test('BReg refuses paths outside the route scheme', () => { const input = { ...document({ type: 'string' }), paths: { '/v1/foreign': {} } } assert.throws(() => generate(JSON.stringify(input), { breg: true }), /\/paths\/~1v1~1foreign/) }) +test('BReg generates a typed call for Record revision reads', () => { + const path = '/v1/records/applications/{record_id}/revisions/{revision}' + const input = { ...document({ type: 'string' }), paths: { [path]: { get: { + operationId: 'readApplicationRevision', + parameters: [ + { in: 'path', name: 'record_id', required: true, schema: { type: 'string', format: 'uuid' } }, + { in: 'path', name: 'revision', required: true, schema: { type: 'integer', minimum: 1 } }, + ], + responses: { 200: { description: 'ok', content: { 'application/json': { schema: { type: 'string' } } } } }, + } } } } + const output = generate(JSON.stringify(input), { breg: true }) + assert.match(output, /"readApplicationRevision": \{ input:.*"record_id": \(string\); "revision": \(number\)/u) + assert.ok(output.includes(path)) + const unsupported = { ...input, paths: { [path.replace('{revision}', '{other}')]: input.paths[path] } } + assert.throws(() => generate(JSON.stringify(unsupported), { breg: true }), /outside BReg route scheme/u) +}) +test('BReg accepts the route families emitted by the native fixture set', () => { + for (const path of [ + '/v1/statistics/entry-counts/releases/{period}/versions', + '/v1/external-refresh-plans/{plan}/source-changes', + '/v1/external-views/licence-holder-indexed/holder/records', + '/v1/external-views/licence-holder-indexed/holder/records/{root}', + '/v1/external-views/licence-holder-indexed/holder/records/{root}/refresh', + '/v1/proposals/{proposal_id}/additions/supporting', + '/v1/proposals/{proposal_id}/additions/{addition_id}', + '/v1/proposals/{proposal_id}/asks/{ask_id}/answer', + ]) assert.doesNotThrow(() => generate(JSON.stringify({ ...document({ type: 'string' }), paths: { [path]: {} } }), { breg: true }), path) +}) + +test('BReg generates a CSV alternative on statistical releases', () => { + const path = '/v1/statistics/entry-counts/releases/{period}' + const operation = { operationId: 'publishedRelease', parameters: [ + { in: 'path', name: 'period', required: true, schema: { type: 'string' } }, + ], responses: { 200: { description: 'ok', content: { 'text/csv': { schema: { type: 'string' } } } } } } + const input = { ...document({ type: 'string' }), paths: { [path]: { get: operation } } } + assert.match(generate(JSON.stringify(input), { breg: true }), /WireText<"text\/csv">/u) + const nonStatistic = { ...input, paths: { '/v1/records/entries': { get: { ...operation, parameters: [] } } } } + assert.throws(() => generate(JSON.stringify(nonStatistic), { breg: true }), /unsupported success media/u) +}) + +test('BReg generates only the native batch patch value as unconstrained JSON', () => { + const batchPatch = (field: string) => ({ type: 'object', properties: { items: { type: 'array', items: { oneOf: [ + { type: 'string', const: 'other' }, + { type: 'object', properties: { patch: { type: 'array', items: { type: 'object', properties: { [field]: true } } } } }, + ] } } } }) + const input = (field: string) => ({ ...document({ type: 'string' }), paths: { + '/v1/records/entries:batch': { post: { operationId: 'batchEntries', responses: success, + requestBody: { content: { 'application/json': { schema: batchPatch(field) } } } } }, + } }) + assert.ok(generate(JSON.stringify(input('value')), { breg: true }).includes('// Unconstrained JSON ')) + assert.throws(() => generate(JSON.stringify(input('extra')), { breg: true }), /outside the reviewed allowlist/u) +}) test('a generated module exports its Client over a Transport and no factory', () => { const output = generate(JSON.stringify({ ...document({ type: 'string' }), info: { title: 'licence-registry' } })) assert.match(output, /^export class Client \{$/mu) diff --git a/clients/typescript/tests/holder-function-create.test.ts b/clients/typescript/tests/holder-function-create.test.ts new file mode 100644 index 0000000000..e081728f36 --- /dev/null +++ b/clients/typescript/tests/holder-function-create.test.ts @@ -0,0 +1,519 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { RegistryError, Transport, type CallOptions, type Operation } from '../core.ts' +import { createHolderActionHandler } from '../holder-function.ts' + +// A create-shaped holder binding: the Action makes one new Record, so the +// submission names no target and no condition. Neither the page nor the +// function can name the new Record's owner. As in the real register-business +// plan, BReg plans the owning office itself and refuses a create outside the +// caller's office through the Action target's row boundary. +const route = '/api/functions/register-business' +const attemptId = '6c0e4c3d-1d0b-4c55-9d43-4ad2a3b3a1f7' +const registrarAuthorization = 'Bearer synthetic-registrar' +const traceId = '33333333333333333333333333333333' +const traceparent = `00-${traceId}-4444444444444444-01` +const submission = { legalName: ' Harbour Bicycle Cooperative ', registrationNumber: 'br-2026-001' } +const prepared = { legalName: 'Harbour Bicycle Cooperative', registrationNumber: 'BR-2026-001' } +const registrar = { subject: 'registrar-a', office: 'central', actor: 'human', client: 'business-registrar', + profile: 'business-registrar', audience: 'businesses' } +const identities = new Map([ + [registrarAuthorization, registrar], + ['Bearer synthetic-registrar-renewed', registrar], + ['Bearer synthetic-reader', { ...registrar, profile: 'business-status' }], + ['Bearer synthetic-other-audience', { ...registrar, audience: 'other' }], + ['Bearer synthetic-north-registrar', { ...registrar, subject: 'registrar-north', office: 'north' }], +]) +// The office register-business plans for every new business Record. +const plannedOffice = 'central' + +const registration: Operation = { + method: 'POST', path: '/v1/actions/register-business', product: 'breg', + accessProfileParameter: true, accessProfileRequired: true, + keyed: true, mutating: true, requestMediaType: 'application/json', + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status', 'title', 'traceId', 'type']) }, + responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, +} + +type RegistrationInput = { legalName: string; registrationNumber: string } +type RegistrationReceipt = { results: { business?: { recordId: string; revision: number } } } + +function exactObject(value: unknown, keys: readonly string[]): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) +} + +// Host-owned: the page sends only the two business fields. +function parseSubmission(value: unknown) { + if (!exactObject(value, ['legalName', 'registrationNumber']) || + typeof value.legalName !== 'string' || typeof value.registrationNumber !== 'string') return undefined + return { preparation: { legalName: value.legalName, registrationNumber: value.registrationNumber } } +} + +// Host-owned: the function may return only the Action's two inputs. +function parsePreparation(value: unknown) { + if (!exactObject(value, ['legalName', 'registrationNumber']) || + typeof value.legalName !== 'string' || typeof value.registrationNumber !== 'string') return undefined + return { legalName: value.legalName, registrationNumber: value.registrationNumber } +} + +// The declared function: a pure normalisation of what the page submitted. +function prepareRegistration({ legalName, registrationNumber }: RegistrationInput) { + return { legalName: legalName.trim(), registrationNumber: registrationNumber.trim().toUpperCase() } +} + +function request(options: { path?: string; method?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { + const { path = route, method = 'POST', authorization = registrarAuthorization, body = submission, key = attemptId, signal } = options + const headers = new Headers({ + 'Content-Type': 'application/json', 'Idempotency-Key': key, + 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', + }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { + method, headers, body: method === 'GET' ? undefined : JSON.stringify(body), signal, + }) +} + +function setup(prepare: (input: RegistrationInput) => unknown = prepareRegistration, + { loseFirstReceipt = false, receiptRevision = 1, omitReceipt = false, replayProblem, preparationTimeoutMs = 1000, + receiptRecordId, parse = parseSubmission, answer }: { + answer?: (signal: AbortSignal | null | undefined) => Response | Promise + loseFirstReceipt?: boolean; receiptRevision?: number; omitReceipt?: boolean; preparationTimeoutMs?: number + replayProblem?: 'idempotency.key-reused' | 'idempotency.expired'; receiptRecordId?: string + parse?: (value: unknown) => { preparation: RegistrationInput } | undefined + } = {}, +) { + const preparations: unknown[][] = [] + const preparationSignals: AbortSignal[] = [] + const invokeSignals: AbortSignal[] = [] + const calls: { url: string; headers: Record; body: unknown }[] = [] + // Each new Record and the owner BReg derived for it from the verified caller. + const records = new Map() + const committed = new Map() + let next = 0 + + const fetchProduct: typeof fetch = async (target, options) => { + const url = new URL(String(target)) + const headers = new Headers(options?.headers) + const body = JSON.parse(String(options?.body)) + calls.push({ url: url.href, headers: Object.fromEntries(headers), body }) + if (answer) return answer(options?.signal) + if (url.pathname !== registration.path || options?.method !== 'POST' || + url.searchParams.get('accessProfile') !== 'business-registrar') { + throw new Error('The caller changed the checked Action contract.') + } + const refuse = (status: number, code: string) => Response.json({ + status, code, detail: 'product-only detail', title: 'BReg refused the request.', traceId, + type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), + }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) + const receipt = (recordId: string) => Response.json({ action: 'register-business', applicationId: attemptId, + results: omitReceipt ? {} : { business: { recordId: receiptRecordId ?? recordId, recordType: 'business', revision: receiptRevision } }, + }, { headers: { 'Cache-Control': 'no-store', traceparent } }) + const identity = identities.get(headers.get('authorization') ?? '') + if (!identity || identity.audience !== 'businesses') return refuse(401, 'authentication.refused') + if (identity.profile !== 'business-registrar') return refuse(403, 'profile.not-authorized') + if (!exactObject(body, ['input']) || !exactObject(body.input, ['legalName', 'registrationNumber'])) { + return refuse(400, 'request.invalid') + } + const receiptKey = identity.subject + ':' + headers.get('idempotency-key') + const command = JSON.stringify(body) + const earlier = committed.get(receiptKey) + if (earlier) { + if (replayProblem) return refuse(replayProblem === 'idempotency.expired' ? 410 : 409, replayProblem) + if (earlier.command !== command) return refuse(409, 'idempotency.key-reused') + return receipt(earlier.recordId) + } + // The plan fixes the office. Natively, the row policy's check on the Action target's row + // boundary refuses the insert for a caller from another office with 412 precondition.failed. + if (identity.office !== plannedOffice) return refuse(412, 'precondition.failed') + const recordId = `00000000-0000-4000-8000-${String(++next).padStart(12, '0')}` + committed.set(receiptKey, { command, recordId }) + records.set(recordId, { + owner: plannedOffice, + input: { legalName: String(body.input.legalName), registrationNumber: String(body.input.registrationNumber) }, + }) + if (loseFirstReceipt && calls.length === 1) { + throw new Error('Simulated lost product receipt') + } + return receipt(recordId) + } + + const handle = createHolderActionHandler({ + kind: 'create', + path: route, + preparationTimeoutMs, + parseSubmission: parse, + parsePreparation, + async invoke(credential, { input, idempotencyKey, signal }) { + invokeSignals.push(signal) + const transport = new Transport({ baseUrl: 'https://businesses.test', token: () => credential, fetch: fetchProduct }) + const { data } = await transport.call(registration, { + idempotencyKey, signal, query: { accessProfile: 'business-registrar' }, body: { input }, + } as CallOptions & { query: Record; body: unknown }) + const business = data.results.business + if (!business) throw new Error('BReg returned no business receipt.') + return { recordId: business.recordId, revision: business.revision } + }, + }, (value, options) => { + preparations.push([value]) + preparationSignals.push(options.signal) + return prepare(value) + }) + return { handle, preparations, preparationSignals, invokeSignals, calls, records } +} + +test('a create binding prepares the projected value and invokes the Action with no target or condition', async () => { + const { handle, preparations, calls, records } = setup() + const result = await handle(request()) + assert.equal(result.status, 200) + const { recordId } = await result.json() as { recordId: string } + assert.deepEqual(preparations, [[submission]]) + assert.equal(calls.length, 1) + const call = calls[0]! + assert.equal(call.url, 'https://businesses.test/v1/actions/register-business?accessProfile=business-registrar') + assert.equal(call.headers.authorization, registrarAuthorization) + assert.equal(call.headers['idempotency-key'], attemptId) + for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) + assert.deepEqual(call.body, { input: prepared }) + assert.deepEqual([...records], [[recordId, { owner: 'central', input: prepared }]]) +}) + +test('neither the page nor the function can name the owner of a created Record', async () => { + // A page that names an owner is refused before preparation. + const named = setup() + const refused = await named.handle(request({ body: { ...submission, registeringOffice: 'north' } })) + assert.equal(refused.status, 400) + assert.equal(named.preparations.length, 0) + assert.equal(named.calls.length, 0) + + // A function that hard-codes an owner or a record ID cannot reach BReg. + for (const extra of [{ registeringOffice: 'north' }, { recordId: '00000000-0000-4000-8000-000000000999' }]) { + const hardCoded = setup(input => ({ ...prepareRegistration(input), ...extra })) + const answer = await hardCoded.handle(request()) + assert.equal(answer.status, 502, JSON.stringify(extra)) + assert.equal(hardCoded.calls.length, 0, JSON.stringify(extra)) + assert.equal(hardCoded.records.size, 0, JSON.stringify(extra)) + } +}) + +test('a create binding refuses a request outside the declared binding before preparation or BReg', async () => { + for (const options of [ + { path: '/api/functions/other' }, { path: route + '?accessProfile=admin' }, { method: 'PUT' }, + { authorization: null }, { authorization: 'Basic synthetic' }, { key: 'not-a-key' }, + { body: { legalName: 'Only a name' } }, { body: [submission] }, + ]) { + const { handle, preparations, calls } = setup() + const answer = await handle(request(options)) + assert.ok(answer.status >= 400 && answer.status < 500, `${JSON.stringify(options)}: ${answer.status}`) + assert.equal(preparations.length, 0, JSON.stringify(options)) + assert.equal(calls.length, 0, JSON.stringify(options)) + } +}) + +test('a create binding answers only for one new Record', async () => { + // An existing Record's revision, or no Record, leaves the attempt unresolved. + for (const options of [{ receiptRevision: 2 }, { omitReceipt: true }]) { + const { handle } = setup(prepareRegistration, options) + const answer = await handle(request()) + assert.equal(answer.status, 502, JSON.stringify(options)) + assert.equal((await answer.json() as { code: string }).code, 'holder-action.outcome-unresolved') + } +}) + +test('a create binding retry after a lost receipt returns the same new Record once', async () => { + const { handle, calls, records } = setup(prepareRegistration, { loseFirstReceipt: true }) + const first = await handle(request()) + assert.equal(first.status, 502) + assert.equal((await first.json() as { code: string }).code, 'holder-action.outcome-unresolved') + const retried = await handle(request({ authorization: 'Bearer synthetic-registrar-renewed' })) + assert.equal(retried.status, 200) + const { recordId } = await retried.json() as { recordId: string } + assert.deepEqual([...records.keys()], [recordId]) + assert.equal(calls.length, 2) + assert.deepEqual(calls[1]!.body, calls[0]!.body) + assert.equal(calls[1]!.headers['idempotency-key'], calls[0]!.headers['idempotency-key']) +}) + +test('a create binding keeps a spent key unresolved', async () => { + for (const replayProblem of ['idempotency.key-reused', 'idempotency.expired'] as const) { + const { handle, records } = setup(prepareRegistration, { replayProblem }) + assert.equal((await handle(request())).status, 200) + const replay = await handle(request()) + assert.equal(replay.status, replayProblem === 'idempotency.expired' ? 410 : 409) + assert.equal((await replay.json() as { code: string }).code, 'holder-action.outcome-unresolved') + assert.equal(records.size, 1) + } +}) + +test('a create binding product refusal stays a refusal', async () => { + for (const [authorization, status] of [ + ['Bearer synthetic-reader', 403], ['Bearer synthetic-other-audience', 401], + // A registrar outside the planned office: the Action target's row boundary refuses it. + ['Bearer synthetic-north-registrar', 412], + ] as const) { + const { handle, records } = setup() + const answer = await handle(request({ authorization })) + assert.equal(answer.status, status) + assert.equal(records.size, 0) + } +}) + +test('cancellation before or during a create preparation makes no Action call', { timeout: 3000 }, async () => { + const early = setup() + const aborted = new AbortController() + aborted.abort() + assert.equal((await early.handle(request({ signal: aborted.signal }))).status, 502) + assert.equal(early.preparations.length, 0) + assert.equal(early.calls.length, 0) + + let release!: (value: unknown) => void + const pending = setup(() => new Promise(resolve => { release = resolve })) + const during = new AbortController() + const answer = pending.handle(request({ signal: during.signal })) + while (pending.preparations.length === 0) await new Promise(resolve => setImmediate(resolve)) + during.abort() + assert.equal((await answer).status, 502) + release(prepared) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(pending.calls.length, 0) + assert.equal(pending.records.size, 0) +}) + +test('a binding names its kind, and a target binding still needs its target and condition', () => { + const common = { + path: route, preparationTimeoutMs: 1000, parseSubmission, parsePreparation, + async invoke() { return { recordId: '00000000-0000-4000-8000-000000000001', revision: 1 } }, + } + for (const kind of [undefined, 'update', 'Create']) { + assert.throws(() => createHolderActionHandler({ ...common, kind } as never, prepareRegistration), + /Expected a target or create holder binding/u, String(kind)) + } +}) + +test('a target binding refuses a submission without its target and condition', async () => { + let invoked = 0 + const handle = createHolderActionHandler({ + kind: 'target', path: route, preparationTimeoutMs: 1000, parsePreparation, + // A target parser that drops the target: the handler must still refuse. + parseSubmission: value => parseSubmission(value) as never, + async invoke() { + invoked += 1 + return { recordId: '00000000-0000-4000-8000-000000000001' } + }, + }, prepareRegistration) + const answer = await handle(request()) + assert.equal(answer.status, 400) + assert.equal(invoked, 0) +}) + +test('keeping the attempt key through a refused retry leaves one Record', async () => { + // A lost receipt leaves the attempt unresolved. A retry with an expired credential is an + // ordinary refusal, which the handler cannot tell apart statelessly. A page that keeps the + // original key and body, as the binding documents, still ends with one Record. + const { handle, records } = setup(prepareRegistration, { loseFirstReceipt: true }) + assert.equal((await handle(request())).status, 502) + assert.equal((await handle(request({ authorization: 'Bearer synthetic-expired' }))).status, 401) + const retried = await handle(request({ authorization: 'Bearer synthetic-registrar-renewed' })) + assert.equal(retried.status, 200) + assert.deepEqual([...records.keys()], [(await retried.json() as { recordId: string }).recordId]) +}) + +test('a create receipt naming a record that is not a UUID leaves the attempt unresolved', async () => { + const { handle } = setup(prepareRegistration, { receiptRecordId: 'not-a-record' }) + const answer = await handle(request()) + assert.equal(answer.status, 502) + assert.equal((await answer.json() as { code: string }).code, 'holder-action.outcome-unresolved') +}) + +test('a synchronous preparation that overruns its deadline makes no Action call', async () => { + const { handle, calls } = setup(input => { + const until = performance.now() + 40 + while (performance.now() < until) { /* busy */ } + return prepareRegistration(input) + }, { preparationTimeoutMs: 10 }) + assert.equal((await handle(request())).status, 502) + assert.equal(calls.length, 0) +}) + +test('the preparation signal aborts at the deadline', { timeout: 3000 }, async () => { + let observed: AbortSignal | undefined + let invoked = 0 + const slow = createHolderActionHandler({ + kind: 'create', path: route, preparationTimeoutMs: 20, parseSubmission, parsePreparation, + async invoke() { + invoked += 1 + return { recordId: '00000000-0000-4000-8000-000000000001', revision: 1 } + }, + }, async (value, { signal }) => { + observed = signal + await new Promise(resolve => setTimeout(resolve, 80)) + return prepareRegistration(value) + }) + assert.equal((await slow(request())).status, 502) + assert.equal(observed?.aborted, true) + assert.equal(invoked, 0) +}) + +test('the preparation deadline removes its timer and abort listener', async () => { + const controller = new AbortController() + const signal = controller.signal + let added = 0 + let removed = 0 + const addEventListener = signal.addEventListener.bind(signal) + const removeEventListener = signal.removeEventListener.bind(signal) + signal.addEventListener = ((...args: Parameters) => { + if (args[0] === 'abort') added += 1 + return addEventListener(...args) + }) as typeof signal.addEventListener + signal.removeEventListener = ((...args: Parameters) => { + if (args[0] === 'abort') removed += 1 + return removeEventListener(...args) + }) as typeof signal.removeEventListener + const { handle } = setup(prepareRegistration, { preparationTimeoutMs: 600_000 }) + // Count the timers the handler starts and clears, so a leaked timer fails here. + const started = new Set() + const realSetTimeout = globalThis.setTimeout + const realClearTimeout = globalThis.clearTimeout + globalThis.setTimeout = ((...args: Parameters) => { + const timer = realSetTimeout(...args) + if (args[1] === 600_000) started.add(timer) + return timer + }) as typeof setTimeout + globalThis.clearTimeout = ((timer?: Parameters[0]) => { + started.delete(timer) + return realClearTimeout(timer) + }) as typeof clearTimeout + // The handler reads the caller's signal from the Request; hand it the spied one. + class SpiedRequest extends Request { + override get signal() { return signal } + } + let answer: Response + try { + answer = await handle(new SpiedRequest(request())) + } finally { + globalThis.setTimeout = realSetTimeout + globalThis.clearTimeout = realClearTimeout + } + // Clear any leaked timer before asserting, so a leak fails the test instead of hanging it. + const leaked = started.size + for (const timer of started) realClearTimeout(timer as Parameters[0]) + assert.equal(answer.status, 200) + assert.ok(added >= 1) + assert.equal(removed, added) + assert.equal(leaked, 0, 'a deadline timer was left running') +}) + +test('a create preparation receives the host projection, not the raw body', async () => { + // A host parser that admits a note the function does not need, and drops it. + const parse = (value: unknown) => { + if (!exactObject(value, ['legalName', 'registrationNumber', 'note']) || + typeof value.legalName !== 'string' || typeof value.registrationNumber !== 'string') return undefined + return { preparation: { legalName: value.legalName, registrationNumber: value.registrationNumber } } + } + const { handle, preparations } = setup(prepareRegistration, { parse }) + assert.equal((await handle(request({ body: { ...submission, note: 'not for the function' } }))).status, 200) + assert.deepEqual(preparations, [[submission]]) +}) + +test('the caller signal reaches the Action call and the preparation', async () => { + const controller = new AbortController() + const { handle, invokeSignals, preparationSignals } = setup() + assert.equal((await handle(request({ signal: controller.signal }))).status, 200) + assert.equal(invokeSignals.length, 1) + assert.equal(preparationSignals.length, 1) + controller.abort() + assert.equal(invokeSignals[0]!.aborted, true) + assert.equal(preparationSignals[0]!.aborted, true) +}) + +test('the attempt key is forwarded in lower case', async () => { + const { handle, calls } = setup() + assert.equal((await handle(request({ key: attemptId.toUpperCase() }))).status, 200) + assert.equal(calls[0]!.headers['idempotency-key'], attemptId) +}) + +test('a binding kind changed after construction has no effect', async () => { + const binding = { + kind: 'create' as 'create' | 'target', path: route, preparationTimeoutMs: 1000, parseSubmission, parsePreparation, + async invoke() { return { recordId: '00000000-0000-4000-8000-000000000001', revision: 1 } }, + } + const handle = createHolderActionHandler(binding as never, prepareRegistration) + binding.kind = 'target' + const answer = await handle(request()) + assert.equal(answer.status, 200) +}) + +test('an answer that is not a product refusal leaves the attempt unresolved', async () => { + // A 5xx may follow a commit, and a 2xx the client cannot read may carry one: neither is a refusal. + for (const [name, answer] of [ + ['5xx problem', () => Response.json({ status: 503, code: 'service.unavailable', detail: 'd', title: 't', traceId, + type: 'https://id.registrystack.org/problems/registry-breg/service/unavailable' }, + { status: 503, headers: { 'Content-Type': 'application/problem+json', traceparent } })], + ['unreadable 2xx', () => new Response('not json', { status: 200, headers: { 'Content-Type': 'application/json' } })], + // A 4xx with no problem body may come from a proxy, not from BReg's decision. + ['4xx without a problem', () => new Response('denied', { status: 403, headers: { 'Content-Type': 'text/plain' } })], + ] as const) { + const { handle, calls } = setup(prepareRegistration, { answer }) + const result = await handle(request()) + assert.equal(result.status, 502, name) + assert.equal((await result.json() as { code: string }).code, 'holder-action.outcome-unresolved', name) + assert.equal(calls.length, 1, name) + } +}) + +test('a caller abort after dispatch leaves the attempt unresolved', { timeout: 3000 }, async () => { + const controller = new AbortController() + const { handle, calls } = setup(prepareRegistration, { + answer: signal => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => reject(signal.reason), { once: true }) + controller.abort() + }), + }) + const result = await handle(request({ signal: controller.signal })) + assert.equal(result.status, 502) + assert.equal((await result.json() as { code: string }).code, 'holder-action.outcome-unresolved') + assert.equal(calls.length, 1) +}) + +test('a create request that is not JSON is refused before preparation', async () => { + // A cross-site form cannot send application/json without a preflight. + for (const type of ['text/plain', 'application/x-www-form-urlencoded', 'multipart/form-data']) { + const { handle, preparations, calls } = setup() + const forged = new Request('https://service.test' + route, { + method: 'POST', body: JSON.stringify(submission), + headers: { 'Content-Type': type, 'Idempotency-Key': attemptId, Authorization: registrarAuthorization }, + }) + assert.equal((await handle(forged)).status, 400, type) + assert.deepEqual([preparations.length, calls.length], [0, 0], type) + } +}) + +test('every handler answer is marked no-store', async () => { + const { handle } = setup() + for (const answer of [await handle(request()), await handle(request({ authorization: null })), + await handle(request({ path: '/api/functions/other' }))]) { + assert.equal(answer.headers.get('cache-control'), 'no-store') + } +}) + +test('a host invoke error is a refusal only when refused, settled and 4xx', async () => { + // Each error fails exactly one of the three conditions, so each condition is needed on its own. + const refusal = (kind: 'refused' | 'unexpected', status: number, outcomeUnknown: boolean) => + new RegistryError({ kind, reason: 'status', status, outcomeUnknown }) + for (const [name, error, expected] of [ + ['settled 4xx refusal', refusal('refused', 403, false), 403], + ['4xx refusal with an unknown outcome', refusal('refused', 403, true), 502], + ['5xx marked refused', refusal('refused', 503, false), 502], + ['unexpected 4xx', refusal('unexpected', 403, false), 502], + ] as const) { + const handle = createHolderActionHandler({ + kind: 'create', path: route, preparationTimeoutMs: 1000, parseSubmission, parsePreparation, + async invoke() { throw error }, + }, prepareRegistration) + const result = await handle(request()) + assert.equal(result.status, expected, name) + if (expected === 502) { + assert.equal((await result.json() as { code: string }).code, 'holder-action.outcome-unresolved', name) + } + } +}) diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts new file mode 100644 index 0000000000..64badc47a2 --- /dev/null +++ b/clients/typescript/tests/holder-function.test.ts @@ -0,0 +1,444 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test, { after } from 'node:test' +import { pathToFileURL } from 'node:url' +import { Transport, type CallOptions, type Operation } from '../core.ts' +import { generateFile } from '../generate.ts' +import { createHolderActionHandler } from '../holder-function.ts' + +const route = '/api/functions/renew' +const licenceId = 'c137aa49-8a74-4d63-9f38-47fde38b2949' +const otherLicenceId = 'a4d5b3fe-eaf4-456e-ae33-9ef6b85fa4b2' +const reviewedExpiresOn = '2027-06-30' +const newExpiresOn = '2028-06-30' +const ifMatch = '"reviewed-revision"' +const otherIfMatch = '"other-reviewed-revision"' +const attemptId = '08114403-75d2-48d3-961a-5d4fb8b19687' +const holderAuthorization = 'Bearer synthetic-holder' +const traceId = '11111111111111111111111111111111' +const traceparent = `00-${traceId}-2222222222222222-01` +const submission = { licenceId, reviewedExpiresOn, preconditions: { licenceId: { ifMatch } } } +const holder = { subject: 'person-a', holderRef: 'holder-a', actor: 'human', client: 'licence-holder', + profile: 'licence-holder', audience: 'licences' } +const identities = new Map([ + [holderAuthorization, holder], + ['Bearer synthetic-holder-renewed', holder], + ['Bearer synthetic-other-subject', { ...holder, subject: 'person-b', holderRef: 'holder-b' }], + ['Bearer synthetic-agent', { ...holder, actor: 'agent' }], + ['Bearer synthetic-officer', { ...holder, profile: 'licence-officer' }], + ['Bearer synthetic-other-client', { ...holder, client: 'other' }], + ['Bearer synthetic-other-audience', { ...holder, audience: 'other' }], +]) +const records = new Map([[licenceId, { holderRef: 'holder-a', ifMatch }], + [otherLicenceId, { holderRef: 'holder-b', ifMatch: otherIfMatch }]]) +const otherSubmission = { ...submission, licenceId: otherLicenceId, preconditions: { licenceId: { ifMatch: otherIfMatch } } } + +const renewal: Operation = { + method: 'POST', path: '/v1/actions/renew', product: 'breg', + accessProfileParameter: true, accessProfileRequired: true, + keyed: true, mutating: true, requestMediaType: 'application/json', + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status', 'title', 'traceId', 'type']) }, + responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, +} + +type RenewalInput = { licenceId: string; newExpiresOn: string } +type RenewalOptions = CallOptions & { accessProfile: 'licence-holder'; preconditions: { licenceId: { ifMatch: string } } } +type RenewalReceipt = { results: { licence?: { recordId: string } } } +type RenewalClient = { + invoke(action: 'renew', input: RenewalInput, options: RenewalOptions): Promise<{ data: RenewalReceipt }> +} + +let renewalClient = (transport: Transport): RenewalClient => ({ + invoke(_action, input, { accessProfile, preconditions, ...options }) { + return transport.call(renewal, { ...options, query: { accessProfile }, body: { input, preconditions } }) + }, +}) + +// Re-run the same synthetic transport cases using a client generated from the medical project's OpenAPI. +const medicalOpenApi = process.env.REGISTRY_HOLDER_TEST_OPENAPI +if (medicalOpenApi) { + const scratch = mkdtempSync(join(tmpdir(), 'registry-holder-openapi-')) + after(() => rmSync(scratch, { recursive: true })) + writeFileSync(join(scratch, 'package.json'), '{"type":"module"}\n') + const output = join(scratch, 'medical-renewal.ts') + generateFile(medicalOpenApi, output, false, true, [], true) + const { Client } = await import(pathToFileURL(output).href) as { Client: new (transport: Transport) => RenewalClient } + renewalClient = transport => new Client(transport) +} + +function exactObject(value: unknown, keys: readonly string[]): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) +} + +function parseSubmission(value: unknown) { + if (!exactObject(value, ['licenceId', 'reviewedExpiresOn', 'preconditions']) || + typeof value.licenceId !== 'string' || typeof value.reviewedExpiresOn !== 'string' || + !exactObject(value.preconditions, ['licenceId']) || !exactObject(value.preconditions.licenceId, ['ifMatch']) || + typeof value.preconditions.licenceId.ifMatch !== 'string') return undefined + return { + recordId: value.licenceId, ifMatch: value.preconditions.licenceId.ifMatch, + preparation: { reviewedExpiresOn: value.reviewedExpiresOn }, + } +} + +function parsePreparation(value: unknown) { + if (!exactObject(value, ['newExpiresOn']) || typeof value.newExpiresOn !== 'string') return undefined + return { newExpiresOn: value.newExpiresOn } +} + +function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { + const { path = route, authorization = holderAuthorization, body = submission, key = attemptId, signal } = options + const headers = new Headers({ + 'Content-Type': 'application/json', 'Idempotency-Key': key, + 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', + }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body), signal }) +} + +function prepareRenewal({ reviewedExpiresOn }: { reviewedExpiresOn: string }) { + const year = Number(reviewedExpiresOn.slice(0, 4)) + return { newExpiresOn: String(year + 1) + reviewedExpiresOn.slice(4) } +} + +function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prepareRenewal, + { loseFirstReceipt = false, parse = parseSubmission, receiptRecordId = '', preparationTimeoutMs = 1000, + replayProblem, omitReceiptRevision = false }: { loseFirstReceipt?: boolean; parse?: typeof parseSubmission; + receiptRecordId?: string | null; preparationTimeoutMs?: number; omitReceiptRevision?: boolean; + replayProblem?: 'idempotency.key-reused' | 'idempotency.expired' | 'mutation.conflict' } = {}, +) { + const preparations: unknown[][] = [] + const preparationSignals: AbortSignal[] = [] + const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] + const writes: string[] = [] + const verifiedApplicantIds: string[] = [] + const committed = new Map() + + const fetchProduct: typeof fetch = async (target, options) => { + const url = new URL(String(target)) + const headers = new Headers(options?.headers) + const body = JSON.parse(String(options?.body)) + calls.push({ url: url.href, method: options?.method, headers: Object.fromEntries(headers), body }) + if (url.pathname !== renewal.path || options?.method !== 'POST' || url.searchParams.get('accessProfile') !== 'licence-holder') { + throw new Error('The caller changed the checked Action contract.') + } + const refuse = (status: number, code: string) => Response.json({ + status, code, detail: 'product-only detail', title: 'BReg refused the request.', traceId, + type: 'https://id.registrystack.org/problems/registry-breg/' + code.replaceAll('.', '/'), + }, { status, headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store', traceparent } }) + const receipt = () => Response.json({ action: 'renew', applicationId: attemptId, + results: receiptRecordId === null ? {} : { licence: { recordId: receiptRecordId || body.input.licenceId, + recordType: 'licence', revision: omitReceiptRevision ? undefined : 2 } }, + }, { headers: { 'Cache-Control': 'no-store', traceparent } }) + const identity = identities.get(headers.get('authorization') ?? '') + if (!identity || identity.audience !== 'licences') return refuse(401, 'authentication.refused') + if (identity.actor !== 'human' || identity.client !== 'licence-holder' || identity.profile !== 'licence-holder') { + return refuse(403, 'profile.not-authorized') + } + const record = records.get(body.input.licenceId) + if (record?.holderRef !== identity.holderRef || body.preconditions.licenceId.ifMatch !== record.ifMatch) { + return refuse(412, 'precondition.failed') + } + if (body.input.newExpiresOn !== newExpiresOn) return refuse(412, 'action.guard-failed') + const receiptKey = identity.subject + ':' + headers.get('idempotency-key') + const command = JSON.stringify(body) + if (committed.has(receiptKey)) { + if (replayProblem) return refuse(replayProblem === 'idempotency.expired' ? 410 : 409, replayProblem) + if (committed.get(receiptKey) !== command) return refuse(409, 'idempotency.key-reused') + return receipt() + } + committed.set(receiptKey, command) + writes.push(body.input.licenceId) + verifiedApplicantIds.push(identity.holderRef) + if (loseFirstReceipt && writes.length === 1) throw new Error('Simulated lost product receipt') + return receipt() + } + + const handle = createHolderActionHandler({ + kind: 'target', + path: route, + preparationTimeoutMs, + parseSubmission: parse, + parsePreparation, + async invoke(credential, command) { + const { recordId, ifMatch, input, idempotencyKey, signal } = command + const client = renewalClient(new Transport({ baseUrl: 'https://licences.test', token: () => credential, fetch: fetchProduct })) + const { data } = await client.invoke('renew', { licenceId: recordId, newExpiresOn: input.newExpiresOn }, { + accessProfile: 'licence-holder', preconditions: { licenceId: { ifMatch } }, + idempotencyKey, + signal, + }) + const receivedRecordId = data.results.licence?.recordId + if (!receivedRecordId) throw new Error('BReg returned no licence receipt.') + return { recordId: receivedRecordId } + }, + }, (value, options) => { + preparations.push([value]) + preparationSignals.push(options.signal) + return prepare(value) + }) + return { handle, preparations, preparationSignals, calls, writes, verifiedApplicantIds } +} + +test('preparation receives one projected value and the checked Action receives the holder command', async () => { + const { handle, preparations, calls, writes } = setup() + const result = await handle(request()) + assert.equal(result.status, 200) + assert.deepEqual(await result.json(), { recordId: licenceId }) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.equal(calls.length, 1) + const call = calls[0]! + assert.equal(call.url, 'https://licences.test/v1/actions/renew?accessProfile=licence-holder') + assert.equal(call.method, 'POST') + assert.equal(call.headers.authorization, holderAuthorization) + assert.equal(call.headers['idempotency-key'], attemptId) + for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) + assert.deepEqual(call.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) + assert.deepEqual(writes, [licenceId]) +}) + +test('a missing caller or request outside the declared binding never reaches preparation or BReg', async () => { + const { handle, preparations, calls } = setup() + const cases = [ + [request({ authorization: null }), 401], + [request({ path: route + '/other' }), 404], + [request({ path: route + '?accessProfile=licence-officer' }), 404], + [request({ path: '/api/functions/issue' }), 404], + [request({ body: { ...submission, action: 'issue' } }), 400], + [request({ body: { ...submission, product: 'other' } }), 400], + [request({ body: { ...submission, accessProfile: 'licence-officer' } }), 400], + [request({ body: { ...submission, subject: 'other' } }), 400], + [request({ body: { ...submission, applicantId: 'holder-b' } }), 400], + [request({ body: { ...submission, licenceId: licenceId.toUpperCase() } }), 400], + [request({ key: 'wrong' }), 400], + ] as const + for (const [incoming, expected] of cases) assert.equal((await handle(incoming)).status, expected) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('a preparation result outside its projection cannot substitute the target or invoke BReg', async () => { + const { handle, preparations, calls } = setup(() => ({ newExpiresOn, licenceId: otherLicenceId })) + assert.equal((await handle(request())).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.deepEqual(calls, []) +}) + +test('a preparation result naming an applicant is refused before BReg', async () => { + // The function cannot choose the person: an applicant ID it hard-codes fails the + // strict projection, so no Action is dispatched and BReg keeps the holder's authority. + const { handle, preparations, calls, writes } = setup(() => ({ newExpiresOn, applicantId: 'holder-b' })) + const result = await handle(request()) + assert.equal(result.status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.deepEqual(calls, []) + assert.deepEqual(writes, []) +}) + +test('cancellation before preparation admits no preparation or Action dispatch', async () => { + const { handle, preparations, calls } = setup() + const response = await handle(request({ signal: AbortSignal.abort() })) + assert.equal(response.status, 502) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('cancellation during preparation returns without waiting for the result or dispatching an Action', { timeout: 3000 }, async t => { + const caller = new AbortController() + let finish: ((result: unknown) => void) | undefined + t.after(() => finish?.({ newExpiresOn })) + const { handle, preparations, calls } = setup(() => new Promise(resolve => { + finish = resolve + caller.abort() + }), { preparationTimeoutMs: 10_000 }) + assert.equal((await handle(request({ signal: caller.signal }))).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + finish?.({ newExpiresOn }) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(calls, []) +}) + +test('a late preparation result cannot dispatch an Action after the deadline', { timeout: 3000 }, async () => { + let finish: ((result: unknown) => void) | undefined + const { handle, preparations, calls } = setup(() => new Promise(resolve => { finish = resolve }), { + preparationTimeoutMs: 20, + }) + assert.equal((await handle(request())).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + finish?.({ newExpiresOn }) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(calls, []) +}) + +test('a throwing submission parser returns a fixed refusal before preparation or BReg', async () => { + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { throw new Error('submitted values excluded from the reply') }, + }) + const response = await handle(request()) + assert.equal(response.status, 400) + assert.doesNotMatch(await response.text(), /submitted values/u) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('absent and oversized bodies are refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + assert.equal((await handle(new Request(url, { headers, method }))).status, 400) + assert.equal((await handle(request({ body: 'x'.repeat(32_768) }))).status, 413) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('ambiguous request JSON is refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + const cases = [ + '{"preconditions":{"licenceId":{"ifMatch":"a","ifM\\u0061tch":"b"}}}', + '{"input":9007199254740993}', + ] + for (const body of cases) assert.equal((await handle(new Request(url, { headers, method, body }))).status, 400) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('synthetic product refusals for subject, actor, role, client, audience, target, or condition stay refusals', async () => { + const { handle, calls, writes } = setup() + const refusals = [ + [request({ authorization: 'Bearer synthetic-other-subject' }), 412], + [request({ authorization: 'Bearer synthetic-agent' }), 403], + [request({ authorization: 'Bearer synthetic-officer' }), 403], + [request({ authorization: 'Bearer synthetic-other-client' }), 403], + [request({ authorization: 'Bearer synthetic-other-audience' }), 401], + [request({ body: otherSubmission }), 412], + [request({ authorization: 'Bearer synthetic-other-subject', body: { ...submission, licenceId: otherLicenceId } }), 412], + [request({ body: { ...submission, preconditions: { licenceId: { ifMatch: '"stale-revision"' } } } }), 412], + ] as const + for (const [incoming, expected] of refusals) { + const response = await handle(incoming) + assert.equal(response.status, expected) + assert.doesNotMatch(await response.text(), /product-only detail|synthetic/u) + } + assert.equal(calls.length, refusals.length) + assert.deepEqual(writes, []) +}) + +test('overlapping requests keep each captured holder and exact target together', async () => { + const { handle, calls, writes } = setup() + const [first, second] = await Promise.all([ + handle(request()), + handle(request({ authorization: 'Bearer synthetic-other-subject', body: otherSubmission })), + ]) + assert.deepEqual([first.status, second.status], [200, 200]) + assert.deepEqual(await first.json(), { recordId: licenceId }) + assert.deepEqual(await second.json(), { recordId: otherLicenceId }) + assert.deepEqual(calls.map(call => call.headers.authorization).sort(), + [holderAuthorization, 'Bearer synthetic-other-subject'].sort()) + assert.deepEqual(writes.sort(), [licenceId, otherLicenceId].sort()) +}) + +test('a product refusal of the prepared value stays a refusal', async () => { + const { handle, calls, writes } = setup(() => ({ newExpiresOn: '2031-07-01' })) + const response = await handle(request()) + assert.equal(response.status, 412) + assert.deepEqual(await response.json(), { message: 'BReg refused the request.' }) + assert.equal(calls.length, 1) + assert.deepEqual(writes, []) +}) + +test('a product receipt missing the exact record leaves the original attempt unresolved', async () => { + for (const receiptRecordId of [otherLicenceId, null]) { + const { handle, calls } = setup(prepareRenewal, { receiptRecordId }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.deepEqual(await response.json(), { + code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }) + assert.equal(calls.length, 1) + assert.equal(calls[0]?.headers['idempotency-key'], attemptId) + } +}) + +if (medicalOpenApi) { + test('the generated client refuses a receipt that names the exact record without the required revision', async () => { + const { handle, calls } = setup(prepareRenewal, { omitReceiptRevision: true }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.deepEqual(await response.json(), { + code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }) + assert.equal(calls.length, 1) + }) +} + +test('after a lost product receipt the renewed holder credential reuses the same command and reads back one effect', async () => { + const { handle, calls, preparations, writes } = setup(prepareRenewal, { loseFirstReceipt: true }) + const first = await handle(request()) + assert.equal(first.status, 502) + assert.doesNotMatch(await first.text(), /Simulated/u) + const retry = await handle(request({ authorization: 'Bearer synthetic-holder-renewed' })) + assert.equal(retry.status, 200) + assert.deepEqual(await retry.json(), { recordId: licenceId }) + assert.equal(calls.length, 2) + const [firstCall, secondCall] = calls + assert.ok(firstCall && secondCall) + assert.equal(firstCall.headers.authorization, holderAuthorization) + assert.deepEqual(secondCall, { ...firstCall, headers: { ...firstCall.headers, authorization: 'Bearer synthetic-holder-renewed' } }) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }], [{ reviewedExpiresOn }]]) + assert.deepEqual(writes, [licenceId]) +}) + +test('a spent key leaves the original attempt unresolved without dispatching with a new key', async () => { + for (const [status, replayProblem] of [[409, 'idempotency.key-reused'], [410, 'idempotency.expired']] as const) { + const { handle, calls, writes } = setup(prepareRenewal, { loseFirstReceipt: true, replayProblem }) + const first = await handle(request()) + assert.equal(first.status, 502) + const retry = await handle(request({ authorization: 'Bearer synthetic-holder-renewed' })) + assert.equal(retry.status, status) + assert.deepEqual(await retry.json(), { + code: 'holder-action.outcome-unresolved', message: 'The Action outcome is unconfirmed. Keep the original attempt.', + }) + assert.deepEqual(calls.map(call => call.headers['idempotency-key']), [attemptId, attemptId]) + assert.deepEqual(writes, [licenceId]) + } +}) + +test('an ordinary product conflict keeps its refusal response', async () => { + const { handle, writes } = setup(prepareRenewal, { replayProblem: 'mutation.conflict' }) + assert.equal((await handle(request())).status, 200) + const conflict = await handle(request()) + assert.equal(conflict.status, 409) + assert.deepEqual(await conflict.json(), { message: 'BReg refused the request.' }) + assert.deepEqual(writes, [licenceId]) +}) + +test('a target submission needs a string UUID record and a strong condition', async () => { + for (const [name, parse] of [ + ['weak condition', (value: unknown) => ({ ...parseSubmission(value)!, ifMatch: 'W/"reviewed-revision"' })], + ['unquoted condition', (value: unknown) => ({ ...parseSubmission(value)!, ifMatch: 'reviewed-revision' })], + // A one-element array stringifies to a valid value, so only the type check refuses it. + ['array record', (value: unknown) => { + const parsed = parseSubmission(value)! + return { ...parsed, recordId: [parsed.recordId] as unknown as string } + }], + ['array condition', (value: unknown) => { + const parsed = parseSubmission(value)! + return { ...parsed, ifMatch: [parsed.ifMatch] as unknown as string } + }], + ] as const) { + const { handle, preparations, calls } = setup(prepareRenewal, { parse }) + assert.equal((await handle(request())).status, 400, name) + assert.deepEqual([preparations.length, calls.length], [0, 0], name) + } +}) diff --git a/clients/typescript/tests/live/products.live.ts b/clients/typescript/tests/live/products.live.ts index 2a8f564d44..85488bea88 100644 --- a/clients/typescript/tests/live/products.live.ts +++ b/clients/typescript/tests/live/products.live.ts @@ -157,7 +157,7 @@ export function registerServerLiveMatrix( token: () => manifest.tokens.coordinatorCaller, })) const workflow = await client.call('workflowContract', { - path: { workflow: manifest.metadata.coordinatorWorkflow }, + path: { workflowId: manifest.metadata.coordinatorWorkflow }, }) assert.equal(workflow.status, 200) assert.equal(workflow.developmentPeer, true) @@ -180,12 +180,12 @@ export function registerServerLiveMatrix( }) assert.equal(replayed.data.runId, started.data.runId) - const status = await client.call('runStatus', { path: { run: started.data.runId } }) + const status = await client.call('runStatus', { path: { runId: started.data.runId } }) assert.equal(status.data.runId, started.data.runId) const anon = new CoordinatorClient(new Transport({ baseUrl: manifest.products.coordinator, token: () => undefined })) await expectUnauthorized(anon.call('workflowContract', { - path: { workflow: manifest.metadata.coordinatorWorkflow }, + path: { workflowId: manifest.metadata.coordinatorWorkflow }, })) }) diff --git a/clients/typescript/tests/media.test.ts b/clients/typescript/tests/media.test.ts index 84d7160587..b6895891cc 100644 --- a/clients/typescript/tests/media.test.ts +++ b/clients/typescript/tests/media.test.ts @@ -177,20 +177,22 @@ test('Scheduling receipt lookup needs the original key and sends exactly it as a test('a signed Coordinator event sends the signed bytes unchanged and no bearer credential', async () => { const signed = new TextEncoder().encode('{ "id" : "evt-1",\n "type": "fixture" }\n') let asked = 0 - let seen: { body: unknown; authorization: string | null; credentials: unknown } | undefined + let seen: { path: string; body: unknown; authorization: string | null; credentials: unknown } | undefined const coordinator = make(Coordinator, { baseUrl: 'https://registry.example', token: () => { asked++; return 'bearer' }, - fetch: async (_url, init) => { - seen = { body: init?.body, authorization: new Headers(init?.headers).get('authorization'), credentials: init?.credentials } + fetch: async (url, init) => { + seen = { path: new URL(String(url)).pathname, body: init?.body, + authorization: new Headers(init?.headers).get('authorization'), credentials: init?.credentials } return new Response(null, { status: 204 }) } }) const headers = { 'webhook-id': '00000000-0000-4000-8000-000000000001', 'webhook-timestamp': '1614265330', 'webhook-signature': 'v1,fixture' } - const answer = await coordinator.call('admitEvent', { path: { workflow: 'w', trigger: 't' }, headers, body: signed }) + const answer = await coordinator.call('admitEvent', { path: { workflowId: 'w', triggerId: 't' }, headers, body: signed }) assert.equal(answer.status, 204) assert.ok(seen?.body instanceof Uint8Array) + assert.equal(seen.path, '/v1/events/w/t') assert.deepEqual(seen.body, signed) assert.equal(seen.authorization, null) assert.equal(seen.credentials, 'omit') assert.equal(asked, 0) - await assert.rejects(coordinator.call('admitEvent', { path: { workflow: 'w', trigger: 't' }, headers, + await assert.rejects(coordinator.call('admitEvent', { path: { workflowId: 'w', triggerId: 't' }, headers, body: { id: 'evt-1' } as never }), { name: 'TypeError', message: 'Signed request body must be the signed bytes' }) }) diff --git a/clients/typescript/tests/package.test.ts b/clients/typescript/tests/package.test.ts index 390c4aa195..ed01c8d0e1 100644 --- a/clients/typescript/tests/package.test.ts +++ b/clients/typescript/tests/package.test.ts @@ -14,6 +14,9 @@ test('the browser package is publishable at the unified client release version', assert.equal(manifest.exports['.'].types, './dist/browser.d.ts') assert.equal(manifest.exports['.'].default, './dist/browser.js') assert.deepEqual(manifest.exports['./mcp'], { types: './dist/mcp.d.ts', default: './dist/mcp.js' }) + // A trusted host invokes a holder-authorized Action through this binding. + assert.deepEqual(manifest.exports['./holder-function'], + { types: './dist/holder-function.d.ts', default: './dist/holder-function.js' }) assert.equal(manifest.license, 'Apache-2.0') const binaries = { 'registry-generate': './registry-generate.js', 'registry-preview': './preview/cli.mjs' } assert.deepEqual(manifest.bin, binaries) @@ -28,3 +31,11 @@ test('the browser package is publishable at the unified client release version', } assert.deepEqual(manifest.files, ['dist', 'registry-generate.js', 'preview/*.mjs', 'LICENSE']) }) + +test('the package builds and exports the holder binding source', async () => { + // CI runs the tests before the build, so check the source the export is built from. + const build = JSON.parse(readFileSync(new URL('../tsconfig.browser.json', import.meta.url), 'utf8')) + assert.ok(build.include.includes('holder-function.ts')) + const { createHolderActionHandler } = await import('../holder-function.ts') + assert.equal(typeof createHolderActionHandler, 'function') +}) diff --git a/clients/typescript/tests/page.test.ts b/clients/typescript/tests/page.test.ts index 5ba0bc7139..7c2f649dce 100644 --- a/clients/typescript/tests/page.test.ts +++ b/clients/typescript/tests/page.test.ts @@ -310,7 +310,7 @@ test('a signed operation omits cookies and keeps a 401 as a signature refusal in const { seen, fetch } = recording(() => new Response(null, { status: 401 })) const coordinator = make(Coordinator, { baseUrl, fetch }) const headers = { 'webhook-id': '00000000-0000-4000-8000-000000000001', 'webhook-timestamp': '1', 'webhook-signature': 'v1,x' } - await assert.rejects(coordinator.call('admitEvent', { path: { workflow: 'w', trigger: 't' }, headers, body: Uint8Array.of(123, 125) }), + await assert.rejects(coordinator.call('admitEvent', { path: { workflowId: 'w', triggerId: 't' }, headers, body: Uint8Array.of(123, 125) }), { reason: 'status', status: 401 }) assert.deepEqual(seen, [{ authorization: null, credentials: 'omit', page: 'page' }]) }) diff --git a/clients/typescript/tsconfig.browser.json b/clients/typescript/tsconfig.browser.json index 2d68615e35..d858b90af0 100644 --- a/clients/typescript/tsconfig.browser.json +++ b/clients/typescript/tsconfig.browser.json @@ -8,5 +8,5 @@ "outDir": "dist", "declaration": true }, - "include": ["browser.ts", "core.ts", "mcp.ts", "webhook.ts", "schema.ts", "generated/**/*.ts"] + "include": ["browser.ts", "core.ts", "holder-function.ts", "mcp.ts", "webhook.ts", "schema.ts", "generated/**/*.ts"] } diff --git a/crates/registry-adapter-core/src/runtime.rs b/crates/registry-adapter-core/src/runtime.rs index 8e766523eb..2d1b7c1cb0 100644 --- a/crates/registry-adapter-core/src/runtime.rs +++ b/crates/registry-adapter-core/src/runtime.rs @@ -807,9 +807,9 @@ mod tests { id: LocalId::new("case-deployment").expect("id"), endpoints: UniqueIdList::new(vec![binding()]).expect("unique"), secret_providers: Some(SecretProvidersConfig { - file: Some(registry_platform_config::FileSecretProviderConfig { - root: "/run/secrets/adapter".into(), - }), + file: Some(registry_platform_config::FileSecretProviderConfig::new( + "/run/secrets/adapter".into(), + )), environment: None, }), outbound_tls: Some(OutboundTls { diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index 998fb86cd8..1cee780125 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -517,6 +517,10 @@ fn secret_refusal_fix(error: &SecretError) -> &'static str { "create the file under secretProviders.file.root or set the variable" } SecretError::UnsafeFile(check) => check.suggested_action(), + SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), + SecretError::PrivateKeyInPublicDocument | SecretError::PublicDocumentNotText => { + error.suggested_action() + } SecretError::Read => "check that the service user can read the secret file", SecretError::InvalidValue => { "store a non-empty value with no NUL byte, within the secret size limit" @@ -2158,9 +2162,7 @@ audit: {retentionDays: 90} std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o600)) .expect("private mode"); let providers = SecretProvidersConfig { - file: Some(FileSecretProviderConfig { - root: root.path().to_path_buf(), - }), + file: Some(FileSecretProviderConfig::new(root.path().to_path_buf())), environment: None, }; diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index e4f67c6c31..009394178a 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -436,6 +436,10 @@ fn resolve_member( } SecretError::Unavailable => "the secret file is missing", SecretError::UnsafeFile(check) => check.suggested_action(), + SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), + SecretError::PrivateKeyInPublicDocument | SecretError::PublicDocumentNotText => { + error.suggested_action() + } SecretError::Read => "the secret file could not be read", SecretError::InvalidValue => "the secret is empty or contains a NUL byte", SecretError::ProviderDisabled => { diff --git a/crates/registry-adapter-job/src/runtime_destination.rs b/crates/registry-adapter-job/src/runtime_destination.rs index 5dea3ec2ae..be28eed68e 100644 --- a/crates/registry-adapter-job/src/runtime_destination.rs +++ b/crates/registry-adapter-job/src/runtime_destination.rs @@ -24,6 +24,11 @@ use registry_platform_crypto::delivery_signature::DeliveryKeys; #[cfg(any(feature = "direct-breg", feature = "signed-coordinator-event"))] use registry_platform_crypto::delivery_signature::{distinct_delivery_keys, DeliveryKey}; #[cfg(feature = "signed-coordinator-event")] +use registry_platform_httputil::{ + destination::EventDestinationPolicy, + select::{select_destination, TransportClass}, +}; +#[cfg(feature = "signed-coordinator-event")] use registry_platform_yaml::ExternalId; use registry_platform_yaml::{BoundedU64, LocalId, SecretReference, Url}; use serde::Deserialize; @@ -106,16 +111,15 @@ pub async fn activate_destination<'a>( ) -> Result, String> { require_compiled_destination(&program.job.destination).map_err(not_compiled_message)?; let bindings = load_runtime_bindings(runtime)?; - #[cfg(any(feature = "direct-breg", feature = "signed-coordinator-event"))] - let keys = resolve_destination_keys(resolver, &bindings)?; match &program.job.destination { JobDestination::DirectBreg { binding, .. } => { + #[cfg(feature = "direct-breg")] + drop(resolve_destination_keys(resolver, &bindings)?); let configured = bindings .get(binding) .ok_or_else(|| missing_binding(binding))?; #[cfg(feature = "direct-breg")] { - drop(keys); activate_direct( program, configured, @@ -142,7 +146,7 @@ pub async fn activate_destination<'a>( configured, &runtime.core, resolver, - keys, + &bindings, runtime.posture.posture(), ) } @@ -155,9 +159,8 @@ pub async fn activate_destination<'a>( } } -/// Check destination feature and runtime binding shape without resolving a -/// secret or opening a network connection. `adapter-job check` uses this -/// before it reports success. +/// Check the destination feature, runtime binding and signed event transport +/// without resolving a secret or opening a network connection. pub fn check_destination_runtime( job: &AdapterJob, runtime: &JobRuntimeConfig, @@ -178,14 +181,28 @@ pub fn check_destination_runtime( revised_receiver, .. }, RuntimeDestinationBinding::SignedCoordinatorEvent { + #[cfg(feature = "signed-coordinator-event")] + base_url, revised_receiver: configured_revised, + #[cfg(feature = "signed-coordinator-event")] + tls_trust_profile, .. }, - ) => check_revised_receiver( - binding, - revised_receiver.is_some(), - configured_revised.is_some(), - ), + ) => { + check_revised_receiver( + binding, + revised_receiver.is_some(), + configured_revised.is_some(), + )?; + #[cfg(feature = "signed-coordinator-event")] + signed_destination_policy( + binding, + base_url, + &runtime.core, + tls_trust_profile.is_some(), + )?; + Ok(()) + } _ => Err("the runtime destination kind does not match the job destination".to_string()), } } @@ -561,19 +578,50 @@ fn take_receiver_keys(keys: &mut BTreeMap, path: &str) -> D DeliveryKeys::new(current, previous).expect("the inventory validated distinct key bytes") } +#[cfg(feature = "signed-coordinator-event")] +fn signed_destination_policy( + binding: &LocalId, + base_url: &Url, + core: &AdapterEndpointBindings, + configured_tls: bool, +) -> Result { + let refused = "the signed-event destination policy was refused"; + // Transport inference admits HTTPS and loopback HTTP. Source CIDRs keep + // their existing role in the fixed event policy's address checks. + let selected = + select_destination(&base_url.to_url(), None, &[]).map_err(|_| refused.to_owned())?; + let private_cidrs = core + .allowed_private_cidrs + .iter() + .map(registry_adapter_core::Cidr::network) + .collect::>(); + // The original URL must be a bare origin, and HTTPS retains its existing + // profile and DNS policy. + let policy = EventDestinationPolicy::new( + binding.as_str(), + base_url.as_str(), + selected.profile(), + &private_cidrs, + ) + .map_err(|_| refused.to_owned())?; + if configured_tls && selected.transport() != TransportClass::VerifiedTls { + return Err("the signed-event destination TLS material was refused".to_owned()); + } + Ok(policy) +} + #[cfg(feature = "signed-coordinator-event")] fn activate_signed<'a>( program: &'a JobProgram, configured: &RuntimeDestinationBinding, core: &AdapterEndpointBindings, resolver: &SecretResolver, - mut keys: BTreeMap, + bindings: &BTreeMap, posture: registry_platform_config::Posture, ) -> Result, String> { use registry_adapter_connectors::coordinator_event::{ CoordinatorEventConnector, CoordinatorEventReceiver, }; - use registry_platform_httputil::destination::{DestinationProfile, EventDestinationPolicy}; let JobDestination::SignedCoordinatorEvent { binding, @@ -602,28 +650,18 @@ fn activate_signed<'a>( revised_receiver.is_some(), configured_revised.is_some(), )?; + let mut policy = + signed_destination_policy(binding, base_url, core, tls_trust_profile.is_some())? + .with_peer_policy(registry_platform_httputil::PeerPolicy::from_posture( + posture, + )); + let mut keys = resolve_destination_keys(resolver, bindings)?; let path = format!("destinations.{binding}"); let primary_keys = take_receiver_keys(&mut keys, &path); let revised_keys = configured_revised .as_ref() .map(|_| take_receiver_keys(&mut keys, &format!("{path}.revisedReceiver"))); drop(keys); - let profile = if base_url.is_https() { - DestinationProfile::ProductionHttps - } else { - DestinationProfile::LoopbackHttp - }; - let private_cidrs = core - .allowed_private_cidrs - .iter() - .map(registry_adapter_core::Cidr::network) - .collect::>(); - let mut policy = - EventDestinationPolicy::new(binding.as_str(), base_url.as_str(), profile, &private_cidrs) - .map_err(|_| "the signed-event destination policy was refused".to_string())? - .with_peer_policy(registry_platform_httputil::PeerPolicy::from_posture( - posture, - )); if tls_trust_profile.is_some() { let endpoint = tls_endpoint(binding, base_url, tls_trust_profile.clone())?; let materials = diff --git a/crates/registry-adapter-job/src/store.rs b/crates/registry-adapter-job/src/store.rs index 5dc4a03766..2c51791e9c 100644 --- a/crates/registry-adapter-job/src/store.rs +++ b/crates/registry-adapter-job/src/store.rs @@ -745,7 +745,7 @@ fn tls_connector( .map_err(|_| invalid("no platform root certificate could be loaded")); }; let protected = resolver - .resolve(reference.as_str()) + .resolve_public_document(reference.as_str()) .map_err(|error| store_secret_error("caBundleRef", reference.as_str(), &error))?; postgres_tls_from_pem(protected.expose_secret()).map_err(|_| { StoreError::Pool("store.caBundleRef: put a usable PEM CA bundle in the secret".to_owned()) diff --git a/crates/registry-adapter-job/tests/job_file_host.rs b/crates/registry-adapter-job/tests/job_file_host.rs index 468abcef49..3e0e3d29e2 100644 --- a/crates/registry-adapter-job/tests/job_file_host.rs +++ b/crates/registry-adapter-job/tests/job_file_host.rs @@ -200,7 +200,7 @@ fn runtime_json(source: &Path, component: &str) -> String { }, "destinations": {"coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": "http://127.0.0.1:9/events", + "baseUrl": "http://127.0.0.1:9", "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 }} diff --git a/crates/registry-adapter-job/tests/postgres_source_host.rs b/crates/registry-adapter-job/tests/postgres_source_host.rs index a400ea2a54..d2b672cf27 100644 --- a/crates/registry-adapter-job/tests/postgres_source_host.rs +++ b/crates/registry-adapter-job/tests/postgres_source_host.rs @@ -820,7 +820,7 @@ fn runtime_yaml(binding: &DatabaseBinding, query_kind: SourceQuery) -> String { "id": "ledger-job-test", "endpoints": [], "sources": {"postgres": postgres_sources}, - "allowedPrivateCidrs": ["127.0.0.0/8"], + "allowedPrivateCidrs": [], "store": { "runtimeUrlRef": "secret:env/JOB_TEST_DB", "transport": "loopback-plaintext" @@ -828,7 +828,7 @@ fn runtime_yaml(binding: &DatabaseBinding, query_kind: SourceQuery) -> String { "destinations": { "coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": "http://127.0.0.1:9/events", + "baseUrl": "http://127.0.0.1:9", "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 } diff --git a/crates/registry-adapter-job/tests/posture.rs b/crates/registry-adapter-job/tests/posture.rs index 0e93d2a3d5..56cbfc8bf2 100644 --- a/crates/registry-adapter-job/tests/posture.rs +++ b/crates/registry-adapter-job/tests/posture.rs @@ -130,7 +130,7 @@ fn job_check_enforces_and_lists_the_posture() { .unwrap() .join("runtime.yaml"); let yaml = std::fs::read_to_string(base.join("job-runtime.yaml")).unwrap(); - let destination = "\ndestinations:\n coordinator-test:\n type: signed-coordinator-event\n baseUrl: http://127.0.0.1:9/events\n hmacSha256KeyRef: secret:env/JOB_EVENT_KEY\n attemptTimeoutMilliseconds: 1000\n"; + let destination = "\ndestinations:\n coordinator-test:\n type: signed-coordinator-event\n baseUrl: http://127.0.0.1:9\n hmacSha256KeyRef: secret:env/JOB_EVENT_KEY\n attemptTimeoutMilliseconds: 1000\n"; let run = |flag: Option<&str>, environment: Option<&str>| { let mut command = Command::new(env!("CARGO_BIN_EXE_adapter-job")); command diff --git a/crates/registry-adapter-job/tests/sftp_cli_host.rs b/crates/registry-adapter-job/tests/sftp_cli_host.rs index 35605401cd..4bb1bc04eb 100644 --- a/crates/registry-adapter-job/tests/sftp_cli_host.rs +++ b/crates/registry-adapter-job/tests/sftp_cli_host.rs @@ -189,7 +189,7 @@ fn runtime_json(server: &SftpSourceServer) -> Vec { }, "destinations": {"coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": "http://127.0.0.1:9/events", + "baseUrl": "http://127.0.0.1:9", "hmacSha256KeyRef": "secret:env/JOB_TEST_SIGNING_KEY", "attemptTimeoutMilliseconds": 1000 }} diff --git a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs index 78e2e85151..45e2054b43 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs @@ -29,7 +29,7 @@ use registry_adapter_engine::job::{compile_job, JobProgram}; use registry_adapter_engine::job_sources::JobRuntimeConfig; use registry_adapter_job::destination::{DeliverableItem, HandOffOutcome, JobDestination}; use registry_adapter_job::pass::{run_pass, PassOptions, PassReport, StopReason}; -use registry_adapter_job::runtime_destination::activate_destination; +use registry_adapter_job::runtime_destination::{activate_destination, check_destination_runtime}; use registry_adapter_job::signed_coordinator_event::{ receiver_identity, CoordinatorReceiverDigestContext, SignedCoordinatorEventDestination, SignedCoordinatorEventReceiver, @@ -162,6 +162,8 @@ async fn isolated_store() -> Pool { #[tokio::test(flavor = "multi_thread")] async fn runtime_binding_activates_the_signed_destination_without_fallback() { const KEY_ENV: &str = "ADAPTER_JOB_SIGNED_DESTINATION_TEST_KEY"; + const RECEIVER_DIGEST: &str = "SELECT receiver_identity FROM adapter_job_items \ + WHERE job_id = 'case-daily' AND item_key = 'submissions/a'"; struct EnvironmentGuard; impl Drop for EnvironmentGuard { fn drop(&mut self) { @@ -177,6 +179,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { .await .expect("the signed receiver binds"); let address = listener.local_addr().expect("the receiver address"); + let base_url = format!("http://127.0.0.1:{}/", address.port()); let app = Router::new() .route(TARGET, post(admit)) .with_state(receiver.clone()); @@ -203,7 +206,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { runtime["destinations"] = json!({ "coordinator-test": { "type": "signed-coordinator-event", - "baseUrl": format!("http://127.0.0.1:{}/", address.port()), + "baseUrl": &base_url, "hmacSha256KeyRef": format!("secret:env/{KEY_ENV}"), "attemptTimeoutMilliseconds": 2000 } @@ -221,6 +224,7 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { let program = compile_job(&fixture.pack, &fixture.job, &fixture.runtime).expect("the job compiles"); let runtime = JobRuntimeConfig::load(&fixture.runtime).expect("the runtime snapshot loads"); + check_destination_runtime(&program.job, &runtime).expect("the signed destination checks"); let resolver = SecretResolver::new([SecretProvider::Environment], "") .expect("the environment secret resolver starts"); let destination = activate_destination(&program, &runtime, &resolver) @@ -249,6 +253,18 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { assert_eq!(pending.sequence, 1); assert!(pending.run_id.is_none()); assert!(!pending.admitted_before); + let expected_identity = receiver_identity(&CoordinatorReceiverDigestContext { + binding: "coordinator-test", + base_url: &base_url, + tls_trust_profile: None, + workflow: "case-ingestion", + trigger: "submitted", + source: "urn:registry-adapter:job:case-daily", + event_type: "org.example.case-submitted.v1", + data_schema: "urn:example:schema:case-submitted:v1", + }); + let pending_identity: Vec = client.query_one(RECEIVER_DIGEST, &[]).await.unwrap().get(0); + assert_eq!(pending_identity, expected_identity); let state = store::read_state(&client, "case-daily") .await .unwrap() @@ -275,11 +291,81 @@ async fn runtime_binding_activates_the_signed_destination_without_fallback() { assert_eq!(acknowledged.sequence, pending.sequence); assert_eq!(acknowledged.last_digest, pending.last_digest); assert!(acknowledged.run_id.is_some()); + let retried_identity: Vec = client.query_one(RECEIVER_DIGEST, &[]).await.unwrap().get(0); + assert_eq!(retried_identity, pending_identity); let bodies = receiver.bodies.lock().expect("the receiver body lock"); assert_eq!(bodies.len(), 2); assert_eq!(bodies[0], bodies[1], "a retry preserves envelope bytes"); } +#[tokio::test] +async fn signed_destination_refuses_invalid_transports_and_origins_before_keys() { + let fixture = job_fixture::JobFixture::start( + job_fixture::PAGE_SCRIPT, + vec![], + job_fixture::Edits::Ordered, + ) + .await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let missing_key = tempfile::tempdir().expect("an empty directory for the missing key"); + let resolver = SecretResolver::new([SecretProvider::File], missing_key.path()) + .expect("the file resolver starts"); + let mut document: serde_json::Value = + serde_json::from_slice(&std::fs::read(&fixture.runtime).unwrap()).unwrap(); + let policy_refused = "the signed-event destination policy was refused"; + for (base_url, tls_trust_profile, expected) in [ + // The job fixture intentionally lists a CIDR covering this address. + ( + "http://192.168.10.8:41001/".to_owned(), + None, + policy_refused, + ), + ( + format!("http://{address}/?resource=unexpected"), + None, + policy_refused, + ), + ("https://localhost:41001/".to_owned(), None, policy_refused), + ( + format!("http://{address}/"), + Some("private-ca"), + "the signed-event destination TLS material was refused", + ), + ] { + document["destinations"] = json!({ + "coordinator-test": { + "type": "signed-coordinator-event", + "baseUrl": base_url, + "hmacSha256KeyRef": "secret:file/missing-key", + "attemptTimeoutMilliseconds": 2000 + } + }); + if let Some(profile) = tls_trust_profile { + document["destinations"]["coordinator-test"]["tlsTrustProfile"] = json!(profile); + } + std::fs::write(&fixture.runtime, serde_json::to_vec(&document).unwrap()).unwrap(); + let program = compile_job(&fixture.pack, &fixture.job, &fixture.runtime).unwrap(); + let runtime = JobRuntimeConfig::load(&fixture.runtime).unwrap(); + assert_eq!( + check_destination_runtime(&program.job, &runtime).unwrap_err(), + expected + ); + assert_eq!( + activate_destination(&program, &runtime, &resolver) + .await + .err() + .as_deref(), + Some(expected) + ); + } + assert!( + tokio::time::timeout(Duration::from_millis(100), listener.accept()) + .await + .is_err() + ); +} + #[tokio::test(flavor = "multi_thread")] async fn a_lost_signed_event_answer_recovers_one_run_through_the_job_store() { let receiver = Receiver::default(); diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 9350638609..f8dc460e39 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -277,7 +277,7 @@ async fn issuer_keys( ), JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = resolver - .resolve(document_ref) + .resolve_public_document(document_ref) .map_err(|_| invalid("the static key document could not be resolved"))?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { match error { @@ -425,7 +425,7 @@ fn tls_connector( } if let Some(reference) = &config.ca_bundle_ref { let certificate = resolver - .resolve(reference) + .resolve_public_document(reference) .map_err(|_| invalid("the trusted root could not be resolved"))?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; diff --git a/crates/registry-adapterctl/src/job_provision.rs b/crates/registry-adapterctl/src/job_provision.rs index 714783bd35..04d74553d4 100644 --- a/crates/registry-adapterctl/src/job_provision.rs +++ b/crates/registry-adapterctl/src/job_provision.rs @@ -4,7 +4,7 @@ use std::path::Path; use registry_adapter::engine::job_sources::{job_runtime_diagnostic, JobRuntimeConfig}; use registry_adapter_core::ADAPTER_JOB_RUNTIME_KIND; -use registry_platform_config::{describe_secret_failure, DeclaredPosture}; +use registry_platform_config::{describe_secret_failure, DatabaseMember, DeclaredPosture}; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, }; @@ -79,8 +79,9 @@ pub(crate) fn load( error.suggested_action(), ) })?; - let resolve = |member: &str, reference: &SecretReference| { - resolver.resolve(reference.as_str()).map_err(|error| { + let resolve = |member: DatabaseMember, reference: &SecretReference| { + let read = member.read(&resolver, reference.as_str()); + read.map_err(|error| { refuse( &format!("/store/{member}"), describe_secret_failure(&format!("store.{member}"), reference.as_str(), &error), @@ -88,7 +89,7 @@ pub(crate) fn load( ) }) }; - let url = |member: &str, reference: &SecretReference| { + let url = |member: DatabaseMember, reference: &SecretReference| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -107,14 +108,15 @@ pub(crate) fn load( btree_gist: false, spatial: None, }, - migration_url: url("migrationUrlRef", migration)?, - runtime_url: url("runtimeUrlRef", &store.runtime_url_ref)?, + migration_url: url(DatabaseMember::MigrationUrl, migration)?, + runtime_url: url(DatabaseMember::RuntimeUrl, &store.runtime_url_ref)?, ca_pem: store .ca_bundle_ref .as_ref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()), transport: provision_transport(&store.database_config()), + explicit_settings: runtime.posture.explicit_setting_notices(), }) } diff --git a/crates/registry-adapterctl/src/provision.rs b/crates/registry-adapterctl/src/provision.rs index 8d10db71a1..3ba29612c9 100644 --- a/crates/registry-adapterctl/src/provision.rs +++ b/crates/registry-adapterctl/src/provision.rs @@ -11,8 +11,8 @@ use registry_adapter_core::{ ADAPTER_RUNTIME_KIND, }; use registry_platform_config::{ - describe_secret_failure, DeclaredPosture, RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, - SecretResolver, + describe_secret_failure, DatabaseMember, DeclaredPosture, RuntimeConfigLoader, RuntimeEnvelope, + SecretProvider, SecretResolver, }; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, @@ -64,6 +64,7 @@ pub(crate) fn load( .removed_keys(ADAPTER_FACADE_REMOVED_KEYS) .load::(&absolute) .map_err(|error| error.diagnostics().to_vec())?; + let explicit_settings = loaded.posture.explicit_setting_notices(); let config = loaded.config; let secrets = match config.secret_providers.as_ref() { Some(providers) => providers.resolver(loaded.development.as_ref()), @@ -77,17 +78,18 @@ pub(crate) fn load( "Correct secretProviders in the runtime file, then run provision again.", ) })?; - let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), describe_secret_failure(&format!("database.{member}"), reference, &error), - "Check the secret provider and that the secret exists, then run provision again.", + error.suggested_action(), ) }) }; - let url = |member: &str, reference: &str| { + let url = |member: DatabaseMember, reference: &str| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -100,13 +102,16 @@ pub(crate) fn load( ) }) }; - let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; - let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let migration_url = url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?; + let runtime_url = url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?; let ca_pem = config .database .ca_bundle_ref .as_deref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); Ok(ProvisionInput { @@ -115,5 +120,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(&config.database), + explicit_settings, }) } diff --git a/crates/registry-adapterctl/tests/job_provision_postgres.rs b/crates/registry-adapterctl/tests/job_provision_postgres.rs index 6fb0afa58d..732fb08edc 100644 --- a/crates/registry-adapterctl/tests/job_provision_postgres.rs +++ b/crates/registry-adapterctl/tests/job_provision_postgres.rs @@ -160,7 +160,6 @@ async fn provision_then_initialize_and_run_with_split_roles() { for (member, name) in [ ("runtimeUrlRef", "runtime-url"), ("migrationUrlRef", "migration-url"), - ("caBundleRef", "ca.pem"), ] { let secret = secrets.join(name); std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o644)).unwrap(); @@ -207,8 +206,12 @@ async fn provision_then_initialize_and_run_with_split_roles() { "the failed initialization committed part of the schema" ); + // A CA bundle is a public document: a world-readable one is read. + let ca_file = secrets.join("ca.pem"); + std::fs::set_permissions(&ca_file, std::fs::Permissions::from_mode(0o644)).unwrap(); let (first, second) = tokio::join!(run(job.clone(), init_args()), run(job.clone(), init_args())); + std::fs::set_permissions(&ca_file, std::fs::Permissions::from_mode(0o600)).unwrap(); assert_eq!(first["ok"], true); assert_eq!(second["ok"], true); diff --git a/crates/registry-breg-review/src/check.rs b/crates/registry-breg-review/src/check.rs index 25d27363bb..ec5f2fa56f 100644 --- a/crates/registry-breg-review/src/check.rs +++ b/crates/registry-breg-review/src/check.rs @@ -154,13 +154,7 @@ fn write_explicit_settings( settings: &[registry_platform_config::FoundExplicitSetting], ) -> std::io::Result<()> { for found in settings { - writeln!( - output, - "Explicit production setting {} at {}. {}.", - found.setting.code, - found.pointer.as_deref().unwrap_or_default(), - found.setting.summary - )?; + writeln!(output, "{}", found.notice())?; } Ok(()) } diff --git a/crates/registry-breg/src/action_evidence_config.rs b/crates/registry-breg/src/action_evidence_config.rs index ef601cf818..f3613baf8d 100644 --- a/crates/registry-breg/src/action_evidence_config.rs +++ b/crates/registry-breg/src/action_evidence_config.rs @@ -95,16 +95,18 @@ pub fn activate( .as_ref() .map(|reference| { secrets - .resolve_reference(reference) + .resolve_public_document_reference(reference) .map(|secret| secret.expose_secret().to_vec()) .map_err(|_| Error::Secret) }) .transpose()?; let token_provider = token_provider(binding, secrets, ca_bundle.as_deref())?; let keys = secrets - .resolve_reference(&binding.trusted_jwks_ref) + .resolve_public_document_reference(&binding.trusted_jwks_ref) .map_err(|_| Error::Secret)?; - let jwks = registry_platform_crypto::parse_json_strict(keys.expose_secret()) + // The key set may be readable by everyone, so it must hold public keys + // only: a private or symmetric member is refused, not loaded. + let jwks = registry_platform_oidc::public_jwks_document(keys.expose_secret()) .map_err(|_| Error::InvalidBinding)?; let jwks = serde_json::from_value(jwks).map_err(|_| Error::InvalidBinding)?; let mut config = registry_evidence_client::EvidenceClientConfig::new( @@ -422,11 +424,36 @@ mod tests { }; assert!(activate( &compiled, - &BTreeMap::from([("farmer-registry".into(), binding)]), + &BTreeMap::from([("farmer-registry".into(), binding.clone())]), &secrets, registry_platform_httputil::PeerPolicy::RefuseDevelopmentPeer, ) .unwrap() .is_some()); + + // The same key set with a private member staged by mistake. + let public = std::fs::read_to_string(directory.path().join("jwks")).unwrap(); + let private = public.replacen( + "\"kty\": \"EC\",", + "\"kty\": \"EC\",\n \"d\": \"AAAA\",", + 1, + ); + assert_ne!(private, public, "the private member is written"); + let path = directory.path().join("private-jwks"); + std::fs::write(&path, private).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let binding = EvidenceProviderConfig { + trusted_jwks_ref: SecretReference::parse("secret:file/private-jwks").unwrap(), + ..binding + }; + assert!(matches!( + activate( + &compiled, + &BTreeMap::from([("farmer-registry".into(), binding)]), + &secrets, + registry_platform_httputil::PeerPolicy::RefuseDevelopmentPeer, + ), + Err(crate::runtime_config::RuntimeConfigError::InvalidBinding) + )); } } diff --git a/crates/registry-breg/src/event_destination.rs b/crates/registry-breg/src/event_destination.rs index f8dd6096cf..146ac86eb7 100644 --- a/crates/registry-breg/src/event_destination.rs +++ b/crates/registry-breg/src/event_destination.rs @@ -17,10 +17,11 @@ use registry_platform_crypto::delivery_signature::{ use registry_platform_hooks::delivery::{UrlDestination, UrlDestinationParts}; use registry_platform_httputil::destination::{ DestinationDnsFamily, DestinationProfile, DestinationTlsMaterial, EventDestinationPolicy, - EventDestinationRequestTemplate, MAX_DESTINATION_PRIVATE_CIDRS, - MAX_DESTINATION_REQUEST_BODY_BYTES, MAX_DESTINATION_REQUEST_HEADER_BYTES, - MAX_DESTINATION_TARGET_BYTES, + EventDestinationRequestTemplate, MAX_DESTINATION_ORIGIN_URL_BYTES, + MAX_DESTINATION_PRIVATE_CIDRS, MAX_DESTINATION_REQUEST_BODY_BYTES, + MAX_DESTINATION_REQUEST_HEADER_BYTES, MAX_DESTINATION_TARGET_BYTES, }; +use registry_platform_httputil::select::{select_destination, TransportClass}; use serde::Deserialize; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; @@ -472,7 +473,7 @@ impl EventDestinationConfig { let policy = EventDestinationPolicy::new_with_dns_family( logical_id, &self.origin, - self.network_profile.platform(), + self.network_profile.select(&self.origin)?, &self.allowed_private_cidrs, self.dns_family.platform(), ) @@ -495,7 +496,7 @@ impl EventDestinationConfig { let ca_bundle = tls .ca_bundle_ref .as_ref() - .map(|reference| secrets.resolve_reference(reference)) + .map(|reference| secrets.resolve_public_document_reference(reference)) .transpose()?; let client_identity = tls .client_identity_ref @@ -632,13 +633,24 @@ impl<'de> Deserialize<'de> for EventDestinationNetworkProfile { } impl EventDestinationNetworkProfile { - fn platform(self) -> DestinationProfile { - match self { - Self::ProductionHttps => DestinationProfile::ProductionHttps, - Self::LoopbackHttp => DestinationProfile::LoopbackHttp, + fn select(self, origin: &str) -> ConfigResult { + let transport = match self { + Self::ProductionHttps => TransportClass::VerifiedTls, + Self::LoopbackHttp => TransportClass::LoopbackPlaintext, #[cfg(feature = "postgres-test")] - Self::PinnedLoopbackHttpsTest => DestinationProfile::PinnedLoopbackHttpsTest, + Self::PinnedLoopbackHttpsTest => { + return Ok(DestinationProfile::PinnedLoopbackHttpsTest) + } + }; + if origin.len() > MAX_DESTINATION_ORIGIN_URL_BYTES { + return Err(EventDestinationConfigError); } + let url = url::Url::parse(origin).map_err(|_| EventDestinationConfigError)?; + // The fixed policy keeps the authored origin and its existing DNS + // address-family and range constraints. + select_destination(&url, Some(transport), &[]) + .map(|selected| selected.profile()) + .map_err(|_| EventDestinationConfigError) } /// The word the binding digest is computed over. The digest is stored @@ -801,3 +813,87 @@ fn canonical_binding_digest(value: &Value) -> Result { canonicalize_json(value).map_err(|_| EventDestinationActivationError::InvalidBinding)?; Ok(format!("sha256:{}", hex::encode(Sha256::digest(canonical)))) } + +#[cfg(test)] +mod tests { + use super::*; + + fn configured_policy( + origin: &str, + profile: &str, + dns_family: &str, + cidrs: &[&str], + ) -> ConfigResult { + let binding = serde_json::from_value(json!({ + "origin": origin, + "path": "/events", + "networkProfile": profile, + "dnsFamily": dns_family, + "allowedPrivateCidrs": cidrs, + "hmacSha256KeyRef": "secret:file/hook-key", + "classificationCeiling": "internal", + "deliveryCeilings": { + "attemptTimeoutMilliseconds": 2500, + "maximumAttempts": 3, + }, + })) + .expect("a well-formed authored binding"); + EventDestinationConfig::from_raw("events", binding)?.platform_binding("events") + } + + #[test] + fn event_bindings_keep_their_configured_dns_family() { + let private_https = configured_policy( + "https://events.example/", + "production-https", + "ipv4-only", + &["10.42.0.0/24"], + ) + .expect("private HTTPS receiver with IPv4-only DNS"); + assert_eq!(private_https.dns_family(), DestinationDnsFamily::Ipv4Only); + + let loopback = configured_policy( + "http://[::1]:8100/", + "loopback-http", + "dual-stack-strict", + &[], + ) + .expect("loopback HTTP receiver"); + assert_eq!(loopback.dns_family(), DestinationDnsFamily::DualStackStrict); + } + + #[test] + fn event_bindings_refuse_mismatched_profiles_and_invalid_origins() { + for (origin, profile) in [ + ("http://10.42.0.2/", "loopback-http"), + ("http://127.0.0.1/", "production-https"), + ("https://127.0.0.1/", "loopback-http"), + ("https://localhost/", "production-https"), + ("https://events.example/unexpected", "production-https"), + ] { + assert!( + configured_policy(origin, profile, "dual-stack-strict", &["10.42.0.0/24"]).is_err(), + "{origin} using {profile}" + ); + } + assert!(configured_policy( + "https://events.example/", + "production-https", + "ipv4-only", + &["fd00::/8"], + ) + .is_err()); + } + + #[cfg(feature = "postgres-test")] + #[test] + fn pinned_test_profile_still_accepts_local_https() { + configured_policy( + "https://localhost:8100/", + "pinned-loopback-https-test", + "dual-stack-strict", + &[], + ) + .expect("native pinned TLS fixture binding"); + } +} diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 9adc280ea2..37725e8c2b 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -545,6 +545,10 @@ pub enum RuntimeConfigError { Secret, #[error("runtime configuration secret file refused: {} ({})", .0.message(), .0.code())] SecretFile(SecretFileCheck), + #[error("runtime configuration public document refused: {} ({})", .0.public_message(), .0.code())] + PublicDocumentFile(SecretFileCheck), + #[error("runtime configuration public document holds a PEM private key block")] + PublicDocumentPrivateKey, } /// The config path of the exposure key a wildcard metrics refusal names. @@ -597,7 +601,10 @@ impl RuntimeConfigError { Self::InvalidBounds => "breg.runtime.invalid-bounds", Self::PoolBudgetExceeded => "breg.runtime.pool-budget-exceeded", Self::InvalidWasmExecution => "breg.runtime.invalid-wasm-execution", - Self::Secret | Self::SecretFile(_) => "breg.runtime.secret", + Self::Secret + | Self::SecretFile(_) + | Self::PublicDocumentFile(_) + | Self::PublicDocumentPrivateKey => "breg.runtime.secret", } } @@ -606,7 +613,11 @@ impl RuntimeConfigError { fn path(&self) -> &str { match self { Self::Reader(refusal) => &refusal.deciding_diagnostic().path, - Self::InvalidBinding | Self::Secret | Self::SecretFile(_) => "", + Self::InvalidBinding + | Self::Secret + | Self::SecretFile(_) + | Self::PublicDocumentFile(_) + | Self::PublicDocumentPrivateKey => "", Self::InvalidExternalSource { path, .. } | Self::InvalidDeliveryKey { path, .. } | Self::DuplicateCompletionRecipient { path, .. } => path, @@ -746,6 +757,10 @@ impl RuntimeConfigError { "Make every secret reference resolve through the declared secret providers." } Self::SecretFile(check) => check.suggested_action(), + Self::PublicDocumentFile(check) => check.public_suggested_action(), + Self::PublicDocumentPrivateKey => { + SecretError::PrivateKeyInPublicDocument.suggested_action() + } } } @@ -818,6 +833,8 @@ impl From for RuntimeConfigError { fn from(error: SecretError) -> Self { match error { SecretError::UnsafeFile(check) => Self::SecretFile(check), + SecretError::UnsafePublicDocument(check) => Self::PublicDocumentFile(check), + SecretError::PrivateKeyInPublicDocument => Self::PublicDocumentPrivateKey, _ => Self::Secret, } } @@ -1748,7 +1765,7 @@ impl RuntimeConfig { .with_attempt_timeout(self.operational_timeouts.http_request) .with_connect_timeout(self.operational_timeouts.http_request); if let Some(reference) = &oauth.ca_bundle_ref { - let ca = resolver.resolve_reference(reference)?; + let ca = resolver.resolve_public_document_reference(reference)?; provider = provider.with_trusted_root_certificates(ca.expose_secret().to_vec()); } Arc::new( @@ -2223,7 +2240,9 @@ impl RuntimeConfig { }; let connection = match &self.database.ca_bundle_ref { Some(roots_ref) => { - let roots = self.secret_resolver()?.resolve_reference(roots_ref)?; + let roots = self + .secret_resolver()? + .resolve_public_document_reference(roots_ref)?; ConnectionConfig::require_tls_config_with_roots_pem( postgres, roots.expose_secret(), @@ -3309,7 +3328,7 @@ impl OidcVerifierConfig { } OidcJwksSource::Static { document_ref } => { let document = resolver - .resolve_reference(document_ref) + .resolve_public_document_reference(document_ref) .map_err(|_| RuntimeConfigError::InvalidOidc)?; if document.is_empty() || u64::try_from(document.len()) diff --git a/crates/registry-bregctl/src/check.rs b/crates/registry-bregctl/src/check.rs index a0386cd661..4de44caf4d 100644 --- a/crates/registry-bregctl/src/check.rs +++ b/crates/registry-bregctl/src/check.rs @@ -100,6 +100,7 @@ pub(super) struct RankedDiagnostic<'a> { } #[derive(Clone, Copy, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub(super) enum FindingRank { WidensAccess, @@ -1301,10 +1302,12 @@ fn explicit_setting_notes(settings: Option<&[registry_cli_report::ExplicitSettin location.push(' '); } format!( - "Explicit production setting {} at {location}{}. {}.\n", - setting.code, - setting.pointer.as_deref().unwrap_or(""), - setting.summary.trim_end_matches('.') + "{}\n", + registry_platform_config::explicit_setting_notice( + &setting.code, + &format!("{location}{}", setting.pointer.as_deref().unwrap_or("")), + setting.summary.trim_end_matches('.'), + ) ) }) .collect() diff --git a/crates/registry-bregctl/src/identity_facts.rs b/crates/registry-bregctl/src/identity_facts.rs index e53df5460b..d359a0f2ad 100644 --- a/crates/registry-bregctl/src/identity_facts.rs +++ b/crates/registry-bregctl/src/identity_facts.rs @@ -565,13 +565,15 @@ fn refuse_unissuable_claim( ))) } -/// Write `facts` to a new file. An existing file is never replaced. -pub(crate) fn write(facts: &IdentityFacts, output: &Path) -> Result<(), FactsError> { +/// Write `facts` to a new file and return the exact YAML written. +/// An existing file is never replaced. +pub(crate) fn write(facts: &IdentityFacts, output: &Path) -> Result { let yaml = facts.to_yaml().map_err(|_| FactsError::Encode)?; let mut file = OpenOptions::new() .write(true) .create_new(true) .open(output) .map_err(FactsError::Write)?; - file.write_all(yaml.as_bytes()).map_err(FactsError::Write) + file.write_all(yaml.as_bytes()).map_err(FactsError::Write)?; + Ok(yaml) } diff --git a/crates/registry-bregctl/src/init_from_model/render.rs b/crates/registry-bregctl/src/init_from_model/render.rs index 7124567959..3c9d39f357 100644 --- a/crates/registry-bregctl/src/init_from_model/render.rs +++ b/crates/registry-bregctl/src/init_from_model/render.rs @@ -65,9 +65,12 @@ fn development_plan(plan: &Plan) -> String { yaml.line(0, "kind: RStackDev"); yaml.entry(0, "issuer", &base_iri(plan)); yaml.line(0, "products:"); - yaml.line(1, "- product: breg"); - yaml.line(2, "project: ."); - yaml.entry(2, "audience", &format!("urn:example:{}", plan.registry_id)); + yaml.line(1, "breg:"); + yaml.line(2, "projects:"); + yaml.line(3, "breg:"); + yaml.line(4, "path: ."); + yaml.line(0, "audiences:"); + yaml.entry(1, "breg", &format!("urn:example:{}", plan.registry_id)); yaml.line(0, "people:"); let callers = [ Some((OPERATOR_PROFILE, operator_principal(plan))), diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 05cb3335ea..064bcde286 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -1965,6 +1965,7 @@ enum ExplainSubject { } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "snake_case")] enum ProfileArg { #[default] @@ -2224,6 +2225,7 @@ where } #[derive(Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct RankedProjectFinding<'a> { #[serde(flatten)] diagnostic: &'a registry_platform_yaml::Diagnostic, @@ -10035,7 +10037,7 @@ fn generate_identity_facts( ) })?; let facts = stated.facts; - identity_facts::write(&facts, &args.output).map_err(|error| { + let yaml = identity_facts::write(&facts, &args.output).map_err(|error| { fail( error.code(), &error.to_string(), @@ -10057,7 +10059,7 @@ fn generate_identity_facts( artifacts: vec![artifact_report( &args.output.display().to_string(), "application/yaml", - facts.to_yaml().unwrap_or_default().as_bytes(), + yaml.as_bytes(), )], explanation: Some(json!({ "identityFacts": { diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs index c0d4680736..a92bdb44e5 100644 --- a/crates/registry-bregctl/src/provision.rs +++ b/crates/registry-bregctl/src/provision.rs @@ -16,6 +16,7 @@ use registry_breg::runtime_config::{ load_runtime_config_without_package_root, RuntimeConfig, RuntimeConfigError, RUNTIME_CONFIG_KIND, }; +use registry_platform_config::DatabaseMember; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, Spatial, }; @@ -92,17 +93,22 @@ pub(crate) fn load( let secrets = config .secret_resolver() .map_err(|error| runtime_file_refused(&absolute, &error))?; - let resolve = |member: &str, reference| { - secrets.resolve_reference(reference).map_err(|_| { + let resolve = |member: DatabaseMember, reference| { + let read = member.read_reference(&secrets, reference); + read.map_err(|error| { refused( "config.refused", &format!("/database/{member}"), - format!("database.{member} could not be read from its secret provider"), - "Check the secret provider and that the secret exists, then run provision again.", + registry_platform_config::describe_secret_failure( + &format!("database.{member}"), + reference.as_str(), + &error, + ), + error.suggested_action(), ) }) }; - let url = |member: &str, reference| { + let url = |member: DatabaseMember, reference| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -116,11 +122,11 @@ pub(crate) fn load( }) }; let database = config.database(); - let migration_url = url("migrationUrlRef", database.migration_url_ref())?; - let runtime_url = url("runtimeUrlRef", database.runtime_url_ref())?; + let migration_url = url(DatabaseMember::MigrationUrl, database.migration_url_ref())?; + let runtime_url = url(DatabaseMember::RuntimeUrl, database.runtime_url_ref())?; let ca_pem = database .ca_bundle_ref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); let spatial = package @@ -138,5 +144,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(database.transport_config()), + explicit_settings: config.posture_report().explicit_setting_notices(), }) } diff --git a/crates/registry-bregctl/src/tool_schema.rs b/crates/registry-bregctl/src/tool_schema.rs index 46c675b886..32a22191e6 100644 --- a/crates/registry-bregctl/src/tool_schema.rs +++ b/crates/registry-bregctl/src/tool_schema.rs @@ -1,22 +1,34 @@ // SPDX-License-Identifier: Apache-2.0 -//! Generated JSON Schemas for the tool files `bregctl` reads. +//! Generated JSON Schemas for BReg tooling contracts. //! -//! Each schema is derived from the types its reader decodes and published -//! with the header the reader checks before decoding them. The committed -//! copies under `products/breg/generated/tools` come from the `tool-schema` -//! example; `products/breg/scripts/check-tool-schemas.sh` fails when they -//! differ from what the reader types generate. +//! Each schema publishes the version and kind a reader checks along with the +//! members it accepts. The committed copies under `products/breg/generated/tools` +//! come from the `tool-schema` example and are checked by +//! `products/breg/scripts/check-tool-schemas.sh`. use std::collections::BTreeMap; use registry_breg::{fixtures, migration_plan}; -use registry_platform_yaml::{EnvelopeRule, FormatSpec, VersionStatus}; +use registry_platform_config::identity_facts::{MAXIMUM_CLAIMS, MAXIMUM_PROFILES}; +use registry_platform_yaml::{ApiVersion, EnvelopeRule, FormatSpec, VersionStatus}; +use schemars::generate::SchemaSettings; use serde_json::{json, Map, Value}; -use crate::{examples, init_from_model, test_lifecycle}; +use crate::{ + examples, init_from_model, test_lifecycle, ProfileArg, RankedProjectFinding, + CTL_REPORT_API_VERSION, CTL_REPORT_KIND, +}; const SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema"; const SCHEMA_ID_BASE: &str = "https://id.registrystack.org/schemas/"; +const CTL_REPORT_FORMAT: FormatSpec<'static> = FormatSpec { + kind: CTL_REPORT_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(CTL_REPORT_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; /// One published tool schema. struct Tool { @@ -28,7 +40,7 @@ struct Tool { members: fn() -> schemars::Schema, } -fn tools() -> [Tool; 6] { +fn tools() -> [Tool; 7] { [ Tool { namespace: "breg", @@ -72,9 +84,108 @@ fn tools() -> [Tool; 6] { spec: migration_plan::MIGRATION_DESCRIPTOR_FORMAT, members: migration_plan::migration_descriptor_schema, }, + Tool { + namespace: "breg", + format: "ctl-report", + title: "Completed BReg identity facts command report", + spec: CTL_REPORT_FORMAT, + members: completed_identity_facts_report_schema, + }, ] } +fn completed_identity_facts_report_schema() -> schemars::Schema { + let mut generator = SchemaSettings::draft2020_12() + .for_serialize() + .into_generator(); + let profile = generator.subschema_for::(); + let diagnostic = generator.subschema_for::>(); + let definitions = generator.take_definitions(true); + let mut schema = json!({ + "type": "object", + "additionalProperties": false, + "description": "The completed report from bregctl generate identity-facts. Validation describes the report structure; its artifact metadata does not establish the path or contents of a file.", + "required": ["ok", "command", "status", "version", "profile", "revision", "posture", "diagnostics", "artifacts", "explanation"], + "properties": { + "ok": {"type": "boolean", "const": true}, + "command": {"type": "string", "const": "generate"}, + "status": {"type": "string", "const": registry_cli_report::Status::Complete.as_str()}, + "version": {"type": "string", "minLength": 1}, + "profile": profile, + "revision": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$", "minLength": 71, "maxLength": 71}, + "posture": { + "type": "object", "additionalProperties": false, + "required": ["value", "source"], + "properties": { + "value": {"type": "string", "enum": ["production", "development"]}, + "source": {"type": "string", "enum": ["default", "environment", "flag"]} + } + }, + "diagnostics": {"type": "array", "items": diagnostic}, + "artifacts": { + "type": "array", "minItems": 1, "maxItems": 1, + "items": { + "type": "object", "additionalProperties": false, + "required": ["path", "mediaType", "byteLength", "sha256"], + "properties": { + "path": {"type": "string", "minLength": 1}, + "mediaType": {"type": "string", "const": "application/yaml"}, + "byteLength": {"type": "integer", "minimum": 1, "maximum": registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$", "minLength": 64, "maxLength": 64} + } + } + }, + "explanation": { + "type": "object", "additionalProperties": false, + "required": ["identityFacts"], + "properties": { + "identityFacts": { + "type": "object", "additionalProperties": false, + "required": ["accessProfiles", "claims"], + "properties": { + "accessProfiles": {"type": "integer", "minimum": 0, "maximum": MAXIMUM_PROFILES}, + "claims": {"type": "integer", "minimum": 0, "maximum": MAXIMUM_CLAIMS} + } + } + } + }, + "nextSteps": {"type": "array", "minItems": 1, "items": {"type": "string"}} + }, + "$defs": definitions + }); + close_diagnostic_objects(&mut schema["$defs"]); + // Positioned findings point into a bounded source or runtime document. + // Coordinates start at one and may point just past its last character. + let maximum_coordinate = registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES + 1; + for definition in ["Source", "Related"] { + let properties = &mut schema["$defs"][definition]["properties"]; + for name in ["line", "column"] { + let coordinate = properties + .get_mut(name) + .expect("diagnostic source defines this coordinate"); + coordinate["minimum"] = json!(1); + coordinate["maximum"] = json!(maximum_coordinate); + } + } + schemars::Schema::try_from(schema).expect("the report schema is an object") +} + +/// Saved reports require exact members even for the shared diagnostic types. +fn close_diagnostic_objects(schema: &mut Value) { + match schema { + Value::Object(object) => { + if object.contains_key("properties") { + object.insert("additionalProperties".to_owned(), Value::Bool(false)); + } + for value in object.values_mut() { + close_diagnostic_objects(value); + } + } + Value::Array(values) => values.iter_mut().for_each(close_diagnostic_objects), + _ => {} + } +} + /// Every tool schema under its committed file name, /// `..schema.json`. pub fn documents() -> Result, serde_json::Error> { @@ -112,9 +223,8 @@ fn current_api_version(spec: &FormatSpec<'static>) -> &'static str { } } -/// The reader checks `apiVersion` and `kind` and removes them before it -/// decodes the members, so the derived schema lacks them; the published one -/// requires both, each with the one value this release reads. +/// Require the envelope in the published schema. The member definition covers +/// the body that remains after the reader checks the version and kind. fn with_header(mut derived: Value, api_version: &str, kind: &str) -> Value { let Value::Object(object) = &mut derived else { unreachable!("a reader type derives an object schema") diff --git a/crates/registry-bregctl/tests/explain_contract.rs b/crates/registry-bregctl/tests/explain_contract.rs index cfb95544c1..cf323b2aa7 100644 --- a/crates/registry-bregctl/tests/explain_contract.rs +++ b/crates/registry-bregctl/tests/explain_contract.rs @@ -1321,7 +1321,7 @@ fn authored_display_examples_pin_every_presentation_surface() { } #[test] -fn registered_ctl_report_example_matches_current_actions_report() { +fn ctl_report_explain_example_matches_current_actions_report() { let root = repo_root(); let registry = format_registry(&root); let registration = registry["formats"] @@ -1330,7 +1330,9 @@ fn registered_ctl_report_example_matches_current_actions_report() { .iter() .find(|format| format["id"] == "breg/ctl-report") .expect("ctl report is registered"); - let path = root.join(registration["example"].as_str().unwrap()); + // The registration's example and schema are the completed identity facts report. + // This explain report shares its apiVersion and kind and is held to current output here. + let path = root.join("products/breg/examples/formats/ctl-report.json"); let bytes = std::fs::read(&path).unwrap(); let example: Value = serde_json::from_slice(&bytes).expect("registered report parses"); assert_eq!(example["apiVersion"], registration["current"]["apiVersion"]); diff --git a/crates/registry-bregctl/tests/identity_facts.rs b/crates/registry-bregctl/tests/identity_facts.rs index 945e5ece46..05ec8c6f38 100644 --- a/crates/registry-bregctl/tests/identity_facts.rs +++ b/crates/registry-bregctl/tests/identity_facts.rs @@ -151,6 +151,191 @@ fn an_existing_output_is_refused_and_left_unchanged() { assert_eq!(std::fs::read_to_string(&output).unwrap(), "keep"); } +#[test] +fn native_inventory_report_matches_the_independently_compiled_external_views_project() { + use std::collections::{BTreeMap, BTreeSet}; + use std::fmt::Write as _; + use std::process::Command; + + use registry_breg::compiler::{compile_project, CompileProfile}; + use registry_breg::contract::parse_project_yaml; + use registry_thunderid_tooling::identity_facts::ClaimType; + use serde_json::{json, Value}; + use sha2::{Digest, Sha256}; + + // The archived witness used a copy of this project. Check the maintained + // source directly so the publisher and witness exercise the same input. + let project = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/breg/examples/external-views") + .canonicalize() + .unwrap(); + let authored = parse_project_yaml(&std::fs::read(project.join("registry.yaml")).unwrap()) + .expect("the donor is readable"); + let compiled = compile_project(&authored, &[], CompileProfile::Authoring) + .expect("the separate compiler produces the donor inventory"); + let scratch = tempfile::tempdir().unwrap(); + let runtime = runtime(scratch.path()); + edit_runtime( + &runtime, + "allowedClients: [generic-registry-client]", + "allowedClients: [officer, restricted, licensing-refresh, staff-app]", + ); + let first = scratch.path().join("first-facts.yaml"); + let second = scratch.path().join("second-facts.yaml"); + let native = |output: &Path| { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(["--format", "json", "generate", "identity-facts"]) + .arg(&project) + .arg("--runtime-config") + .arg(&runtime) + .arg("--output") + .arg(output) + .env_remove("REGISTRY_STACK_POSTURE") + .output() + .expect("native bregctl starts") + }; + let report = |output: &Path| { + let result = native(output); + assert!(result.status.success(), "native writer refused the fixture"); + assert!(result.stderr.is_empty(), "unexpected native writer stderr"); + let mut report: Value = registry_platform_canonical_json::parse_json_strict(&result.stdout) + .expect("the completed report is unique-member JSON"); + assert_eq!(report["kind"], "BRegCtlReport"); + assert_eq!( + report["apiVersion"], + registry_bregctl::CTL_REPORT_API_VERSION + ); + assert_eq!(report["command"], "generate"); + assert_eq!(report["status"], "complete"); + assert_eq!(report["ok"], true); + assert_eq!(report["revision"], compiled.revision()); + #[cfg(feature = "schema")] + { + let schemas = registry_bregctl::tool_schema::documents().unwrap(); + let schema = serde_json::from_str(&schemas["ctl-report.v1alpha1.schema.json"]) + .expect("generated report schema is JSON"); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .expect("generated report schema compiles"); + assert!( + validator.is_valid(&report), + "native report violates its schema" + ); + } + let bytes = std::fs::read(output).unwrap(); + let mut digest = String::new(); + for byte in Sha256::digest(&bytes) { + write!(digest, "{byte:02x}").unwrap(); + } + let artifact = &mut report["artifacts"][0]; + assert_eq!( + *artifact, + json!({ + "path": output, + "byteLength": bytes.len(), + "mediaType": "application/yaml", + "sha256": digest, + }) + ); + artifact["path"] = json!("identity-facts.yaml"); + (bytes, report) + }; + let (facts_bytes, first_report) = report(&first); + assert_eq!((facts_bytes.clone(), first_report.clone()), report(&second)); + let facts = read_facts(&first); + assert_eq!( + first_report["explanation"]["identityFacts"], + json!({"accessProfiles": facts.access_profiles.len(), "claims": facts.claims.len()}) + ); + + let mut expected = BTreeMap::new(); + for entity in compiled.entities().values() { + for profile in entity.access_profiles.values() { + let entry = expected.entry(profile.id.as_str()).or_insert_with(|| { + ( + profile.required_scopes.as_set(), + profile.required_purposes.as_set(), + profile.requester_clients.as_set(), + BTreeSet::new(), + ) + }); + entry.3.insert(profile.principal_claim.as_str()); + entry.3.extend( + profile + .row_boundaries + .iter() + .map(|boundary| boundary.claim.as_str()), + ); + } + } + assert_eq!(facts.access_profiles.len(), expected.len()); + for profile in &facts.access_profiles { + let (scopes, purposes, clients, required_claims) = &expected[profile.id.as_str()]; + assert_eq!( + profile.scopes.iter().cloned().collect::>(), + **scopes + ); + assert_eq!( + profile.purposes.iter().cloned().collect::>(), + **purposes + ); + assert_eq!( + profile + .requester_clients + .iter() + .flatten() + .cloned() + .collect::>(), + **clients, + ); + assert_eq!( + profile + .required_claims + .iter() + .map(String::as_str) + .collect::>(), + *required_claims, + ); + } + let authority = registry_breg::authority::authority_inventory(&compiled).unwrap(); + for (name, claim) in authority.direct_claims { + let kind = if claim.multi_value { + ClaimType::StringArray + } else { + ClaimType::String + }; + assert_eq!(facts.claims[&name], kind); + } + + let schema = serde_json::from_str(include_str!( + "../../../products/platform/schemas/identity-facts.schema.json" + )) + .unwrap(); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + let facts_value = serde_json::to_value(facts).unwrap(); + assert!(validator.is_valid(&facts_value)); + let mut malformed = facts_value; + malformed["unrecognized"] = json!("synthetic-refusal"); + assert!(!validator.is_valid(&malformed)); + assert!(registry_thunderid_tooling::identity_facts::read( + "malformed", + &serde_json::to_vec(&malformed).unwrap(), + ) + .is_err()); + let refusal = native(&first); + assert_eq!(refusal.status.code(), Some(1)); + let refusal = registry_platform_canonical_json::parse_json_strict(&refusal.stdout).unwrap(); + assert_eq!( + refusal["diagnostics"][0]["code"], + "identity-facts.output-exists" + ); + assert_eq!(std::fs::read(first).unwrap(), facts_bytes); +} + #[test] fn an_unrestricted_runtime_states_unrestricted_admission() { let scratch = tempfile::tempdir().unwrap(); diff --git a/crates/registry-bregctl/tests/local_package.rs b/crates/registry-bregctl/tests/local_package.rs index 62802079d4..6e774987e8 100644 --- a/crates/registry-bregctl/tests/local_package.rs +++ b/crates/registry-bregctl/tests/local_package.rs @@ -22,7 +22,7 @@ fn project(root: &std::path::Path, extra: &str) { apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {{product: breg, project: ., audience: registry}}\n\ +products:\n breg: {{projects: {{breg: {{path: .}}}}}}\naudiences:\n breg: registry\n\ people:\n operator:\n subject: operator\n client: operator-client\n roles: [operator]\n\ journeyFile: dev-journeys.yaml\n\ {extra}" diff --git a/crates/registry-bregctl/tests/provision_cli.rs b/crates/registry-bregctl/tests/provision_cli.rs index 1e6b5d67aa..2ae650c75d 100644 --- a/crates/registry-bregctl/tests/provision_cli.rs +++ b/crates/registry-bregctl/tests/provision_cli.rs @@ -11,6 +11,15 @@ use std::process::{Command, Output}; const MIGRATION_PASSWORD: &str = "migration-password-for-print-mode"; const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; +/// The runtime file states `accessTokenType: JWT`, an explicit production +/// setting, so `provision` reports it on stderr and nothing else. +fn assert_only_the_jwt_notice(stderr: &str) { + assert_eq!( + stderr, + "Explicit production setting platform.posture.jwt-access-token at /authentication/oidc/issuers/primary/accessTokenType. Admits access tokens typed JWT. ID tokens stay refused.\n" + ); +} + /// A runtime file whose secret files name a migration and a runtime login on /// one server that does not exist, so a connection attempt could only fail. fn write_runtime(directory: &Path) -> String { @@ -117,7 +126,7 @@ fn print_sql_writes_the_script_and_no_password() { let stdout = String::from_utf8(output.stdout).unwrap(); let stderr = String::from_utf8(output.stderr).unwrap(); assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); - assert!(stderr.is_empty(), "{stderr}"); + assert_only_the_jwt_notice(&stderr); for name in [ "breg_migration", "breg_runtime", @@ -151,7 +160,7 @@ fn print_sql_succeeds_before_the_package_root_exists() { let stdout = String::from_utf8(output.stdout).unwrap(); let stderr = String::from_utf8(output.stderr).unwrap(); assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); - assert!(stderr.is_empty(), "{stderr}"); + assert_only_the_jwt_notice(&stderr); assert!(stdout.contains("CREATE ROLE"), "{stdout}"); } diff --git a/crates/registry-bregctl/tests/tool_schema.rs b/crates/registry-bregctl/tests/tool_schema.rs index 365c9b3737..d4f6bbc454 100644 --- a/crates/registry-bregctl/tests/tool_schema.rs +++ b/crates/registry-bregctl/tests/tool_schema.rs @@ -36,6 +36,10 @@ const EXAMPLES: &[(&str, &str)] = &[ "products/breg/examples/formats/retire-legacy-field-binding.json", ), ("migration-descriptor.v1alpha1.schema.json", DESCRIPTOR), + ( + "ctl-report.v1alpha1.schema.json", + "products/breg/examples/formats/identity-facts-report.json", + ), ]; const DESCRIPTOR: &str = "products/breg/examples/formats/reviewed-migrations/modules/asset-site-placement-core/migrations/read-maintenance-note/descriptor.json"; @@ -79,6 +83,64 @@ fn every_committed_example_satisfies_its_generated_schema() { } } +#[test] +fn identity_facts_report_schema_refuses_other_reports_and_undeclared_members() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["ctl-report.v1alpha1.schema.json"]); + let valid = example("products/breg/examples/formats/identity-facts-report.json"); + for (path, refused) in [ + ("/kind", json!("PlatformIdentityFacts")), + ("/command", json!("check")), + ("/status", json!("domain-refusal")), + ("/ok", json!(false)), + ("/artifacts", json!([])), + ("/artifacts/0/byteLength", json!(-1)), + ("/artifacts/0/sha256", json!("unexpected")), + ("/explanation/identityFacts/accessProfiles", json!("3")), + ("/explanation/identityFacts/accessProfiles", json!(65)), + ( + "/diagnostics/0/source", + json!({"file": "registry.yaml", "extra": true}), + ), + ] { + let mut changed = valid.clone(); + *changed + .pointer_mut(path) + .expect("member is present in fixture") = refused; + assert!(!schema.is_valid(&changed), "accepted a change at {path}"); + } + let mut extra = valid.clone(); + extra["explanation"]["identityFacts"]["unrecognised"] = json!(true); + assert!(!schema.is_valid(&extra)); + let mut missing = valid; + missing.as_object_mut().unwrap().remove("explanation"); + assert!(!schema.is_valid(&missing)); +} + +#[test] +fn identity_facts_report_schema_bounds_document_coordinates() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["ctl-report.v1alpha1.schema.json"]); + let mut report = example("products/breg/examples/formats/identity-facts-report.json"); + report["diagnostics"][0]["related"] = json!([{ + "file": "registry.yaml", "path": "", "message": "Check the project", "line": 1, "column": 1 + }]); + let maximum = registry_platform_yaml::MAXIMUM_DOCUMENT_BYTES + 1; + for path in [ + "/diagnostics/0/source/line", + "/diagnostics/0/source/column", + "/diagnostics/0/related/0/line", + "/diagnostics/0/related/0/column", + ] { + for (coordinate, admitted) in [(0, false), (1, true), (maximum, true), (maximum + 1, false)] + { + let mut changed = report.clone(); + *changed.pointer_mut(path).expect("coordinate exists") = json!(coordinate); + assert_eq!(schema.is_valid(&changed), admitted, "{path}: {coordinate}"); + } + } +} + #[test] fn example_scenario_schema_uses_bounded_display_text() { let documents = documents().expect("the tool schemas generate"); @@ -382,8 +444,9 @@ fn a_wrong_header_a_missing_header_and_an_explicit_null_are_refused() { } /// The identifiers the catalog records, in file-name order. -const IDENTIFIERS: [&str; 6] = [ +const IDENTIFIERS: [&str; 7] = [ "https://id.registrystack.org/schemas/breg/backup-binding/backup-binding.v1alpha1.schema.json", + "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", "https://id.registrystack.org/schemas/breg/example-scenarios/example-scenarios.v1alpha1.schema.json", "https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json", "https://id.registrystack.org/schemas/breg/migration-descriptor/migration-descriptor.v1alpha1.schema.json", diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index 9992084b05..28c15649f8 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -1881,13 +1881,15 @@ async fn issuer_keys( issuer: id.to_owned(), reason, }; - let document = secrets.resolve(document_ref).map_err(|error| { - jwks_secret(describe_secret_failure( - &format!("authentication.oidc.issuers.{id}.jwksSource.documentRef"), - document_ref, - &error, - )) - })?; + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| { + jwks_secret(describe_secret_failure( + &format!("authentication.oidc.issuers.{id}.jwksSource.documentRef"), + document_ref, + &error, + )) + })?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| match error { OidcError::StaticKeySet(refusal) => jwks_secret(refusal.to_string()), diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 85bd647f3c..97817bac20 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -706,13 +706,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-casework/tests/secret_diagnostics.rs b/crates/registry-casework/tests/secret_diagnostics.rs index b349505db4..1f75d4e080 100644 --- a/crates/registry-casework/tests/secret_diagnostics.rs +++ b/crates/registry-casework/tests/secret_diagnostics.rs @@ -110,7 +110,7 @@ mod unix { } #[test] - fn a_group_readable_trusted_root_reference_is_refused_without_the_reference() { + fn a_group_readable_trusted_root_is_read_as_a_public_document() { let root = tempfile::tempdir().expect("temporary secret root"); write_secret(root.path(), "casework-database-url", DATABASE_URL, 0o600); write_secret( @@ -124,16 +124,18 @@ mod unix { config.ca_bundle_ref = Some("secret:file/database-root.pem".to_owned()); let error = PostgresStore::connect_runtime(&config, &secrets, None) - .expect_err("a group-readable certificate file is refused"); + .expect_err("the truncated certificate holds no trusted root"); + // A CA bundle is public: the mode rule does not apply, and the + // refusal comes from the certificate content instead. let message = error.to_string(); assert!( !message.contains("secret:file/database-root.pem"), "the failure repeats the certificate reference: {message}" ); assert!( - message.contains("0400 or 0600"), - "the failure does not name the mode rule: {message}" + !message.contains("0400 or 0600"), + "a public CA bundle was held to the secret mode rule: {message}" ); } } diff --git a/crates/registry-caseworkctl/src/project.rs b/crates/registry-caseworkctl/src/project.rs index d6c7ab1fe8..a9a976f216 100644 --- a/crates/registry-caseworkctl/src/project.rs +++ b/crates/registry-caseworkctl/src/project.rs @@ -145,7 +145,7 @@ reviewPolicies: trustedProducers: requester: profile: requester - issuer: http://127.0.0.1:8093 + issuer: https://identity.casework.example.test subject: b75315b2-5854-70f3-8867-511dd771a6da sourceNamespaces: [standalone] reviewPolicies: [decision] @@ -315,8 +315,7 @@ fn development_plan(project: &CaseworkProject) -> Result<(String, String, String .iter() .find(|profile| profile.acts_as == CaseworkActsAs::Staff) .context("the template needs a staff profile for the development journey")?; - // A logical HTTPS issuer for the run. The starter's producer pins may - // identify a different teaching issuer and stay in the authored policy. + // The logical HTTPS issuer matches the standalone requester binding. let issuer = "https://identity.casework.example.test"; let mut people = BTreeMap::new(); let mut roles = BTreeMap::new(); @@ -350,7 +349,8 @@ fn development_plan(project: &CaseworkProject) -> Result<(String, String, String "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": issuer, - "products": [{"product": "casework", "project": ".", "audience": "urn:example:casework"}], + "products": {"casework": {"path": "."}}, + "audiences": {"casework": "urn:example:casework"}, "people": people, "journeyFile": "dev-journeys.yaml", }))?; @@ -1240,6 +1240,32 @@ pub(super) fn doctor(path: &Path, declared: DeclaredPosture) -> Result { mod display_integrity_tests { use super::*; + #[test] + fn standalone_starter_pins_its_generated_development_requester() { + let root = crate::canonical_tempdir(); + let project_path = root.path().join("project"); + init(&project_path, "standalone-decision").unwrap(); + + let project = load_and_check_policy(&project_path).unwrap(); + let producer = project + .trusted_producers + .iter() + .find(|producer| producer.profile.as_str() == "requester") + .expect("the standalone requester has a producer binding"); + let plan_path = project_path.join("dev.yaml"); + let plan = registry_platform_yaml::Reader::new(plan_path.display().to_string()) + .scan(&fs::read(&plan_path).unwrap()) + .unwrap() + .unwrap() + .to_json_value(); + + assert_eq!(plan["issuer"].as_str(), Some(producer.issuer.as_str())); + assert_eq!( + plan["people"]["requester"]["subject"].as_str(), + Some(producer.subject.as_str()) + ); + } + fn assert_typed_authoring_refusal(error: anyhow::Error) { let (exit, diagnostic) = crate::classify_failure(crate::CommandKind::Authoring, &error); assert_eq!(exit, crate::DOMAIN_REFUSAL_EXIT); diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs index c84aae73fd..d73cef84b7 100644 --- a/crates/registry-caseworkctl/src/provision.rs +++ b/crates/registry-caseworkctl/src/provision.rs @@ -49,6 +49,7 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result Result, #[serde(default, skip_serializing_if = "Option::is_none")] - secret_providers: Option, + secret_providers: Option, auth: SavedAuth, } @@ -544,7 +544,7 @@ fn add(path: &Path, product: &str, mut args: AddConnectionArgs) -> Result<(), Ap } fn saved_auth( - secret_providers: &mut Option, + secret_providers: &mut Option, mut args: AddConnectionArgs, ) -> Result { let choices = usize::from(args.anonymous) @@ -776,7 +776,7 @@ fn secret( } fn resolve_secret( - providers: Option<&SecretProvidersConfig>, + providers: Option<&StrictSecretProvidersConfig>, reference: &SecretReference, ) -> Result { let providers = providers.ok_or(ApiError::Credential)?; @@ -791,7 +791,7 @@ fn resolve_secret( } fn file_reference( - secret_providers: &mut Option, + secret_providers: &mut Option, path: &Path, ) -> Result { let canonical = path @@ -810,7 +810,7 @@ fn file_reference( "the secret file name must use lowercase letters, digits, '.', '_' or '-'".to_owned(), ) })?; - let providers = secret_providers.get_or_insert_with(SecretProvidersConfig::default); + let providers = secret_providers.get_or_insert_with(StrictSecretProvidersConfig::default); match &providers.file { Some(existing) if existing.root != root => { return Err(ApiError::Usage( @@ -819,7 +819,7 @@ fn file_reference( )); } Some(_) => {} - None => providers.file = Some(FileSecretProviderConfig { root }), + None => providers.file = Some(StrictFileSecretProviderConfig { root }), } Ok(reference) } @@ -838,14 +838,14 @@ fn canonical_public_file(path: &Path) -> Result { } fn environment_reference( - secret_providers: &mut Option, + secret_providers: &mut Option, name: &str, ) -> Result { let reference = SecretReference::parse(format!("secret:env/{name}")).map_err(|_| { ApiError::Usage("the token environment variable name is invalid".to_owned()) })?; secret_providers - .get_or_insert_with(SecretProvidersConfig::default) + .get_or_insert_with(StrictSecretProvidersConfig::default) .environment = Some(EnvironmentSecretProviderConfig::default()); Ok(reference) } diff --git a/crates/registry-cli-api/tests/connection_store.rs b/crates/registry-cli-api/tests/connection_store.rs index 9c111e58ba..9f966552a3 100644 --- a/crates/registry-cli-api/tests/connection_store.rs +++ b/crates/registry-cli-api/tests/connection_store.rs @@ -553,3 +553,40 @@ fn saved_connections_add_show_use_reread_credentials_and_acquire_private_key_jwt b"failure" ); } + +#[test] +fn a_saved_connection_file_refuses_the_compose_mount_policy() { + let _lock = ENVIRONMENT_LOCK + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + let temporary = TempDir::new().unwrap(); + let file = temporary.path().join("connections.yaml"); + let strict = "apiVersion: id.registrystack.org/formats/platform/cli-connections/v1alpha1\nkind: PlatformCliConnections\nconnections:\n - product: breg\n name: offline\n baseUrl: https://registry.example.test/api\n secretProviders:\n file:\n root: /run/registry-cli\n auth:\n type: bearer\n tokenRef: secret:file/token\n"; + let check = |text: &str| { + fs::write(&file, text).unwrap(); + run_connection( + "breg", + ConnectionCommand::Check(CheckConnectionArgs { + file: file.clone(), + deny_warnings: false, + }), + ) + }; + check(strict).expect("the strict provider block passes the offline check"); + let stated = strict.replace( + " root: /run/registry-cli\n", + " root: /run/registry-cli\n mountPolicy: compose-native\n", + ); + let error = check(&stated).expect_err("a saved connection file has no mountPolicy"); + assert_eq!(error.exit_code(), 1); + let report = registry_cli_api::inspect_connections_file(&file).unwrap(); + assert!( + report + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "config.unknown-key" + && diagnostic.path == "/connections/0/secretProviders/file/mountPolicy"), + "{}", + report.render_human() + ); +} diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index abb867c811..27384f14fa 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -13563,7 +13563,7 @@ { "name": "check", "invocation": "coordinatorctl check", - "about": "Validate the workflow, functions and root YAML companions offline", + "about": "Validate the workflow, Transforms and root YAML companions offline", "long_about": null, "usage": "coordinatorctl check [OPTIONS]", "arguments": [], @@ -13669,7 +13669,7 @@ { "name": "explain", "invocation": "coordinatorctl explain", - "about": "Explain a checked graph, mappings and execution bounds offline, or the helpers Functions may call", + "about": "Explain a checked graph, mappings and execution bounds offline, or the helpers Transforms may call", "long_about": null, "usage": "coordinatorctl explain [OPTIONS] --project \n coordinatorctl explain ", "arguments": [], @@ -13728,11 +13728,11 @@ "constraints": [], "subcommands": [ { - "name": "functions", - "invocation": "coordinatorctl explain functions", - "about": "List the helpers a pure Function may call, with the interpreter ABI and limits", + "name": "transforms", + "invocation": "coordinatorctl explain transforms", + "about": "List the helpers a pure Transform may call, with the interpreter ABI and limits", "long_about": null, - "usage": "coordinatorctl explain functions [OPTIONS]", + "usage": "coordinatorctl explain transforms [OPTIONS]", "arguments": [], "options": [ { @@ -19399,11 +19399,11 @@ "invocation": "evidencectl check", "about": "Check a normalized project and, when selected, deployment closure, or one tooling file, offline", "long_about": null, - "usage": "evidencectl check [OPTIONS] >", + "usage": "evidencectl check [OPTIONS] |--store-provision-config >", "arguments": [ { "display": "[PROJECT]", - "description": "Editable Evidence project directory. Required unless --file is given", + "description": "Editable Evidence project directory. Required unless --file or --store-provision-config is given", "always_required": false, "repeatable": false, "default_values": [], @@ -19430,6 +19430,24 @@ "possible_values": [], "environment": null }, + { + "display": "--store-provision-config ", + "description": "Check a store provisioning file offline without resolving secrets", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--environment", + "description": "Resolve text substitutions in the provisioning file from the environment", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--target ", "description": "Explicit deployment target whose governance and runtime structure are checked", @@ -19488,7 +19506,15 @@ "when": null, "arguments": [ "[PROJECT]", - "--file " + "--file ", + "--store-provision-config " + ] + }, + { + "kind": "requires-all", + "when": "--environment", + "arguments": [ + "--store-provision-config " ] }, { @@ -19506,6 +19532,14 @@ "--production" ] }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--file ", + "--store-provision-config " + ] + }, { "kind": "mutually-exclusive", "when": null, @@ -19521,6 +19555,30 @@ "--file ", "[PROJECT]" ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--production", + "--store-provision-config " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--store-provision-config ", + "--target " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--store-provision-config ", + "[PROJECT]" + ] } ], "subcommands": [] @@ -23647,6 +23705,112 @@ "constraints": [], "subcommands": [] }, + { + "name": "provision", + "invocation": "evidencectl provision", + "about": "Create split PostgreSQL roles and an empty database for a held Evidence store", + "long_about": null, + "usage": "evidencectl provision [OPTIONS] --runtime-config ", + "arguments": [], + "options": [ + { + "display": "--admin-url-file ", + "description": "File holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--admin-url-env ", + "description": "Name of the environment variable holding the administrator PostgreSQL URL", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--print-sql", + "description": "Print the SQL script and connect to nothing", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--posture ", + "description": "Declared posture: development or production. Unset means production", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--runtime-config ", + "description": "Runtime configuration file for Evidence store provisioning", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format. `junit` is accepted only by `test` and `fixtures run`", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json", + "junit" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [ + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--admin-url-file " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-env ", + "--print-sql" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--admin-url-file ", + "--print-sql" + ] + } + ], + "subcommands": [] + }, { "name": "runtime", "invocation": "evidencectl runtime", @@ -27519,9 +27683,9 @@ { "name": "envoy", "invocation": "registry-session gateway envoy", - "about": "Write or compare the Envoy configuration fragments", + "about": "Generate or verify the Envoy configuration", "long_about": null, - "usage": "registry-session gateway envoy [OPTIONS] <--out |--check |--verify-assembled >", + "usage": "registry-session gateway envoy [OPTIONS] <--out |--check |--verify-assembled |--standalone-out >", "arguments": [], "options": [ { @@ -27551,6 +27715,69 @@ "possible_values": [], "environment": null }, + { + "display": "--route-inventory-out ", + "description": "Write browser paths for the selected Base Registry Engine route from a verified loopback HTTPS assembly", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--checked-route ", + "description": "Select the Base Registry Engine module for the browser route inventory", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--standalone-out ", + "description": "Write one complete Envoy JSON configuration using loopback listeners and upstreams", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--listen
", + "description": "Numeric loopback socket address for Envoy", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--upstream ", + "description": "Numeric loopback socket for one configured module or page cluster. Repeat for each cluster", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--tls-certificate ", + "description": "Absolute filename of the certificate chain for dedicated loopback HTTPS", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--tls-key ", + "description": "Absolute filename of the Envoy TLS private key", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--posture ", "description": "Declared posture: development or production. Unset means production.", @@ -27577,7 +27804,65 @@ "arguments": [ "--out ", "--check ", - "--verify-assembled " + "--verify-assembled ", + "--standalone-out " + ] + }, + { + "kind": "requires-all", + "when": "--route-inventory-out ", + "arguments": [ + "--verify-assembled ", + "--checked-route " + ] + }, + { + "kind": "requires-all", + "when": "--checked-route ", + "arguments": [ + "--verify-assembled ", + "--route-inventory-out " + ] + }, + { + "kind": "requires-all", + "when": "--standalone-out ", + "arguments": [ + "--listen
" + ] + }, + { + "kind": "requires-all", + "when": "--upstream ", + "arguments": [ + "--listen
", + "--standalone-out " + ] + }, + { + "kind": "requires-all", + "when": "--tls-certificate ", + "arguments": [ + "--listen
", + "--standalone-out ", + "--tls-key " + ] + }, + { + "kind": "requires-all", + "when": "--tls-key ", + "arguments": [ + "--standalone-out ", + "--tls-certificate ", + "--listen
" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--check ", + "--listen
" ] }, { @@ -27593,9 +27878,57 @@ "when": null, "arguments": [ "--check ", + "--standalone-out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--check ", + "--upstream " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--check ", + "--verify-assembled " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--listen
", + "--out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--listen
", "--verify-assembled " ] }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--out ", + "--standalone-out " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--out ", + "--upstream " + ] + }, { "kind": "mutually-exclusive", "when": null, @@ -27603,6 +27936,22 @@ "--out ", "--verify-assembled " ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--standalone-out ", + "--verify-assembled " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--upstream ", + "--verify-assembled " + ] } ], "subcommands": [] @@ -29723,14 +30072,14 @@ { "name": "check", "invocation": "rstack dev check", - "about": "Validate a development plan without starting services", + "about": "Validate a development plan or the structure of a saved owner report without starting services", "long_about": null, - "usage": "rstack dev check [OPTIONS] ", + "usage": "rstack dev check [OPTIONS] [PROJECT]", "arguments": [ { - "display": "", + "display": "[PROJECT]", "description": "Project directory containing dev.yaml and, when it declares audiences, service.yaml", - "always_required": true, + "always_required": false, "repeatable": false, "default_values": [], "possible_values": [], @@ -29738,6 +30087,27 @@ } ], "options": [ + { + "display": "--owner-report ", + "description": "Saved JSON report to check structurally", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--owner-report-format ", + "description": "Exact saved document format", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [ + "casework-report", + "breg-identity-facts-report" + ], + "environment": null + }, { "display": "--deny-warnings", "description": "Refuse an unaccepted warning. Development posture listings do not count", @@ -29771,7 +30141,38 @@ "environment": null } ], - "constraints": [], + "constraints": [ + { + "kind": "requires-all", + "when": "--owner-report ", + "arguments": [ + "--owner-report-format " + ] + }, + { + "kind": "requires-all", + "when": "--owner-report-format ", + "arguments": [ + "--owner-report " + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--owner-report ", + "[PROJECT]" + ] + }, + { + "kind": "mutually-exclusive", + "when": null, + "arguments": [ + "--owner-report-format ", + "[PROJECT]" + ] + } + ], "subcommands": [] }, { @@ -29803,7 +30204,7 @@ }, { "display": "--database-url ", - "description": "PostgreSQL administrator URL (verified TLS, or loopback with sslmode=disable). Defaults to RSTACK_DEV_DATABASE_URL; without either, the run starts its own PostgreSQL server in Docker", + "description": "PostgreSQL administrator URL. Defaults to verified TLS. For development, select loopback plaintext with sslmode=disable or private network plaintext with transport=private-network-plaintext. Defaults to RSTACK_DEV_DATABASE_URL; without either, the run starts its own PostgreSQL server in Docker", "always_required": false, "repeatable": false, "default_values": [], @@ -30046,7 +30447,7 @@ }, { "display": "--database-url ", - "description": "PostgreSQL administrator URL for --recover (verified TLS, or loopback with sslmode=disable). Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own server needs none", + "description": "The same PostgreSQL administrator URL used at start, including its transport choice. Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own server needs none", "always_required": false, "repeatable": false, "default_values": [], diff --git a/crates/registry-cli-docs/src/lib.rs b/crates/registry-cli-docs/src/lib.rs index 7bcd41c234..822423ccb2 100644 --- a/crates/registry-cli-docs/src/lib.rs +++ b/crates/registry-cli-docs/src/lib.rs @@ -1108,7 +1108,12 @@ mod tests { let evidencectl_check = find_command(&catalog.binaries, "evidencectl check"); assert!(evidencectl_check.constraints.iter().any(|constraint| { constraint.kind == ConstraintKind::RequiredExactlyOne - && constraint.arguments == ["[PROJECT]", "--file "] + && constraint.arguments + == [ + "[PROJECT]", + "--file ", + "--store-provision-config ", + ] })); let mock_serve = find_command(&catalog.binaries, "evidencectl source mock serve"); diff --git a/crates/registry-cli-report/src/lib.rs b/crates/registry-cli-report/src/lib.rs index 991655380e..eb1daa70e0 100644 --- a/crates/registry-cli-report/src/lib.rs +++ b/crates/registry-cli-report/src/lib.rs @@ -3,7 +3,7 @@ use std::io::{self, Write}; -use registry_platform_config::FoundExplicitSetting; +pub use registry_platform_config::ExplicitSettingLine; #[doc(hidden)] pub use registry_platform_posture::declared_from; /// The declaration used by CLI report producers. @@ -79,62 +79,6 @@ pub struct Report<'a> { explicit_settings: Option>, } -/// One explicit production setting an operator stated, as a `check` report -/// lists it: a setting valid in every posture that relaxes something and is -/// worth a reviewer's attention. It is a list of facts, not a diagnostic, so -/// `--deny-warnings` is unaffected. The summary is value-free. -/// -/// `file` names the document `pointer` refers to, such as the runtime file or -/// the package, and is left out when absent. `pointer`, `line` and `column` -/// are left out when unknown. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct ExplicitSettingLine { - pub code: String, - pub file: Option, - pub pointer: Option, - pub line: Option, - pub column: Option, - pub summary: String, -} - -impl ExplicitSettingLine { - /// The line a `check` report lists for `found`. `file` names the document - /// the pointer refers to: the runtime file, or the package for a setting - /// found there. - #[must_use] - pub fn from_found(found: &FoundExplicitSetting, file: Option<&str>) -> Self { - Self { - code: found.setting.code.to_owned(), - file: file.map(ToOwned::to_owned), - pointer: found.pointer.clone(), - line: found.position.map(|position| position.line), - column: found.position.map(|position| position.column), - summary: found.setting.summary.to_owned(), - } - } -} - -impl Serialize for ExplicitSettingLine { - fn serialize(&self, serializer: S) -> Result { - let mut map = serializer.serialize_map(None)?; - map.serialize_entry("code", &self.code)?; - if let Some(file) = &self.file { - map.serialize_entry("file", file)?; - } - if let Some(pointer) = &self.pointer { - map.serialize_entry("pointer", pointer)?; - } - if let Some(line) = self.line { - map.serialize_entry("line", &line)?; - } - if let Some(column) = self.column { - map.serialize_entry("column", &column)?; - } - map.serialize_entry("summary", &self.summary)?; - map.end() - } -} - impl<'a> Report<'a> { /// Check the product's envelope and attach the binary's build identity. /// Command-specific status words become outcomes; result classes stay fixed. diff --git a/crates/registry-coordinator-client/src/client.rs b/crates/registry-coordinator-client/src/client.rs index 2a17003fcc..7ac0020be3 100644 --- a/crates/registry-coordinator-client/src/client.rs +++ b/crates/registry-coordinator-client/src/client.rs @@ -121,7 +121,9 @@ impl CoordinatorClient { return Err(Error::invalid_request("the workflow identifier is invalid")); } if key.is_empty() || key.len() > 256 || !key.bytes().all(|b| (0x20..=0x7e).contains(&b)) { - return Err(Error::invalid_request("the admission key is invalid")); + return Err(Error::invalid_request( + "Idempotency-Key must contain 1 to 256 printable ASCII characters", + )); } if !valid_revision(&request.workflow_revision) { return Err(Error::invalid_request("the workflow revision is invalid")); diff --git a/crates/registry-coordinator-client/tests/http.rs b/crates/registry-coordinator-client/tests/http.rs index 679e8c136c..717ed310c9 100644 --- a/crates/registry-coordinator-client/tests/http.rs +++ b/crates/registry-coordinator-client/tests/http.rs @@ -1423,11 +1423,14 @@ async fn invalid_admission_and_recovery_fail_before_io() { "", "contains\tcontrol", "injected\r\nheader", + "mañana", &"a".repeat(257), ] { assert!(matches!( client.start(&token(), key, &request()).await, - Err(CoordinatorClientError::InvalidRequest { .. }) + Err(CoordinatorClientError::InvalidRequest { + reason: "Idempotency-Key must contain 1 to 256 printable ASCII characters", + }) )); } let mut input = request(); diff --git a/crates/registry-coordinator/src/access.rs b/crates/registry-coordinator/src/access.rs index ecad3c0531..f68377dbdf 100644 --- a/crates/registry-coordinator/src/access.rs +++ b/crates/registry-coordinator/src/access.rs @@ -717,7 +717,7 @@ impl IssuerConfig { let value = secrets .resolver(development) .map_err(|_| refused())? - .resolve(document_ref) + .resolve_public_document(document_ref) .map_err(|_| refused())?; Arc::new(JwksFetcher::new_static( parse_static_jwks(value.expose_secret()).map_err(|error| match error { diff --git a/crates/registry-coordinator/src/access/token_characterisation.rs b/crates/registry-coordinator/src/access/token_characterisation.rs index 8773788073..dd4c0a4438 100644 --- a/crates/registry-coordinator/src/access/token_characterisation.rs +++ b/crates/registry-coordinator/src/access/token_characterisation.rs @@ -213,7 +213,9 @@ fn static_secrets(root: &std::path::Path, signer: &TokenSigner) -> SecretProvide .expect("owner-only key file"); } SecretProvidersConfig { - file: Some(registry_platform_config::FileSecretProviderConfig { root: root_path }), + file: Some(registry_platform_config::FileSecretProviderConfig::new( + root_path, + )), environment: None, } } diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index 3c7d9aa169..b49efd6559 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -64,6 +64,8 @@ enum Connection { Payments(Box), Casework(Box), External(Box), + /// One bound service function, reached only by `service.invoke-function/v1`. + ServiceFunction(Box), Decision(Box), } @@ -109,20 +111,13 @@ fn config_error() -> CoordinatorError { // Destinations are explicit, reviewed deployment bindings. Institutional peers // may use private HTTPS networks; all token requests remain DNS-pinned and -// reject metadata addresses. Cleartext remains numeric loopback only. +// reject metadata addresses. Cleartext remains numeric loopback only. An +// endpoint the Coordinator would not admit gets the strict policy, which +// refuses it again at request time. fn configured_endpoint_policy(endpoint: &Url) -> FetchUrlPolicy { - if endpoint.scheme() == "http" { - FetchUrlPolicy::https_or_loopback() - } else { - FetchUrlPolicy { - allowed_schemes: vec!["https".into()], - allow_localhost: true, - allow_http_private_network: false, - allow_http_non_loopback: false, - deny_private_ranges: false, - deny_cloud_metadata: true, - } - } + crate::outbound::select_endpoint(endpoint).map_or_else(FetchUrlPolicy::strict, |selected| { + crate::outbound::fetch_policy(&selected) + }) } fn tokens( @@ -190,6 +185,7 @@ impl HttpAdapters { .resolver(config.development.as_ref()) .map_err(|_| config_error())?, ); + distinct_function_keys(config, &secrets)?; let mut connections = BTreeMap::new(); for (name, configured) in &config.connections { if let Some(binding) = configured.external_http() { @@ -213,6 +209,45 @@ impl HttpAdapters { connections.insert(name.clone(), Connection::External(Box::new(connection))); continue; } + if let Some(binding) = configured.service_function() { + let provider: Arc = + match (&binding.authorization, &binding.host_key_ref) { + (Some(auth), None) => { + let key_bytes = secrets + .resolve_reference(&auth.signing_key_ref) + .map_err(|_| config_error())?; + let key_text = std::str::from_utf8(key_bytes.expose_secret()) + .map_err(|_| config_error())?; + let key = PrivateJwk::parse(key_text).map_err(|_| config_error())?; + Arc::new( + tokens(auth, key, &auth.resource, &auth.scopes) + .map_err(|_| config_error())?, + ) + } + (None, Some(reference)) => { + let key = secrets + .resolve_reference(reference) + .map_err(|_| config_error())?; + let text = std::str::from_utf8(key.expose_secret()) + .map_err(|_| config_error())?; + Arc::new( + registry_platform_httputil::client::StaticToken::new( + text.trim_end_matches('\n'), + ) + .map_err(|_| config_error())?, + ) + } + _ => return Err(config_error()), + }; + let connection = crate::external_http::ExternalHttpConnection::service_function( + binding, provider, + )?; + connections.insert( + name.clone(), + Connection::ServiceFunction(Box::new(connection)), + ); + continue; + } if let Some(binding) = configured.decision() { let connection = crate::decision::DecisionConnection::new(binding, Arc::clone(&secrets))?; @@ -423,6 +458,70 @@ impl HttpAdapters { } } +/// A service function host never holds a key this runtime file gives +/// something else, even under another secret reference: a JWK is compared by +/// its RFC 7638 thumbprint, any other key by a digest of its bytes. The +/// refusal names the two locations and no key value. +fn distinct_function_keys( + config: &RuntimeConfig, + secrets: ®istry_platform_config::SecretResolver, +) -> Result<()> { + use sha2::Digest as _; + // Key files may hold binary material with NUL bytes, so compare bytes. + let identity = |reference: ®istry_platform_config::SecretReference| -> Result { + let secret = secrets + .resolve_binary_reference(reference) + .map_err(|_| config_error())?; + let bytes = secret.expose_secret(); + let jwk = std::str::from_utf8(bytes) + .ok() + .and_then(|text| PrivateJwk::parse(text).ok()) + .and_then(|key| key.public().jkt().ok()); + // A host key is sent without its trailing newlines, so bytes compare + // in that form: a file differing only by them holds the same key. + let trimmed = bytes + .iter() + .rposition(|byte| *byte != b'\n') + .map_or(&bytes[..0], |last| &bytes[..=last]); + Ok(match jwk { + Some(thumbprint) => format!("jwk:{thumbprint}"), + None => format!("bytes:{}", hex::encode(sha2::Sha256::digest(trimmed))), + }) + }; + let mut functions = Vec::new(); + for (name, configured) in &config.connections { + if let Some(function) = configured.service_function() { + for reference in function + .authorization + .as_ref() + .map(|auth| &auth.signing_key_ref) + .into_iter() + .chain(function.host_key_ref.as_ref()) + { + functions.push((name, identity(reference)?)); + } + } + } + if functions.is_empty() { + return Ok(()); + } + let mut others = Vec::new(); + for (location, reference) in config.other_key_references() { + others.push((location, identity(reference)?)); + } + for (function, key) in &functions { + if let Some((other, _)) = others.iter().find(|(_, value)| value == key) { + return Err(CoordinatorError::new( + "coordinator.runtime-config.refused", + format!("connection {function} and {other} resolve to the same key; a service function host must hold a key nothing else in this runtime uses"), + ) + .at("runtime.yaml", format!("/connections/{function}")) + .suggest(format!("Give connections.{function} its own key, distinct from {other}."))); + } + } + Ok(()) +} + pub(crate) fn refused(code: &str) -> CallOutcome { CallOutcome::Refused { code: code.to_owned(), @@ -1088,6 +1187,16 @@ impl AdapterSet for HttpAdapters { }; connection.command(&request.input, key, final_attempt).await } + ( + Some(Connection::ServiceFunction(connection)), + Operation::InvokeServiceFunction, + None, + ) => { + let Some(key) = &request.idempotency_key else { + return refused("invalid-command"); + }; + connection.command(&request.input, key, final_attempt).await + } _ => self.call_prepared(request, prepared).await, } } @@ -1103,6 +1212,12 @@ impl AdapterSet for HttpAdapters { }; connection.command(&request.input, key, false).await } + (Some(Connection::ServiceFunction(connection)), Operation::InvokeServiceFunction) => { + let Some(key) = &request.idempotency_key else { + return refused("invalid-command"); + }; + connection.command(&request.input, key, false).await + } ( Some(Connection::Breg { client, options, .. @@ -2010,5 +2125,21 @@ mod tests { assert!(configured_endpoint_policy(&cleartext) .validate_dns_pinned_for_immediate_fetch(&cleartext) .is_err()); + for loopback in ["http://127.0.0.1:9999/token", "http://[::1]:9999/token"] { + let loopback: Url = loopback.parse().unwrap(); + assert!(configured_endpoint_policy(&loopback) + .validate_dns_pinned_for_immediate_fetch(&loopback) + .is_ok()); + } + for refused in [ + "https://[::ffff:169.254.169.254]/token", + "https://169.254.1.1/token", + "http://localhost:9999/token", + ] { + let refused: Url = refused.parse().unwrap(); + assert!(configured_endpoint_policy(&refused) + .validate_dns_pinned_for_immediate_fetch(&refused) + .is_err()); + } } } diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index 16df88a480..05af11f6fd 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -45,16 +45,19 @@ const FORMAT: FormatSpec<'static> = FormatSpec { RemovedKey { pointer: "/title", replacement: "Write project.label." }, RemovedKey { pointer: "/label", replacement: "Move label to project.label." }, RemovedKey { pointer: "/description", replacement: "Move description to project.description." }, - RemovedKey { pointer: "/functions/*/title", replacement: "Write label." }, + RemovedKey { pointer: "/functions", replacement: "Rename functions to transforms, then replace each type: function and function member with type: transform and transform." }, + RemovedKey { pointer: "/transforms/*/title", replacement: "Write label." }, + RemovedKey { pointer: "/workflow/steps/*/*/function", replacement: "Write type: transform and name the Transform in the transform member." }, + RemovedKey { pointer: "/workflow/eventTriggers/*/input/function", replacement: "Write type: transform and name the Transform in the transform member." }, RemovedKey { pointer: "/operations/*/title", replacement: "Write label." }, RemovedKey { pointer: "/workflow/steps/*/title", replacement: "Write label." }, RemovedKey { pointer: "/connections", replacement: "Declare logical connections on Operation aliases under operations, then bind them in runtime.yaml." }, - RemovedKey { pointer: "/functionsFile", replacement: "Declare named typed Functions under functions, each with its source asset." }, + RemovedKey { pointer: "/functionsFile", replacement: "Declare named typed Transforms under transforms, each with its source asset." }, RemovedKey { pointer: "/deadlineSeconds", replacement: "Move deadlineSeconds to workflow.deadlineSeconds." }, RemovedKey { pointer: "/start", replacement: "Move start to workflow.start." }, RemovedKey { pointer: "/steps", replacement: "Move steps to workflow.steps and use Operation aliases." }, RemovedKey { pointer: "/outcomes", replacement: "Move outcomes to workflow.outcomes." }, - RemovedKey { pointer: "/workflow/steps/*/*/arguments", replacement: "Use inputs with the Function signature's named references." }, + RemovedKey { pointer: "/workflow/steps/*/*/arguments", replacement: "Use inputs with the Transform signature's named references." }, ], }; @@ -74,7 +77,7 @@ pub struct CoordinatorProject { types: BTreeMap, /// Named typed bounded pure computations over one object of named inputs. #[serde(default)] - functions: BTreeMap, + transforms: BTreeMap, /// Local aliases for exact versioned host Operations and logical deployment connections. #[serde(default)] operations: BTreeMap, @@ -160,13 +163,21 @@ struct AuthoredOperation { /// Fix a Messaging template version, its locales and its data schema. #[serde(default)] template: Option, + /// The one service function `service.invoke-function/v1` calls. Required + /// on, and accepted only on, that Operation. `check` matches it against + /// the function the runtime connection binds; `rstack dev` also checks it + /// against `service.yaml`. The runtime connection binds the host and + /// credential, and the workflow supplies neither. + #[serde(default)] + service_function: Option, /// An optional typed response specialization for the bounded external GET - /// or external command Operation. + /// or external command Operation, or the service function Operation. #[serde(default)] response_schema: Option, - /// The typed pure Function that interprets an external command's provider + /// The typed pure Transform that interprets an external command's provider /// response into an accepted result, a declared refusal or an uncertain - /// outcome. Required on, and accepted only on, `external.command/v1`. + /// outcome. Required on, and accepted only on, `external.command/v1` and + /// `service.invoke-function/v1`. #[serde(default)] interpret: Option, /// Named bounded completion contracts; the host enforces their observation semantics. @@ -194,7 +205,7 @@ struct AuthoredOperation { enum AuthoredCompletion { /// Repeats the accepted read under host-owned transport and credentials. BoundedPoll { - /// The typed pure Function that turns the saved command and response into an observation. + /// The typed pure Transform that turns the saved command and response into an observation. interpret: LocalId, /// Seconds between pending observations; the host may impose a stricter minimum. interval_seconds: BoundedU32<1, 86_400>, @@ -205,16 +216,16 @@ registry_platform_yaml::tagged_union!(AuthoredCompletion); #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -struct AuthoredFunction { +struct AuthoredTransform { /// The pinned pure runtime; rhai has no clock, network, database or credential capability. - runtime: FunctionRuntime, + runtime: TransformRuntime, /// A local reviewed source asset inside the project directory. source: String, /// One public source function taking exactly one named-input object. entrypoint: String, /// Named input schemas or references; every declared input is required exactly once. inputs: BTreeMap, - /// The declared result schema or mapping; Functions and the host enforce it. + /// The declared result schema or mapping; Transforms and the host enforce it. output: Schema, /// Optional narrowing of the bounded pure profile; omitted limits retain the default ceiling. #[serde(default)] @@ -232,7 +243,7 @@ struct AuthoredFunction { #[derive(Debug, Deserialize)] #[serde(rename_all = "kebab-case")] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -enum FunctionRuntime { +enum TransformRuntime { Rhai, } @@ -424,7 +435,7 @@ enum Member { /// A literal JSON value; it remains subject to bounded value checks. value: ForeignValue, }, - /// Builds a nested object member by member, never with a Function. + /// Builds a nested object member by member, never with a Transform. Fields { /// Object members built from typed references, literals or nested fields. fields: Fields, @@ -442,10 +453,10 @@ registry_platform_yaml::tagged_union!(Member); #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] enum AuthoredMapping { - /// Computes a value with a declared typed pure Function. - Function { - /// A declared pure Function called with an object of named inputs. - function: LocalId, + /// Computes a value with a declared typed pure Transform. + Transform { + /// A declared pure Transform called with an object of named inputs. + transform: LocalId, /// Named input schemas or references; every declared input is required exactly once. inputs: BTreeMap, }, @@ -617,7 +628,7 @@ enum AuthoredStep { Finish { /// One declared terminal outcome name. outcome: LocalId, - /// The declared result schema or mapping; Functions and the host enforce it. + /// The declared result schema or mapping; Transforms and the host enforce it. #[serde(default)] output: Option, /// An optional human label; it changes neither stable identity nor behavior revision. @@ -799,9 +810,9 @@ impl From for crate::compare::Condition { impl From for Mapping { fn from(mapping: AuthoredMapping) -> Self { let reference = match mapping { - AuthoredMapping::Function { function, inputs } => { + AuthoredMapping::Transform { transform, inputs } => { return Self::Function { - function: function.into_string(), + function: transform.into_string(), inputs: inputs .into_iter() .map(|(id, reference)| (id.into_string(), reference.into())) @@ -855,7 +866,7 @@ pub(crate) fn asset_path(root: &Path, asset: &str) -> Result CoordinatorError::new("definition.read", "the project asset is unavailable") .with_exit(3) .suggest( - "Restore the named generated contract or Function source asset inside the project.", + "Restore the named generated contract or Transform source asset inside the project.", ) })?; if !candidate.starts_with(&root) || !candidate.is_file() { @@ -960,8 +971,8 @@ fn project_integrity_diagnostics( map_ids("/types", &project.types), ), ( - "coordinator.project.function-id-collision", - map_ids("/functions", &project.functions), + "coordinator.project.transform-id-collision", + map_ids("/transforms", &project.transforms), ), ( "coordinator.project.operation-id-collision", @@ -1002,13 +1013,13 @@ fn project_integrity_diagnostics( ), )); } - for (id, function) in &project.functions { + for (id, function) in &project.transforms { errors.extend(collisions( document, - "coordinator.project.function-input-id-collision", + "coordinator.project.transform-input-id-collision", &map_ids( &format!( - "/functions/{}/inputs", + "/transforms/{}/inputs", registry_platform_yaml::escape_pointer_segment(id.as_str()) ), &function.inputs, @@ -1054,15 +1065,15 @@ fn project_integrity_diagnostics( let groups = [ ( - "coordinator.project.duplicate-function-label", - "functions", + "coordinator.project.duplicate-transform-label", + "transforms", project - .functions + .transforms .iter() .filter_map(|(id, item)| { item.label.as_ref().map(|label| { let pointer = format!( - "/functions/{}/label", + "/transforms/{}/label", registry_platform_yaml::escape_pointer_segment(id.as_str()) ); (id.as_str().to_owned(), label.clone(), pointer) @@ -1277,31 +1288,54 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { &imported, ) .map_err(|error| error.at("workflow.yaml", contract_field))?; + match ( + uses == Operation::InvokeServiceFunction, + &operation.service_function, + ) { + (true, None) => { + return Err(schema_error( + format!("/operations/{id}/serviceFunction"), + "service.invoke-function/v1 requires serviceFunction: the one function this Operation calls, which its runtime connection must bind", + )); + } + (false, Some(_)) => { + return Err(schema_error( + format!("/operations/{id}/serviceFunction"), + "only service.invoke-function/v1 accepts a serviceFunction", + )); + } + _ => {} + } if operation.response_schema.is_some() - && !matches!(uses, Operation::ExternalGet | Operation::ExternalCommand) + && !matches!( + uses, + Operation::ExternalGet + | Operation::ExternalCommand + | Operation::InvokeServiceFunction + ) { return Err(schema_error( format!("/operations/{id}/responseSchema"), - "only the bounded external GET and external command profiles accept a response specialization", + "only the bounded external GET, external command and service function profiles accept a response specialization", )); } - match (uses, operation.interpret) { - (Operation::ExternalCommand, Some(interpret)) => { + match (uses.interprets_response(), operation.interpret) { + (true, Some(interpret)) => { command_interpreters.insert(id.clone(), interpret); } - (Operation::ExternalCommand, None) => { + (true, None) => { return Err(schema_error( format!("/operations/{id}/interpret"), - "external.command/v1 requires interpret: the Function that turns the provider response into an accepted result, a declared refusal or an uncertain outcome", + &format!("{} requires interpret: the Transform that turns the provider response into an accepted result, a declared refusal or an uncertain outcome", uses.as_str()), )); } - (_, Some(_)) => { + (false, Some(_)) => { return Err(schema_error( format!("/operations/{id}/interpret"), - "only external.command/v1 accepts an interpretation Function", + "only external.command/v1 and service.invoke-function/v1 accept an interpretation Transform", )); } - (_, None) => {} + (false, None) => {} } let mut completions = BTreeMap::new(); if uses == Operation::SubmitReviewRequest { @@ -1360,13 +1394,14 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { revision: String::new(), interpret: None, response: None, + service_function: operation.service_function.map(LocalId::into_string), action: contract.action, label: operation.label, description: operation.description, }, ); } - // Base operation schemas resolve before Function signatures. No completion + // Base operation schemas resolve before Transform signatures. No completion // output may take part in that graph, so a completion cannot define itself. let raw_operations = operations.clone(); let resolver = Schemas { @@ -1385,8 +1420,8 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { .transpose()?; } let base = operations.clone(); - // Interpretation Functions can see only resolved base Operation schemas - // and host-owned completions. Downstream Functions resolve after bounded + // Interpretation Transforms can see only resolved base Operation schemas + // and host-owned completions. Downstream Transforms resolve after bounded // completion bindings, so ordinary mappings can consume their typed output. let resolver = Schemas { types: &raw_types, @@ -1407,7 +1442,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { .collect::>(); let mut functions = BTreeMap::new(); let mut downstream = Vec::new(); - for (id, function) in project.functions { + for (id, function) in project.transforms { if interpreters.contains(id.as_str()) { functions.insert( id.as_str().to_owned(), @@ -1425,16 +1460,19 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { .expect("the base alias exists"); let field = format!("/operations/{operation_id}/interpret"); let function = functions.get(interpret.as_str()).ok_or_else(|| { - schema_error(field.clone(), "the interpretation Function is not declared") + schema_error( + field.clone(), + "the interpretation Transform is not declared", + ) })?; if function.inputs.len() != 2 || function.inputs.get("command") != Some(&operation.input) || function.inputs.get("response") != Some(&operation.output) { - return Err(schema_error(field, "the interpretation Function must take command and response with the command's exact input and response schemas")); + return Err(schema_error(field, "the interpretation Transform must take command and response with the command's exact input and response schemas")); } let (output, refusal) = - command_interpretation(&function.output, &format!("/functions/{interpret}/output"))?; + command_interpretation(&function.output, &format!("/transforms/{interpret}/output"))?; operation.response = Some(std::mem::replace(&mut operation.output, output)); operation.refusal = refusal; operation.interpret = Some(interpret.into_string()); @@ -1464,17 +1502,17 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { let function = functions.get(interpret.as_str()).ok_or_else(|| { schema_error( format!("/operations/{operation_id}/completions/{name}/interpret"), - "the interpretation Function is not declared", + "the interpretation Transform is not declared", ) })?; if function.inputs.len() != 2 || function.inputs.get("command") != Some(&operation.input) || function.inputs.get("response") != Some(&operation.output) { - return Err(schema_error(format!("/operations/{operation_id}/completions/{name}/interpret"), "the interpretation Function must take command and response with the owning Operation's exact schemas")); + return Err(schema_error(format!("/operations/{operation_id}/completions/{name}/interpret"), "the interpretation Transform must take command and response with the owning Operation's exact schemas")); } let output = - terminal_schema(&function.output, &format!("/functions/{interpret}/output"))?; + terminal_schema(&function.output, &format!("/transforms/{interpret}/output"))?; operation.completions.insert( name, CompletionDefinition { @@ -1755,7 +1793,7 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { fn resolve_function( id: &str, - function: AuthoredFunction, + function: AuthoredTransform, resolver: &Schemas<'_>, ) -> Result { let _runtime = function.runtime; @@ -1767,14 +1805,14 @@ fn resolve_function( resolver .resolve( &schema.0.into_value(), - &format!("/functions/{id}/inputs/{name}"), + &format!("/transforms/{id}/inputs/{name}"), ) .map(|schema| (name, schema)) }) .collect::>>()?; let output = resolver.resolve( &function.output.0.into_value(), - &format!("/functions/{id}/output"), + &format!("/transforms/{id}/output"), )?; Ok(FunctionDefinition { runtime: "rhai".into(), @@ -1816,8 +1854,8 @@ fn reference_sites(document: &Document) -> BTreeMap { - Some(format!("/functions/{id}")) + ("transform" | "interpret", Some(id)) if !schema => { + Some(format!("/transforms/{id}")) } ( "next" | "onTimeout" | "onCancel" | "onDeclaredRefusal" | "step", @@ -1851,7 +1889,7 @@ fn reference_sites(document: &Document) -> BTreeMap { Some(format!("asset:{asset}")) @@ -1936,8 +1974,8 @@ fn reference_sites(document: &Document) -> BTreeMap Result<()> { } /// The step output and declared refusal an external command's interpretation -/// establishes. The Function returns one closed object per state: `accepted` +/// establishes. The Transform returns one closed object per state: `accepted` /// with a required `result`, and optionally `refused` with a required closed /// enum `code` and `uncertain`. The step output is the accepted result, still /// bound to the interpretation's own local definitions; the refusal admits only @@ -2385,10 +2423,10 @@ pub(crate) fn positioned(document: &Document, error: CoordinatorError) -> Coordi } // A function's own definition is placed in functions.rhai; a function // that fails while a step evaluates it is placed at that step. - if error.code.starts_with("function.") + if error.code.starts_with("transform.") && !matches!( error.code.as_str(), - "function.value-limit" | "function.json" + "transform.value-limit" | "transform.json" ) && error.file.as_deref().map(std::path::PathBuf::as_path) != Some(Path::new("workflow.yaml")) @@ -2490,7 +2528,7 @@ pub fn project_schema() -> std::result::Result { maps(&mut schema); for (pointer, minimum, maximum) in [ ("/properties/operations", 0, 64), - ("/properties/functions", 0, 128), + ("/properties/transforms", 0, 128), ("/properties/types", 0, 128), ("/$defs/AuthoredWorkflow/properties/eventTriggers", 0, 16), ("/$defs/AuthoredWorkflow/properties/calendarTriggers", 0, 1), @@ -2510,13 +2548,13 @@ pub fn project_schema() -> std::result::Result { if variant .pointer("/properties/type/const") .and_then(Value::as_str) - == Some("function") + == Some("transform") { variant["properties"]["inputs"]["maxProperties"] = json!(16); } } } - if let Some(inputs) = schema.pointer_mut("/$defs/AuthoredFunction/properties/inputs") { + if let Some(inputs) = schema.pointer_mut("/$defs/AuthoredTransform/properties/inputs") { inputs["maxProperties"] = json!(16); } let mut text = serde_json::to_string_pretty(&schema)?; diff --git a/crates/registry-coordinator/src/cli.rs b/crates/registry-coordinator/src/cli.rs index af486e8715..865c1d55a0 100644 --- a/crates/registry-coordinator/src/cli.rs +++ b/crates/registry-coordinator/src/cli.rs @@ -106,8 +106,8 @@ impl ListTurn { /// What `explain` describes without a project. #[derive(Subcommand)] enum ExplainTopic { - /// List the helpers a pure Function may call, with the interpreter ABI and limits. - Functions, + /// List the helpers a pure Transform may call, with the interpreter ABI and limits. + Transforms, } mod identity_facts; @@ -155,7 +155,7 @@ enum Command { #[command(subcommand)] topic: GenerateTopic, }, - /// Validate the workflow, functions and root YAML companions offline. + /// Validate the workflow, Transforms and root YAML companions offline. Check { #[arg(long)] /// Directory containing workflow.yaml and its declared code and contract assets. @@ -174,7 +174,7 @@ enum Command { /// Check under the production posture. production: bool, }, - /// Explain a checked graph, mappings and execution bounds offline, or the helpers Functions may call. + /// Explain a checked graph, mappings and execution bounds offline, or the helpers Transforms may call. #[command(args_conflicts_with_subcommands = true, subcommand_negates_reqs = true)] Explain { #[arg(long, required = true)] @@ -971,7 +971,7 @@ async fn execute( Ok(json!({"status":"generated","output":output})) } Command::Check { project, explain, deny_warnings, environment, .. } => check(project.as_deref(), runtime_config(cli)?.as_deref(), *explain, *deny_warnings, *environment, declared, explicit_settings), - Command::Explain { topic: Some(ExplainTopic::Functions), .. } => Ok(crate::functions::explain()), + Command::Explain { topic: Some(ExplainTopic::Transforms), .. } => Ok(crate::functions::explain()), Command::Explain { project, .. } => check(project.as_deref(), runtime_config(cli)?.as_deref(), true, false, false, declared, explicit_settings), Command::Test { project, fixtures } => test(project, fixtures.as_deref()), Command::Package { project, output } => { @@ -1623,9 +1623,9 @@ fn render_human(cli: &Cli, value: &Value) -> String { render_explain(value) } Command::Explain { - topic: Some(ExplainTopic::Functions), + topic: Some(ExplainTopic::Transforms), .. - } => render_functions(value), + } => render_transforms(value), Command::Check { .. } => { let mut out = String::new(); if let Some(workflow) = value["workflow"].as_str() { @@ -1780,15 +1780,15 @@ fn render_explain(value: &Value) -> String { .map(|(limit, bound)| format!("{limit} {bound}")) .collect::>() .join(", "); - out.push_str(&format!("Function limits: {limits}\n")); + out.push_str(&format!("Transform limits: {limits}\n")); out.push_str(&format!("Recovery: {}\n", text(&value["recovery"]))); out } /// The profile, then its helper names in lines a terminal can show. -fn render_functions(value: &Value) -> String { +fn render_transforms(value: &Value) -> String { let mut out = format!( - "Pure function helpers, profile {}\nInterpreter ABI: {}\nFunction limits: {}\nHelpers:\n", + "Transform helpers, profile {}\nInterpreter ABI: {}\nFunction limits: {}\nHelpers:\n", text(&value["profile"]), text(&value["interpreterAbi"]), value["limits"] @@ -1822,7 +1822,7 @@ fn render_functions(value: &Value) -> String { /// A step mapping as one phrase: `f(input, step a /b)`, `{m: input /n}` or /// one reference. fn mapping(value: &Value) -> String { - if let Some(function) = value["function"].as_str() { + if let Some(function) = value["transform"].as_str() { let arguments = value["arguments"] .as_array() .into_iter() @@ -1877,12 +1877,7 @@ fn with_posture(mut value: Value, declared: DeclaredPosture) -> Value { fn print_explicit_settings(settings: &[registry_cli_report::ExplicitSettingLine]) { for setting in settings { - println!( - "Explicit production setting {} at {}. {}.", - setting.code, - setting.pointer.as_deref().unwrap_or_default(), - setting.summary - ); + println!("{}", setting.notice()); } } diff --git a/crates/registry-coordinator/src/compare.rs b/crates/registry-coordinator/src/compare.rs index 217cfb2985..8aaa762fa6 100644 --- a/crates/registry-coordinator/src/compare.rs +++ b/crates/registry-coordinator/src/compare.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 //! The compare decision of a choose step: an ordered list of tests over typed -//! values that routes to `matched` or `unmatched`. A compare holds no Function, +//! values that routes to `matched` or `unmatched`. A compare holds no Transform, //! no nesting and no clock, so the same input and step outputs always take the //! same route. //! @@ -358,7 +358,7 @@ mod tests { fn only_a_compare_that_cannot_test_its_value_is_a_failed_choice() { let choice = CoordinatorError::new("mapping.choice", "the value is missing"); assert_eq!(failure_code(&choice), "choice-invalid"); - for code in ["mapping.path", "mapping.branch", "function.failed"] { + for code in ["mapping.path", "mapping.branch", "transform.failed"] { let error = CoordinatorError::new(code, "refused"); assert_eq!(failure_code(&error), "mapping-invalid", "{code}"); } diff --git a/crates/registry-coordinator/src/completion.rs b/crates/registry-coordinator/src/completion.rs index a6013d1308..6771c5a16e 100644 --- a/crates/registry-coordinator/src/completion.rs +++ b/crates/registry-coordinator/src/completion.rs @@ -23,7 +23,7 @@ use registry_platform_crypto::delivery_signature::{ use registry_review_protocol::ReviewCompletion; use uuid::Uuid; -/// Interpret one bounded external observation using the pinned pure Function. +/// Interpret one bounded external observation using the pinned pure Transform. /// The original saved command is the only correlation input; mappings are not /// evaluated again while waiting. Invalid evidence remains a recovery hold. pub(crate) fn interpret_poll( @@ -65,7 +65,7 @@ pub(crate) fn interpret_poll( }; match value.get("state").and_then(serde_json::Value::as_str) { Some("pending") => CompletionObservation::Pending { retry_after: None }, - // The Function's complete interpretation envelope has been checked. + // The Transform's complete interpretation envelope has been checked. // The worker or scenario checks the cached terminal contract once. Some("complete" | "refused") => CompletionObservation::Settled(value), _ => hold(), diff --git a/crates/registry-coordinator/src/contracts.rs b/crates/registry-coordinator/src/contracts.rs index f95bfb593f..9d89435172 100644 --- a/crates/registry-coordinator/src/contracts.rs +++ b/crates/registry-coordinator/src/contracts.rs @@ -28,7 +28,7 @@ pub struct OperationContract { output_validator: JSONSchema, refusal_validator: Option, /// The complete provider response an `external.command/v1` interpretation - /// Function reads, before it becomes an accepted result or a refusal. + /// Transform reads, before it becomes an accepted result or a refusal. response_validator: Option, } @@ -172,7 +172,7 @@ impl OperationContract { Ok(self) } - /// Checks a provider response before an interpretation Function reads it. + /// Checks a provider response before an interpretation Transform reads it. /// An operation without a declared response accepts none. pub fn check_response(&self, value: &Value) -> Result<(), Violation> { match &self.response_validator { @@ -1255,13 +1255,13 @@ mod derived { (input::(), output::()) } - /// The command body is a JSON object a pinned pure Function builds; the + /// The command body is a JSON object a pinned pure Transform builds; the /// output is the bounded provider response the pinned interpretation - /// Function receives, never the step result itself. + /// Transform receives, never the step result itself. pub(super) fn external_command() -> (Value, Value) { let mut response = output::(); response["description"] = json!( - "The bounded provider response. The operation's interpret Function \ + "The bounded provider response. The operation's interpret Transform \ receives it with the command and returns the step result, a declared \ refusal, or an uncertain outcome." ); @@ -1277,6 +1277,28 @@ mod derived { ) } + /// The function body is a JSON object a pinned pure Transform builds; the + /// output is the bounded function host response the pinned interpretation + /// Transform receives, as for an external command. + pub(super) fn invoke_service_function() -> (Value, Value) { + let mut response = output::(); + response["description"] = json!( + "The bounded function host response. The operation's interpret \ + Transform receives it with the request body and returns the step \ + result, a declared refusal, or an uncertain outcome." + ); + ( + json!({ + "$schema":"https://json-schema.org/draft/2020-12/schema", + "type":"object", + "description":"The request body, sent as the exact JSON object to the \ + one service function the connection binds.", + "additionalProperties":true + }), + response, + ) + } + pub(super) fn evaluate() -> (Value, Value) { (evaluation_input(), output::()) } diff --git a/crates/registry-coordinator/src/decision.rs b/crates/registry-coordinator/src/decision.rs index b097f20325..6295d850a2 100644 --- a/crates/registry-coordinator/src/decision.rs +++ b/crates/registry-coordinator/src/decision.rs @@ -10,12 +10,12 @@ use std::{collections::BTreeMap, sync::Arc, time::Duration}; use registry_platform_canonical_json::{canonicalize_json, parse_json_strict}; use registry_platform_config::{SecretReference, SecretResolver}; use registry_platform_httputil::{ - client::BearerToken, read_bounded, FetchUrlError, FetchUrlPolicy, ServiceBaseUrl, + client::BearerToken, read_bounded, FetchUrlError, ServiceBaseUrl, }; use registry_platform_yaml::{BoundedU64, ExternalId, LocalId}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::{json, Value}; -use url::{Host, Url}; +use url::Url; use crate::{protocol::CallOutcome, CoordinatorError, Result}; @@ -91,15 +91,7 @@ impl DecisionConfig { } pub fn findings(&self, prefix: &str) -> Vec { - let loopback = match self.base_url.host() { - Some(Host::Ipv4(ip)) => { - registry_platform_httputil::loopback::loopback_address(ip.into()) - } - Some(Host::Ipv6(ip)) => { - registry_platform_httputil::loopback::loopback_address(ip.into()) - } - _ => false, - }; + let loopback = crate::outbound::numeric_loopback(&self.base_url); let mut errors = Vec::new(); let mut refuse = |field: &str, repair: &str| { let field = if prefix.is_empty() { @@ -117,8 +109,7 @@ impl DecisionConfig { ); }; if ServiceBaseUrl::new(self.base_url.clone()).is_err() - || !matches!(self.base_url.scheme(), "https" | "http") - || (self.base_url.scheme() == "http" && !loopback) + || crate::outbound::select_endpoint(&self.base_url).is_none() { refuse("baseUrl", "Use HTTPS or explicit numeric loopback HTTP, without credentials, query, fragment or empty interior path segments."); } @@ -314,19 +305,9 @@ impl DecisionConnection { &self, timeout: Duration, ) -> std::result::Result { - let policy = if self.endpoint.scheme() == "http" { - FetchUrlPolicy::https_or_loopback() - } else { - FetchUrlPolicy { - allowed_schemes: vec!["https".into()], - allow_localhost: true, - allow_http_private_network: false, - allow_http_non_loopback: false, - deny_private_ranges: false, - deny_cloud_metadata: true, - } - }; - let validated = policy + let selected = crate::outbound::select_endpoint(&self.endpoint) + .ok_or_else(|| refused("decision-invalid-command"))?; + let validated = crate::outbound::fetch_policy(&selected) .validate_dns_pinned_for_immediate_fetch_with_timeout(&self.endpoint, timeout) .await .map_err(|error| match error { diff --git a/crates/registry-coordinator/src/definition.rs b/crates/registry-coordinator/src/definition.rs index 813d9326ee..3f25cf7abf 100644 --- a/crates/registry-coordinator/src/definition.rs +++ b/crates/registry-coordinator/src/definition.rs @@ -17,7 +17,7 @@ use serde_json::Value; use crate::{ functions::{ - check_value, Functions, INTERPRETER_ABI, MAXIMUM_FUNCTION_ARRAY_ITEMS, + check_value, Transforms, INTERPRETER_ABI, MAXIMUM_FUNCTION_ARRAY_ITEMS, MAXIMUM_FUNCTION_CALL_LEVELS, MAXIMUM_FUNCTION_EXPRESSION_DEPTH, MAXIMUM_FUNCTION_MAP_ENTRIES, MAXIMUM_FUNCTION_OPERATIONS, MAXIMUM_FUNCTION_SOURCE_BYTES, MAXIMUM_FUNCTION_STRING_BYTES, @@ -53,7 +53,7 @@ pub struct Definition { pub workflow: Workflow, pub digest: String, frozen: Snapshot, - functions: Functions, + functions: Transforms, input_schema: Arc, outcome_schemas: BTreeMap>, operation_contracts: BTreeMap>, @@ -94,12 +94,14 @@ pub struct ServiceDeadline { pub next: String, } -/// How a step computes its value: a pure function over references, an +/// How a step computes its value: a pure Transform over references, an /// object built member by member from references and nested objects, or one /// reference. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(untagged, deny_unknown_fields)] pub enum Mapping { + // Frozen v1alpha1 snapshots and semantic revisions keep this member. + // Authoring and operator explanations use the Transform vocabulary. Function { function: String, inputs: BTreeMap, @@ -114,7 +116,7 @@ pub enum Mapping { } /// One member of a fields mapping: a reference, or a nested object built -/// the same way. A member never calls a Function. +/// the same way. A member never calls a Transform. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(untagged)] pub enum Member { @@ -188,6 +190,15 @@ pub(crate) fn valid_field_name(name: &str) -> bool { } impl Mapping { + fn explain(&self) -> Value { + match self { + Self::Function { function, inputs } => { + serde_json::json!({"transform":function,"inputs":inputs}) + } + mapping => serde_json::json!(mapping), + } + } + /// Each reference with its member path below the mapping. pub(crate) fn references(&self) -> Vec<(String, &Reference)> { match self { @@ -370,17 +381,21 @@ pub struct ResolvedOperation { pub refusal: Option, pub completions: BTreeMap, pub revision: String, - /// The pinned pure Function that turns an external command's saved + /// The pinned pure Transform that turns an external command's saved /// command and bounded provider response into an accepted result, a /// declared refusal or an uncertain outcome. Present only on /// `external.command/v1`. #[serde(default, skip_serializing_if = "Option::is_none")] pub interpret: Option, - /// The bounded provider response the interpretation Function reads. + /// The bounded provider response the interpretation Transform reads. /// Present only on `external.command/v1`, whose `output` is the /// interpreted accepted result. #[serde(default, skip_serializing_if = "Option::is_none")] pub response: Option, + /// The one service function `service.invoke-function/v1` calls. Present only on that operation; the + /// runtime connection must bind the same function. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub service_function: Option, /// Exact imported specialization, when the owning product exports one. #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option, @@ -680,14 +695,14 @@ impl Definition { .map_err(|error| { crate::authoring::positioned( &document, - error.at(&path, format!("/functions/{name}/source")), + error.at(&path, format!("/transforms/{name}/source")), ) })?; let source = read_text(&source_path, MAXIMUM_FUNCTION_SOURCE_BYTES as usize) .map_err(|error| { crate::authoring::positioned( &document, - error.at(&path, format!("/functions/{name}/source")), + error.at(&path, format!("/transforms/{name}/source")), ) })?; sources.insert(function.source.clone(), source); @@ -813,7 +828,7 @@ impl Definition { Err(error) => findings.push(error), _ => {} } - let functions = Functions::compile(&frozen.sources, &frozen.workflow.functions) + let functions = Transforms::compile(&frozen.sources, &frozen.workflow.functions) .map_err(|refused| findings.extend(refused)) .ok(); let input_schema = compile_schema(&frozen.workflow.input) @@ -967,10 +982,7 @@ impl Definition { }; let mut item = serde_json::json!({"id":id,"kind":kind,"next":step.targets()}); if let Some(mapping) = step.mapping() { - item["mapping"] = serde_json::json!(mapping); - if let Mapping::Function { inputs, .. } = mapping { - item["mapping"]["inputs"] = serde_json::json!(inputs); - } + item["mapping"] = mapping.explain(); } match step { Step::Call { @@ -1026,9 +1038,13 @@ impl Definition { item }) .collect::>(); + let mut event_triggers = serde_json::json!(self.workflow.event_triggers); + for (id, trigger) in &self.workflow.event_triggers { + event_triggers[id]["input"] = trigger.input.explain(); + } let mut report = serde_json::json!({"workflow":self.workflow.id,"version":self.workflow.version,"workflowRevision":self.digest, "start":self.workflow.start,"deadlineSeconds":parse_duration(&self.workflow.deadline)?.num_seconds(), - "contracts":contracts,"operations":self.workflow.operations,"operationContracts":operation_contracts,"calendarTriggers":self.workflow.calendar_triggers,"eventTriggers":self.workflow.event_triggers,"functions":self.workflow.functions,"types":self.workflow.types,"references":self.workflow.references,"presentation":self.workflow.presentation,"connections":self.workflow.connections,"outcomes":self.workflow.outcomes.keys().collect::>(),"steps":steps, + "contracts":contracts,"operations":self.workflow.operations,"operationContracts":operation_contracts,"calendarTriggers":self.workflow.calendar_triggers,"eventTriggers":event_triggers,"transforms":self.workflow.functions,"types":self.workflow.types,"references":self.workflow.references,"presentation":self.workflow.presentation,"connections":self.workflow.connections,"outcomes":self.workflow.outcomes.keys().collect::>(),"steps":steps, "limits":crate::functions::limits(),"valueLimits":crate::functions::value_limits(),"interpreterAbi":self.frozen.interpreter_abi,"schemaAbi":self.frozen.schema_abi,"adapterAbi":self.frozen.adapter_abi, "recovery":"A run restores this exact snapshot. retry-same preserves a frozen command and cannot adopt edited mappings or repeat an uncertain hold-after-dispatch evaluation."}); @@ -1355,7 +1371,7 @@ fn seal_revisions(workflow: &mut Workflow, sources: &BTreeMap) - for function in workflow.functions.values_mut() { let source = sources .get(&function.source) - .ok_or_else(|| fail("function.definition"))?; + .ok_or_else(|| fail("transform.definition"))?; function.revision = crate::functions::revision(function, source)?; } for operation in workflow.operations.values_mut() { @@ -1390,16 +1406,20 @@ fn seal_revisions(workflow: &mut Workflow, sources: &BTreeMap) - if let Some(response) = &operation.response { identity["response"] = semantic_schema(response); } + if let Some(function) = &operation.service_function { + identity["serviceFunction"] = serde_json::json!(function); + } operation.revision = semantic_hash(&identity)?; } Ok(()) } -/// An external command pins one interpretation Function over its exact -/// command and response schemas, and its output and refusal are exactly what -/// that Function declares. No other operation carries an interpretation. +/// An external command or service function call pins one interpretation +/// Transform over its exact command and response schemas, and its output and +/// refusal are exactly what that Transform declares. No other operation +/// carries an interpretation. fn command_interpretation_valid(flow: &Workflow, operation: &ResolvedOperation) -> bool { - if operation.uses != Operation::ExternalCommand { + if !operation.uses.interprets_response() { return operation.interpret.is_none() && operation.response.is_none(); } let (Some(interpret), Some(response)) = (&operation.interpret, &operation.response) else { @@ -1579,7 +1599,7 @@ fn build_fields( /// What computed a mapping's value, as a refusal names it. fn producer(mapping: &Mapping) -> String { match mapping { - Mapping::Function { function, .. } => format!("function {function}"), + Mapping::Function { function, .. } => format!("Transform {function}"), Mapping::Fields { .. } => "the fields mapping".into(), Mapping::Compare { .. } => "the compare".into(), Mapping::Reference(_) => "the reference".into(), @@ -1679,7 +1699,7 @@ fn workflow_findings(flow: &Workflow) -> Vec { ("connections", flow.connections.len(), 0, 16), ("outcomes", flow.outcomes.len(), 1, 64), ("operations", flow.operations.len(), 0, 64), - ("functions", flow.functions.len(), 0, 128), + ("transforms", flow.functions.len(), 0, 128), ("types", flow.types.len(), 0, 128), ("contracts", flow.contracts.len(), 0, 16), ] { @@ -1801,6 +1821,21 @@ fn workflow_findings(flow: &Workflow) -> Vec { findings.push(authored("definition.abi", &format!("/operations/{alias}/interpret"), "the command interpretation does not match its host-enforced Operation contract", "Recompile the canonical project; local metadata cannot change how a provider response is interpreted.")); } + let names_function = operation + .service_function + .as_deref() + .is_some_and(|name| registry_platform_yaml::LocalId::new(name).is_ok()); + if (operation.uses == Operation::InvokeServiceFunction) != names_function + || (operation.uses != Operation::InvokeServiceFunction + && operation.service_function.is_some()) + { + findings.push(authored( + "definition.abi", + &format!("/operations/{alias}/serviceFunction"), + "the operation does not name exactly one valid service function", + "Recompile the canonical project with its checked service function name.", + )); + } } for (name, step) in &flow.steps { if let Step::Call { call, .. } = step { @@ -1878,11 +1913,11 @@ fn workflow_findings(flow: &Workflow) -> Vec { } if let Some(Mapping::Function { function, inputs }) = step.mapping() { match flow.functions.get(function) { - None => findings.push(authored("mapping.function", &format!("steps.{name}.{}.function", step.role()), - &format!("Function {function} is not declared; available Functions are {}", listed(flow.functions.keys().map(String::as_str))), - "Name one of the declared Functions, or add its typed signature and reviewed source asset.")), - Some(signature) if inputs.keys().ne(signature.inputs.keys()) => findings.push(authored("mapping.function", &format!("steps.{name}.{}.inputs",step.role()), - "the named Function inputs must match its declared signature exactly", "Supply every declared input name once and remove undeclared names.")), + None => findings.push(authored("mapping.transform", &format!("steps.{name}.{}.transform", step.role()), + &format!("Transform {function} is not declared; available Transforms are {}", listed(flow.functions.keys().map(String::as_str))), + "Name one of the declared Transforms, or add its typed signature and reviewed source asset.")), + Some(signature) if inputs.keys().ne(signature.inputs.keys()) => findings.push(authored("mapping.transform", &format!("steps.{name}.{}.inputs",step.role()), + "the named Transform inputs must match its declared signature exactly", "Supply every declared input name once and remove undeclared names.")), _ => {}, } } @@ -2332,12 +2367,12 @@ pub(crate) fn validate_mapping( return Err(authored( "mapping.reference", &base, - "waitUntil and choose take a function or a single reference, not fields", - "Select the instant or label with one reference, or compute it in a function.", + "waitUntil and choose take a Transform or a single reference, not fields", + "Select the instant or label with one reference, or compute it in a Transform.", )) } (_, Mapping::Function { function, .. }) if !valid_name(function) => { - return Err(fail("mapping.function").at("workflow.yaml", format!("steps.{name}"))) + return Err(fail("mapping.transform").at("workflow.yaml", format!("steps.{name}"))) } (_, Mapping::Fields { fields }) => fields_bounds(fields, &base, 1, &mut 0)?, (_, Mapping::Compare { compare }) => compare.check(step, name)?, @@ -2354,7 +2389,7 @@ pub(crate) fn validate_mapping( "mapping.literal", &format!("{field}.value"), "the literal exceeds the structured value bounds", - "Shorten the literal or build the value in a function; literals hold at most 32 levels, 4096 nodes, 16384-byte strings, 131072 canonical bytes, and integers within 2^53 - 1.", + "Shorten the literal or build the value in a Transform; literals hold at most 32 levels, 4096 nodes, 16384-byte strings, 131072 canonical bytes, and integers within 2^53 - 1.", ) })?; continue; @@ -2539,16 +2574,16 @@ fn fail(code: &'static str) -> CoordinatorError { "definition.cycle" => "the graph contains a cycle", "definition.unreachable" => "a step is not reachable from start", "definition.deadline" => "deadline must be a positive s, m, h or d duration no longer than 365 days", - "mapping.branch" => "the function did not return a declared branch label", + "mapping.branch" => "the Transform did not return a declared branch label", "mapping.timestamp" => "waitUntil did not return an RFC 3339 instant", "mapping.missing-output" => "a declared prior call output is absent", "mapping.path" => "the reference path names no member of the value it reads", - "mapping.call-shape" => "the call input function did not return an object", + "mapping.call-shape" => "the call input Transform did not return an object", "definition.input" => "the start input does not satisfy its authored schema", "definition.outcome" => "the final output does not satisfy the declared outcome schema", "definition.schema" => "the schema is invalid or uses an unsupported format or external reference", _ => "the workflow definition or mapping was refused", - }).suggest("Inspect the authored field and function, correct the definition, then rerun check. Admitted runs keep their original snapshot.") + }).suggest("Inspect the authored field and Transform, correct the definition, then rerun check. Admitted runs keep their original snapshot.") } /// A run cancels only work it opened, so a cancel's input is a fields @@ -2559,7 +2594,7 @@ fn fail(code: &'static str) -> CoordinatorError { /// - a review cancel's `request` is the whole accepted request, with no path, /// a `casework.submit-review-request/v1` step returned. /// -/// Any other source, such as the run input, a literal, a Function, a nested +/// Any other source, such as the run input, a literal, a Transform, a nested /// object or another step, is refused with the code, message and suggestion /// returned here. Ordinary step reference checks then hold that the step ran /// on every route here. diff --git a/crates/registry-coordinator/src/deployment.rs b/crates/registry-coordinator/src/deployment.rs index 51e0d371b2..bac4b4f091 100644 --- a/crates/registry-coordinator/src/deployment.rs +++ b/crates/registry-coordinator/src/deployment.rs @@ -639,7 +639,7 @@ fn tls( let _ = rustls::crypto::ring::default_provider().install_default(); if let Some(r) = &database.ca_bundle_ref { let value = secrets - .resolve(r) + .resolve_public_document(r) .map_err(|_| fail("make the database TLS root available"))?; use rustls::pki_types::pem::PemObject as _; let mut roots = rustls::RootCertStore::empty(); diff --git a/crates/registry-coordinator/src/error.rs b/crates/registry-coordinator/src/error.rs index a7fcd29a1a..e9c774accd 100644 --- a/crates/registry-coordinator/src/error.rs +++ b/crates/registry-coordinator/src/error.rs @@ -24,6 +24,10 @@ pub struct CoordinatorError { pub(crate) refusal_detail: Option>, /// Whether this refusal rejected a development-marked token in production. pub(crate) development_assertion: bool, + /// Whether `diagnostics` is this error's own diagnostic, built only to + /// carry related locations, and so rebuilt when its position or remedy + /// changes. + pub(crate) related_only: bool, } #[derive(Debug)] @@ -48,6 +52,7 @@ impl CoordinatorError { check: None, refusal_detail: None, development_assertion: false, + related_only: false, } } /// Preserve all shared-reader findings and their authored positions. @@ -83,6 +88,7 @@ impl CoordinatorError { check: None, refusal_detail: None, development_assertion: false, + related_only: false, } } /// Name the check that refused the caller. @@ -166,13 +172,54 @@ impl CoordinatorError { } Report::new(vec![diagnostic]) } - pub fn at(mut self, file: impl Into, field: impl Into) -> Self { - self.file = Some(Box::new(file.into())); - self.field = Some(field.into().into_boxed_str()); - self + pub fn at(self, file: impl Into, field: impl Into) -> Self { + self.keeping_related(|error| { + error.file = Some(Box::new(file.into())); + error.field = Some(field.into().into_boxed_str()); + }) + } + pub fn suggest(self, action: impl Into) -> Self { + self.keeping_related(|error| { + error.suggested_action = Some(action.into().into_boxed_str()); + }) } - pub fn suggest(mut self, action: impl Into) -> Self { - self.suggested_action = Some(action.into().into_boxed_str()); + /// Apply `change` and keep any related locations already named. + fn keeping_related(mut self, change: impl FnOnce(&mut Self)) -> Self { + let related = if self.related_only { + self.related_only = false; + let diagnostics = std::mem::take(&mut self.diagnostics); + diagnostics + .into_vec() + .into_iter() + .next() + .map(|diagnostic| diagnostic.related) + } else { + None + }; + change(&mut self); + related.into_iter().flatten().fold(self, |error, related| { + error.related(&related.file, &related.path, related.message) + }) + } + /// Name another location that takes part in this refusal. It is reported + /// with the refusal whatever position or remedy is set before or after. + #[must_use] + pub(crate) fn related(mut self, file: &str, pointer: &str, message: impl Into) -> Self { + if self.diagnostics.is_empty() { + self.diagnostics = self.report().diagnostics().to_vec().into(); + self.related_only = true; + } + let mut diagnostics = std::mem::take(&mut self.diagnostics).into_vec(); + if let Some(first) = diagnostics.first_mut() { + first.related.push(registry_platform_yaml::Related { + file: file.to_owned(), + line: None, + column: None, + path: pointer.to_owned(), + message: message.into(), + }); + } + self.diagnostics = diagnostics.into(); self } fn render(&self) -> String { @@ -197,3 +244,26 @@ impl CoordinatorError { } pub type Result = std::result::Result; + +#[cfg(test)] +mod related_tests { + use super::*; + + #[test] + fn a_related_location_survives_any_later_position_or_remedy() { + let error = CoordinatorError::new("workflow-binding", "the function is not bound") + .related( + "runtime.yaml", + "/connections/notices/function", + "the bound function", + ) + .at("workflow.yaml", "/operations/draft/serviceFunction") + .suggest("Bind the function."); + let report = error.report(); + let diagnostic = &report.diagnostics()[0]; + assert_eq!(diagnostic.path, "/operations/draft/serviceFunction"); + assert_eq!(diagnostic.suggested_action, "Bind the function."); + assert_eq!(diagnostic.related.len(), 1); + assert_eq!(diagnostic.related[0].path, "/connections/notices/function"); + } +} diff --git a/crates/registry-coordinator/src/event_trigger.rs b/crates/registry-coordinator/src/event_trigger.rs index 0361df8242..6dd75c724c 100644 --- a/crates/registry-coordinator/src/event_trigger.rs +++ b/crates/registry-coordinator/src/event_trigger.rs @@ -204,7 +204,7 @@ pub(crate) fn check_key_references( } /// Resolved governed trigger. The package revision covers every member, the -/// event schema and all referenced Function implementation bytes. +/// event schema and all referenced Transform implementation bytes. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EventTrigger { @@ -217,7 +217,7 @@ pub struct EventTrigger { impl EventTrigger { /// Evaluate only after durable duplicate lookup. Exact replay must not be - /// reinterpreted by an edited active mapping or Function. + /// reinterpreted by an edited active mapping or Transform. pub(crate) fn map(&self, definition: &Definition, event: &Value) -> Result { crate::functions::check_value(event)?; let schema = crate::definition::compile_schema(&self.event)?; @@ -463,7 +463,7 @@ pub fn verify_delivery( let event_source = envelope.source.as_str(); let value = serde_json::to_value(&envelope).map_err(|_| invalid_event())?; crate::functions::check_value(&value).map_err(|error| { - if error.code == "function.value-limit" { + if error.code == "transform.value-limit" { event_too_large() } else { invalid_event() diff --git a/crates/registry-coordinator/src/event_trigger_tests.rs b/crates/registry-coordinator/src/event_trigger_tests.rs index cfb13e052f..253cdf0ae4 100644 --- a/crates/registry-coordinator/src/event_trigger_tests.rs +++ b/crates/registry-coordinator/src/event_trigger_tests.rs @@ -666,7 +666,7 @@ fn a_function_used_only_by_an_event_trigger_is_hash_covered() { let workflow = project_text() .replace( "workflow:\n input:", - r#"functions: + r#"transforms: event-input: runtime: rhai source: functions.rhai @@ -687,8 +687,8 @@ workflow: fields: recordId: {type: input, path: /data/recordId}"#, r#" input: - type: function - function: event-input + type: transform + transform: event-input inputs: event: {type: input}"#, ); diff --git a/crates/registry-coordinator/src/external_http.rs b/crates/registry-coordinator/src/external_http.rs index 0bc397e345..b9a9305be1 100644 --- a/crates/registry-coordinator/src/external_http.rs +++ b/crates/registry-coordinator/src/external_http.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -//! Configured, bounded external JSON reads and one configured external command. -//! A read never sends a mutation. A command sends one JSON object by POST to -//! the operator's configured command path and nowhere else. +//! Configured, bounded external JSON reads, one configured external command, +//! and one bound service function. A read never sends a mutation. A command +//! sends one JSON object by POST to the operator's configured command path and +//! nowhere else; a service function call sends one to the function host's +//! route for the one function the connection binds. use std::{collections::BTreeMap, sync::Arc, time::Duration}; @@ -9,14 +11,15 @@ use jsonschema::JSONSchema; use registry_platform_canonical_json::parse_json_strict; use registry_platform_httputil::{ client::{RetryAfter, TokenProvider}, - read_bounded, BoundedReadError, FetchUrlError, FetchUrlPolicy, ServiceBaseUrl, + read_bounded, BoundedReadError, FetchUrlError, ServiceBaseUrl, }; -use registry_platform_yaml::{BoundedU64, ExternalId, ForeignValue, UniqueList}; +use registry_platform_yaml::{BoundedU64, ExternalId, ForeignValue, LocalId, UniqueList}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; -use url::{Host, Url}; +use url::Url; use crate::{protocol::CallOutcome, runtime::AuthorizationConfig, CoordinatorError, Result}; +use registry_platform_config::SecretReference; /// The reviewed directory contract and environment-specific destination. #[derive(Clone, Serialize, Deserialize)] @@ -51,6 +54,84 @@ pub struct ExternalHttpConfig { pub maximum_response_bytes: BoundedU64<1, { crate::operations::MAXIMUM_HTTP_RESPONSE_BYTES }>, } +/// One service function, bound by the deployment to its function host and to a +/// credential for that host alone. `rstack dev` checks the name against the +/// service's `service.yaml`; an operator recipe binds a name it has checked. +/// The workflow names the function; it never supplies the destination or the +/// credential. The function host serves the function at `functions/` +/// under the base URL. +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ServiceFunctionConfig { + #[serde(deserialize_with = "endpoint")] + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^[^\\s\\\\]+$")))] + pub base_url: Url, + /// The one function this connection binds. + pub function: LocalId, + /// An OAuth client credential for the function host. Its client, key and + /// resource must differ from every product, external and evaluation + /// credential this runtime file declares. Exactly one of `authorization` + /// and `hostKeyRef` is required. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(extend("not" = serde_json::json!({"required":["taskAuthority"]}))))] + pub authorization: Option, + /// A static key only the function host accepts, sent as the bearer token. + /// `rstack dev` generates one for each run; an operator recipe supplies + /// its own. Exactly one of `authorization` and `hostKeyRef` is required. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_key_ref: Option, + /// Local JSON Schema for the complete {status, body} response. + #[cfg_attr(feature = "schema", schemars(extend("x-registry-foreign" = "json-schema-2020-12")))] + pub response_schema: ForeignValue, + #[serde(default = "default_timeout")] + pub attempt_timeout_milliseconds: + BoundedU64<1, { crate::operations::HTTP_REQUEST_TIMEOUT_MILLISECONDS }>, + #[serde(default = "default_response_bytes")] + pub maximum_response_bytes: BoundedU64<1, { crate::operations::MAXIMUM_HTTP_RESPONSE_BYTES }>, +} + +impl ServiceFunctionConfig { + /// The bounded HTTP transport for the one function route: its only path + /// is the command path, and the credential is always present. + pub(crate) fn transport(&self) -> ExternalHttpConfig { + let route = ExternalId::new(format!("functions/{}", self.function.as_str())) + .expect("a local identifier yields a bounded relative path"); + ExternalHttpConfig { + base_url: self.base_url.clone(), + paths: UniqueList::new(vec![route.clone()]).expect("one path is unique"), + query_parameters: None, + authorization: self.authorization.clone(), + command_path: Some(route), + response_schema: self.response_schema.clone(), + attempt_timeout_milliseconds: self.attempt_timeout_milliseconds, + maximum_response_bytes: self.maximum_response_bytes, + } + } + + pub fn findings(&self, prefix: &str) -> Vec { + let mut transport = self.transport(); + let task_authority = transport + .authorization + .as_mut() + .and_then(|authorization| authorization.task_authority.take()) + .is_some(); + let mut errors = transport.findings(prefix); + if task_authority { + errors.push( + CoordinatorError::new( + "coordinator.external-http.configuration", + "the service function credential was refused", + ) + .at("runtime.yaml", format!("{prefix}.authorization.taskAuthority")) + .suggest("Remove taskAuthority; a service function call runs under the function host credential alone and never under task authority."), + ); + } + errors + } +} + fn endpoint<'de, D: Deserializer<'de>>(d: D) -> std::result::Result { let written = registry_platform_yaml::Url::deserialize(d)?; if written.as_str().contains('\\') || written.as_str().chars().any(char::is_whitespace) { @@ -101,16 +182,7 @@ impl ExternalHttpConfig { ); }; let base = ServiceBaseUrl::new(self.base_url.clone()); - let numeric_loopback = match self.base_url.host() { - Some(Host::Ipv4(ip)) => { - registry_platform_httputil::loopback::loopback_address(ip.into()) - } - Some(Host::Ipv6(ip)) => { - registry_platform_httputil::loopback::loopback_address(ip.into()) - } - _ => false, - }; - if base.is_err() || (self.base_url.scheme() == "http" && !numeric_loopback) { + if base.is_err() || crate::outbound::select_endpoint(&self.base_url).is_none() { refuse("baseUrl", "Use HTTPS or explicit numeric loopback HTTP, without credentials, query, fragment or empty interior path segments."); } if self.paths.is_empty() @@ -221,6 +293,23 @@ impl ExternalHttpConnection { }) } + /// The connection to one bound service function. Calls reach it only + /// through [`Self::command`], under the function host credential: the + /// OAuth client's tokens or the static host key. + pub fn service_function( + config: &ServiceFunctionConfig, + tokens: Arc, + ) -> Result { + let transport = config.transport(); + let oauth = transport + .authorization + .is_some() + .then(|| Arc::clone(&tokens)); + let mut connection = Self::new(&transport, oauth)?; + connection.tokens = Some(tokens); + Ok(connection) + } + /// One attempt at the configured read. Before the final attempt, a busy or /// failing gateway (429, 502, 503 or 504) is retryable with the wait its /// `Retry-After` names; on the final attempt the workflow receives it as @@ -275,7 +364,7 @@ impl ExternalHttpConnection { /// so the same command can still be retried. A `Retry-After` either /// answer carries that the command cannot use is ignored. Only a status /// `command_status` classifies as interpreted reaches the operation's - /// pinned interpretation Function, which receives the response. + /// pinned interpretation Transform, which receives the response. pub async fn command( &self, input: &Value, @@ -417,19 +506,10 @@ impl ExternalHttpConnection { // The destination was reviewed by the operator. Institutional HTTPS // peers may be private, but metadata and non-loopback cleartext remain // denied. Each request connects to only the addresses validated here. - let policy = if url.scheme() == "http" { - FetchUrlPolicy::https_or_loopback() - } else { - FetchUrlPolicy { - allowed_schemes: vec!["https".into()], - allow_localhost: true, - allow_http_private_network: false, - allow_http_non_loopback: false, - deny_private_ranges: false, - deny_cloud_metadata: true, - } + let Some(selected) = crate::outbound::select_endpoint(&url) else { + return Err(refused("external-destination-refused")); }; - let validated = match policy + let validated = match crate::outbound::fetch_policy(&selected) .validate_dns_pinned_for_immediate_fetch_with_timeout(&url, timeout) .await { @@ -478,12 +558,12 @@ impl ExternalHttpConnection { /// What an `external.command/v1` attempt does with the provider's HTTP status /// before any body is read. Only [`CommandStatus::Interpreted`] reaches the -/// operation's interpretation Function; scenario checks use the same -/// classification, so a synthetic response reply cannot show the Function +/// operation's interpretation Transform; scenario checks use the same +/// classification, so a synthetic response reply cannot show the Transform /// reading a status the worker never hands it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum CommandStatus { - /// The bounded response goes to the interpretation Function. + /// The bounded response goes to the interpretation Transform. Interpreted, /// A redirect is never followed. It may answer an accepted command, so /// the command is uncertain. @@ -512,8 +592,8 @@ pub(crate) fn command_status(status: reqwest::StatusCode) -> CommandStatus { } /// Interpret one provider response to an `external.command/v1` call with the -/// project's pinned pure Function. The response is held to its declared -/// schema before the Function reads it. Anything the Function cannot turn into +/// project's pinned pure Transform. The response is held to its declared +/// schema before the Transform reads it. Anything the Transform cannot turn into /// an accepted result or a declared refusal leaves the command uncertain, /// never failed: the provider may already have applied it. No code carries a /// response or command value. diff --git a/crates/registry-coordinator/src/functions.rs b/crates/registry-coordinator/src/functions.rs index c0e567043d..dc068f2a06 100644 --- a/crates/registry-coordinator/src/functions.rs +++ b/crates/registry-coordinator/src/functions.rs @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//! Pure functions under one pinned, bounded interpreter profile. +//! Pure Transforms under one pinned, bounded interpreter profile. use crate::definition::{compile_schema, FunctionDefinition}; use chrono::{DateTime, Datelike, SecondsFormat, TimeDelta, Utc}; @@ -55,7 +55,7 @@ const PROFILE: RhaiProfile = RhaiProfile { }; #[derive(Clone)] -pub(crate) struct Functions { +pub(crate) struct Transforms { entries: BTreeMap, } @@ -83,7 +83,7 @@ fn profile(function: &FunctionDefinition) -> RhaiProfile { } } -impl Functions { +impl Transforms { pub(crate) fn compile( sources: &BTreeMap, definitions: &BTreeMap, @@ -96,7 +96,7 @@ impl Functions { let result = (|| { let source = sources .get(&function.source) - .ok_or_else(|| failure("function.definition"))?; + .ok_or_else(|| failure("transform.definition"))?; let limits = &function.limits; let ceiling = crate::definition::FunctionLimits::default(); if function.runtime != "rhai" @@ -119,20 +119,20 @@ impl Functions { || limits.source_bytes > ceiling.source_bytes || function.inputs.len() > 16 { - return Err(failure("function.limits") - .at("workflow.yaml", format!("/functions/{name}/limits"))); + return Err(failure("transform.limits") + .at("workflow.yaml", format!("/transforms/{name}/limits"))); } let ast = platform::compile_entrypoint(&profile(function), source, &function.entrypoint, &[1]) .map_err(|error| match error { - platform::RhaiCompileError::SourceBound => failure("function.source-limit").at(&function.source, "/"), - platform::RhaiCompileError::Parse(position) if refused_only_for_curry(source) => CoordinatorError::new("function.definition", "function source uses `curry`, which Coordinator Functions do not offer") + platform::RhaiCompileError::SourceBound => failure("transform.source-limit").at(&function.source, "/"), + platform::RhaiCompileError::Parse(position) if refused_only_for_curry(source) => CoordinatorError::new("transform.definition", "Transform source uses `curry`, which Coordinator Transforms do not offer") .at(&function.source, format!("line {} column {}", position.line().unwrap_or(0), position.position().unwrap_or(0))) .suggest("Pass the value as an argument where the function is called, for example add(1, x) instead of Fn(\"add\").curry(1).call(x)."), - platform::RhaiCompileError::Parse(position) => CoordinatorError::new("function.definition", syntax_refusal(source)) + platform::RhaiCompileError::Parse(position) => CoordinatorError::new("transform.definition", syntax_refusal(source)) .at(&function.source, format!("line {} column {}", position.line().unwrap_or(0), position.position().unwrap_or(0))) - .suggest("Correct the named Function source syntax and rerun check."), - platform::RhaiCompileError::Entrypoint => CoordinatorError::new("function.definition", "the Function entrypoint must name one public Rhai function taking one named-input object") - .at("workflow.yaml", format!("/functions/{name}/entrypoint")) + .suggest("Correct the named Transform source syntax and rerun check."), + platform::RhaiCompileError::Entrypoint => CoordinatorError::new("transform.definition", "the Transform entrypoint must name one public Rhai function taking one named-input object") + .at("workflow.yaml", format!("/transforms/{name}/entrypoint")) .suggest("Declare one public function with exactly one parameter for its named input object."), })?; let mut names = std::collections::BTreeSet::new(); @@ -141,7 +141,7 @@ impl Functions { .any(|function| !names.insert(function.name.to_owned())) || names.len() > 128 { - return Err(failure("function.definition").at(&function.source, "/")); + return Err(failure("transform.definition").at(&function.source, "/")); } let properties = function .inputs @@ -160,8 +160,8 @@ impl Functions { let output = std::sync::Arc::new(compile_schema(&function.output)?); let revision = revision(function, source)?; if function.revision != revision { - return Err(failure("function.revision") - .at("workflow.yaml", format!("/functions/{name}"))); + return Err(failure("transform.revision") + .at("workflow.yaml", format!("/transforms/{name}"))); } Ok(CompiledFunction { definition: function.clone(), @@ -172,7 +172,7 @@ impl Functions { })(); match result { Ok(compiled) => { - // Functions share one source, so each walk finds the same + // Transforms share one source, so each walk finds the same // calls; a call is reported once, at its position. let unknown = unknown_calls(&compiled); if unknown.is_empty() { @@ -203,46 +203,46 @@ impl Functions { let function = self .entries .get(name) - .ok_or_else(|| failure("function.definition"))?; + .ok_or_else(|| failure("transform.definition"))?; check_value(inputs)?; if !function.input.is_valid(inputs) { return Err(contract_failure( name, - "function.input", + "transform.input", &function.input, inputs, synthetic, )); } let arguments = - vec![rhai::serde::to_dynamic(inputs).map_err(|_| failure("function.input"))?]; + vec![rhai::serde::to_dynamic(inputs).map_err(|_| failure("transform.input"))?]; let engine = platform::build_engine(&profile(&function.definition), None, register_pure_packages); let value = platform::call_with_fresh_scope(&engine, &function.ast, &function.definition.entrypoint, arguments) .map_err(|error| { let refusal = failure(match platform::classify_failure(&error) { - platform::RhaiFailureCategory::ResourceExhausted => "function.resource-limit", - platform::RhaiFailureCategory::Other => "function.execution", + platform::RhaiFailureCategory::ResourceExhausted => "transform.resource-limit", + platform::RhaiFailureCategory::Other => "transform.execution", }); - if synthetic { CoordinatorError { message: format!("function {name} failed: {}", located(&function.definition.entrypoint, &error)), ..refusal } - .suggest(format!("Correct Function {name} in {} at the named position, or correct its synthetic inputs.", function.definition.source)) } + if synthetic { CoordinatorError { message: format!("Transform {name} failed: {}", located(&function.definition.entrypoint, &error)), ..refusal } + .suggest(format!("Correct Transform {name} in {} at the named position, or correct its synthetic inputs.", function.definition.source)) } else { refusal } })?; if holds_non_finite(&value, 0) { - let refusal = failure("function.execution"); + let refusal = failure("transform.execution"); return Err(if synthetic { - CoordinatorError { message: format!("function {name} returned NaN or an infinite number, which has no JSON form"), ..refusal } - .suggest(format!("Correct Function {name} so it never divides by zero or takes the square root of a negative number; test with is_finite first.")) + CoordinatorError { message: format!("Transform {name} returned NaN or an infinite number, which has no JSON form"), ..refusal } + .suggest(format!("Correct Transform {name} so it never divides by zero or takes the square root of a negative number; test with is_finite first.")) } else { refusal }); } - let value = rhai::serde::from_dynamic(&value).map_err(|_| failure("function.output"))?; + let value = rhai::serde::from_dynamic(&value).map_err(|_| failure("transform.output"))?; check_value(&value)?; if !function.output.is_valid(&value) { return Err(contract_failure( name, - "function.output", + "transform.output", &function.output, &value, synthetic, @@ -263,21 +263,21 @@ fn contract_failure( if !synthetic { return refusal; } - let role = if code == "function.input" { + let role = if code == "transform.input" { "named inputs" } else { "output" }; let rule = crate::definition::schema_refusal(schema, value).unwrap_or_default(); - CoordinatorError {message:format!("function {name} returned a value of class {}; its declared {role} schema refuses it{rule}",crate::definition::class(value)),..refusal} - .suggest(format!("Correct Function {name} or its synthetic input mappings to satisfy the named signature rule.")) + CoordinatorError {message:format!("Transform {name} returned a value of class {}; its declared {role} schema refuses it{rule}",crate::definition::class(value)),..refusal} + .suggest(format!("Correct Transform {name} or its synthetic input mappings to satisfy the named signature rule.")) } pub(crate) fn revision(function: &FunctionDefinition, source: &str) -> Result { let semantic = serde_json::json!({"runtime":function.runtime,"profile":function.profile,"capabilities":function.capabilities,"abi":function.abi,"entrypoint":function.entrypoint, "inputs":function.inputs.iter().map(|(name,schema)| (name,crate::definition::semantic_schema(schema))).collect::>(),"output":crate::definition::semantic_schema(&function.output),"limits":function.limits,"valueLimits":value_limits(),"sourceDigest":registry_platform_config::sha256_uri(source.as_bytes())}); let bytes = registry_platform_canonical_json::canonicalize_json(&semantic) - .map_err(|_| failure("function.definition"))?; + .map_err(|_| failure("transform.definition"))?; Ok(registry_platform_config::sha256_uri(&bytes)) } @@ -349,7 +349,7 @@ fn syntax_refusal(source: &str) -> String { .err() .map(|error| format!(": {}", error.err_type())) .unwrap_or_default(); - format!("function source has invalid or disabled syntax{reason}") + format!("Transform source has invalid or disabled syntax{reason}") } /// Bound structured values before conversion and after execution as well as @@ -376,23 +376,23 @@ pub(crate) fn check_value(value: &Value) -> Result<()> { } } if !walk(value, 0, &mut 0) { - return Err(failure("function.value-limit")); + return Err(failure("transform.value-limit")); } let bytes = registry_platform_canonical_json::canonicalize_json(value) - .map_err(|_| failure("function.json"))?; + .map_err(|_| failure("transform.json"))?; if bytes.len() > MAXIMUM_VALUE_BYTES { - return Err(failure("function.value-limit")); + return Err(failure("transform.value-limit")); } Ok(()) } fn failure(code: &'static str) -> CoordinatorError { CoordinatorError::new(code, match code { - "function.resource-limit" => "the function exceeded its operation, call-depth or value-size budget", - "function.value-limit" => "the structured value exceeded its size or depth budget", - "function.execution" => "the function could not evaluate its supplied values", - "function.source-limit" => "functions.rhai exceeds the 65536-byte source budget", - _ => "the pure function boundary refused the definition or value", + "transform.resource-limit" => "the Transform exceeded its operation, call-depth or value-size budget", + "transform.value-limit" => "the structured value exceeded its size or depth budget", + "transform.execution" => "the Transform could not evaluate its supplied values", + "transform.source-limit" => "functions.rhai exceeds the 65536-byte source budget", + _ => "the pure Transform boundary refused the definition or value", }).suggest("Inspect the named mapping and reduce bounded work or correct its declared arguments; values are omitted.") } @@ -424,7 +424,7 @@ fn register_pure_packages(engine: &mut Engine) { /// every host: IEEE 754 arithmetic (`sqrt` is correctly rounded), rounding, /// parsing and conversion. The package's libm functions (`sin`, `exp`, `ln`, /// `hypot` and the like) are left out because their last digits depend on the -/// host's math library, and Function results are recomputed when waits replay. +/// host's math library, and Transform results are recomputed when waits replay. fn register_deterministic_math(engine: &mut Engine) { engine .register_fn("PI", || std::f64::consts::PI) @@ -643,7 +643,7 @@ const INTERPRETER_CALLS: [&str; 6] = [ "type_of", ]; -/// The names a Function may call: every callable the pure profile registers, +/// The names a Transform may call: every callable the pure profile registers, /// listed once from a real engine so the list cannot drift from what runs. /// Operators, property accessors and the symbols the profile disables are not /// calls an author writes by name. @@ -668,7 +668,7 @@ pub(crate) fn helpers() -> &'static BTreeSet { } /// Array methods that take a function by value or by name. A string literal -/// given to one of them names a Function to call. `index_of` and `contains` +/// given to one of them names a Transform to call. `index_of` and `contains` /// are left out: they search for the string. const CALLBACK_METHODS: [&str; 16] = [ "for_each", @@ -694,7 +694,7 @@ const NAMING_CALLS: [&str; 2] = ["Fn", "is_def_fn"]; /// One finding for each call, in `name`'s source, to a name that is neither a /// profile helper nor a function the source defines. Calls are matched by -/// name alone, so a wrong argument count still fails when the Function runs. +/// name alone, so a wrong argument count still fails when the Transform runs. /// A string literal given to `Fn`, `is_def_fn` or an array method such as /// `map` is read as a function name. A method call is skipped when the source /// also uses its name as a map key or property, since it may call a function @@ -761,14 +761,14 @@ fn unknown_calls(function: &CompiledFunction) -> Vec { _ => "/".to_owned(), }; CoordinatorError::new( - "function.unknown-call", + "transform.unknown-call", format!( "`{callee}` is not available: it is neither a helper of {PURE_PROFILE} nor a function defined in {}", function.definition.source ), ) .at(&function.definition.source, location) - .suggest("Call a listed helper, such as trim, split and starts_with for strings or parse_int and abs for numbers, or define the function in the same source; `coordinatorctl explain functions` lists every helper.") + .suggest("Call a listed helper, such as trim, split and starts_with for strings or parse_int and abs for numbers, or define the function in the same source; `coordinatorctl explain transforms` lists every helper.") }) .collect() } @@ -831,8 +831,8 @@ const HELPER_NOTES: [&str; 2] = [ "A top-level const is not visible inside a function: read it as global::NAME, or pass it as an input.", ]; -/// What `coordinatorctl explain functions` reports: the profile, its -/// interpreter ABI and limits, and every helper a Function may call. +/// What `coordinatorctl explain transforms` reports: the profile, its +/// interpreter ABI and limits, and every helper a Transform may call. pub(crate) fn explain() -> Value { json!({ "profile": PURE_PROFILE, @@ -874,7 +874,7 @@ fn instant_refused() -> Box { } /// Structured JSON custody limits, shared by every host Operation boundary. -/// These are distinct from a pure Function's narrowed interpreter limits. +/// These are distinct from a pure Transform's narrowed interpreter limits. pub(crate) fn value_limits() -> Value { serde_json::json!({ "maximumBytes": MAXIMUM_VALUE_BYTES, diff --git a/crates/registry-coordinator/src/http.rs b/crates/registry-coordinator/src/http.rs index 46776e612e..85ced4d8f8 100644 --- a/crates/registry-coordinator/src/http.rs +++ b/crates/registry-coordinator/src/http.rs @@ -1280,6 +1280,55 @@ mod problem_tests { } } + #[test] + fn openapi_uses_explicit_path_identifier_names() { + let document = openapi(); + let operations: [(&str, &str, &str, &[&str]); 8] = [ + ( + "/v1/workflows/{workflowId}", + "get", + "workflowContract", + &["workflowId"], + ), + ("/v1/runs/{runId}", "get", "runStatus", &["runId"]), + ("/v1/runs/{runId}/inspect", "get", "inspectRun", &["runId"]), + ("/v1/runs/{runId}/check", "post", "checkNow", &["runId"]), + ( + "/v1/runs/{runId}/retry-same", + "post", + "retrySame", + &["runId"], + ), + ("/v1/runs/{runId}/cancel", "post", "cancelRun", &["runId"]), + ( + "/v1/runs/{runId}/reconcile", + "post", + "reconcileRun", + &["runId"], + ), + ( + "/v1/events/{workflowId}/{triggerId}", + "post", + "admitEvent", + &["workflowId", "triggerId"], + ), + ]; + for (path, method, id, expected_names) in operations { + let operation = &document["paths"][path][method]; + assert_eq!(operation["operationId"], id, "{method} {path}"); + let parameters = operation["parameters"].as_array().unwrap(); + let names: Vec<_> = parameters + .iter() + .filter(|parameter| parameter["in"] == "path") + .map(|parameter| { + assert_eq!(parameter["required"], true, "{method} {path}"); + parameter["name"].as_str().unwrap() + }) + .collect(); + assert_eq!(names.as_slice(), expected_names, "{method} {path}"); + } + } + #[test] fn openapi_summarizes_every_operation_once() { let document = openapi(); @@ -1963,7 +2012,7 @@ const BODY_PROBLEMS: [ProblemCode; 3] = [ ProblemCode::RequestBodyTooLarge, ProblemCode::RequestUnsupportedMediaType, ]; -/// Every problem resolving the `{run}` path segment can answer. +/// Every problem resolving the `{runId}` path segment can answer. const RUN_PROBLEMS: [ProblemCode; 2] = [ProblemCode::RequestInvalid, ProblemCode::RunNotVisible]; /// Every problem a review completion sender can be answered with. const REVIEW_COMPLETION_PROBLEMS: [ProblemCode; 6] = [ @@ -2052,11 +2101,11 @@ fn summary(operation_id: &str) -> &'static str { pub fn openapi() -> Value { use ProblemCode as P; let run_state = json!({"type":"string","enum":["running","finished","failed","cancelled","cancelled-after-effect","expired","attention","cancel-requested"]}); - let run_param = json!({"name":"run","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}); + let run_param = json!({"name":"runId","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}); let mut paths = serde_json::Map::new(); let operations: [DocumentedOperation; 15] = [ ( - "/v1/workflows/{workflow}", + "/v1/workflows/{workflowId}", "get", "workflowContract", None, @@ -2102,7 +2151,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}", + "/v1/runs/{runId}", "get", "runStatus", None, @@ -2110,7 +2159,7 @@ pub fn openapi() -> Value { RUN_PROBLEMS.to_vec(), ), ( - "/v1/runs/{run}/inspect", + "/v1/runs/{runId}/inspect", "get", "inspectRun", None, @@ -2126,7 +2175,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}/check", + "/v1/runs/{runId}/check", "post", "checkNow", Some("CheckNow"), @@ -2134,7 +2183,7 @@ pub fn openapi() -> Value { [&BODY_PROBLEMS[..], &RUN_PROBLEMS[..], &[P::CheckNotWaiting]].concat(), ), ( - "/v1/runs/{run}/retry-same", + "/v1/runs/{runId}/retry-same", "post", "retrySame", Some("Reason"), @@ -2157,7 +2206,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}/cancel", + "/v1/runs/{runId}/cancel", "post", "cancelRun", Some("Reason"), @@ -2170,7 +2219,7 @@ pub fn openapi() -> Value { .concat(), ), ( - "/v1/runs/{run}/reconcile", + "/v1/runs/{runId}/reconcile", "post", "reconcileRun", Some("Reason"), @@ -2257,11 +2306,11 @@ pub fn openapi() -> Value { json!({"description":"Authorized result","content":{"application/json":{"schema":{"$ref":format!("#/components/schemas/{response}")}}}}), ); let mut op = json!({"operationId":id,"summary":summary(id),"security":[{"bearer":[]}],"responses":responses}); - if path.contains("{run}") { + if path.contains("{runId}") { op["parameters"] = json!([run_param.clone()]); } - if path.contains("{workflow}") { - op["parameters"] = json!([{"name":"workflow","in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}]); + if path.contains("{workflowId}") { + op["parameters"] = json!([{"name":"workflowId","in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}]); } if id == "listRuns" { op["parameters"] = json!([ diff --git a/crates/registry-coordinator/src/http/admission_contracts.rs b/crates/registry-coordinator/src/http/admission_contracts.rs index bf951c8edc..6e640710dd 100644 --- a/crates/registry-coordinator/src/http/admission_contracts.rs +++ b/crates/registry-coordinator/src/http/admission_contracts.rs @@ -76,11 +76,11 @@ fn event_path(paths: &mut Map) { "description":"Run admission is committed, or the exact event was already admitted. Empty Hook response proposes no source mutation.", "headers":{"X-Coordinator-Run-Id":{"schema":{"type":"string","format":"uuid"}}} })); - let mut parameters = ["workflow", "trigger"].into_iter().map(|name| { + let mut parameters = ["workflowId", "triggerId"].into_iter().map(|name| { json!({"name":name,"in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":64}}) }).collect::>(); parameters.extend(webhook_parameters()); - paths.insert("/v1/events/{workflow}/{trigger}".into(), json!({"post":{ + paths.insert("/v1/events/{workflowId}/{triggerId}".into(), json!({"post":{ "operationId":"admitEvent","summary":"Start a workflow from an authenticated product event", "description":"Accept at most 1048576 canonical JSON bytes in a HookEnvelope, then hold the admitted event to the 131072-byte structured value profile. Standard Webhooks signs the webhook ID, Unix timestamp and exact body using the key for the trigger in the URL. The signed timestamp must be within 300 seconds in either direction. The webhook ID must equal the envelope ID, and the envelope must match the configured producer URI and authored event type and data schema. The source URI, event ID and trigger bind admission across retries. Every downstream call uses its own product authorization.", "security":[{"eventSource":[]}],"parameters":parameters, diff --git a/crates/registry-coordinator/src/lib.rs b/crates/registry-coordinator/src/lib.rs index c71da85b3c..db2452333c 100644 --- a/crates/registry-coordinator/src/lib.rs +++ b/crates/registry-coordinator/src/lib.rs @@ -18,6 +18,7 @@ mod follow_check; mod functions; mod mapping_check; pub mod operations; +mod outbound; pub mod problem; pub mod project; mod project_check; diff --git a/crates/registry-coordinator/src/mapping_check.rs b/crates/registry-coordinator/src/mapping_check.rs index 942f4aa864..85cc38615d 100644 --- a/crates/registry-coordinator/src/mapping_check.rs +++ b/crates/registry-coordinator/src/mapping_check.rs @@ -70,17 +70,17 @@ fn check_step( if let Mapping::Function { function, inputs } = mapping { let signature = workflow.functions.get(function).ok_or_else(|| { authored( - "mapping.function", + "mapping.transform", &format!("{base}.function"), - "the named Function is not declared", - "Name one of the project's declared Functions.", + "the named Transform is not declared", + "Name one of the project's declared Transforms.", ) })?; if inputs.keys().ne(signature.inputs.keys()) { return Err(authored( - "mapping.function", + "mapping.transform", &format!("{base}.inputs"), - "the named Function inputs must match its declared signature exactly", + "the named Transform inputs must match its declared signature exactly", "Supply every declared input name once and remove undeclared names.", )); } @@ -192,7 +192,7 @@ fn schema_fits(target: &Value, read: &Read<'_>, field: &str) -> Result<()> { wanted.describe(), offered.describe() ), - "Select a value of the target type, or convert it with a typed Function.", + "Select a value of the target type, or convert it with a typed Transform.", )); } Ok(()) diff --git a/crates/registry-coordinator/src/operations.rs b/crates/registry-coordinator/src/operations.rs index d671f9d3f1..8618487451 100644 --- a/crates/registry-coordinator/src/operations.rs +++ b/crates/registry-coordinator/src/operations.rs @@ -150,12 +150,17 @@ impl OperationDescriptor { "connectTimeoutMilliseconds":HTTP_CONNECT_TIMEOUT_MILLISECONDS, "maximumMutationRetries":HTTP_MUTATION_RETRIES }); - if matches!(self.product, "external-http" | "evaluation") { + if matches!( + self.product, + "external-http" | "service-function" | "evaluation" + ) { let fields = http.as_object_mut().expect("HTTP contract is an object"); fields.remove("connectTimeoutMilliseconds"); fields.insert("connectionMayLowerLimits".into(), json!(true)); fields.insert("redirects".into(), json!("refused")); - if self.id == Operation::ExternalCommand.as_str() { + if self.id == Operation::ExternalCommand.as_str() + || self.id == Operation::InvokeServiceFunction.as_str() + { fields.insert( "maximumRequestBytes".into(), json!(MAXIMUM_HTTP_RESPONSE_BYTES), @@ -358,6 +363,7 @@ macro_rules! operation_catalog { RequestDisbursement => "payments.request-disbursement/v1", receipt_reconciled_mutation("payments"), request_disbursement; ReadDisbursement => "payments.read-disbursement/v1", read("payments"), read_disbursement; RecordProviderConfirmation => "payments.record-provider-confirmation/v1", mutation("payments", false, false), record_provider_confirmation; + InvokeServiceFunction => "service.invoke-function/v1", declared_mutation("service-function", false, false), invoke_service_function; } }; } @@ -494,6 +500,10 @@ mod tests { Operation::RecordProviderConfirmation, "payments.record-provider-confirmation/v1", ), + ( + Operation::InvokeServiceFunction, + "service.invoke-function/v1", + ), ]; assert_eq!( descriptors() @@ -647,6 +657,7 @@ mod tests { Operation::RecordReceipt, Operation::RequestDisbursement, Operation::RecordProviderConfirmation, + Operation::InvokeServiceFunction, ]; let allowed_mutations = [ Operation::SubmitMessage, diff --git a/crates/registry-coordinator/src/outbound.rs b/crates/registry-coordinator/src/outbound.rs new file mode 100644 index 0000000000..0b3ddad2ed --- /dev/null +++ b/crates/registry-coordinator/src/outbound.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The transport of every configured outbound destination: external reads and +//! commands, decision services and product token endpoints. +//! +//! Each carries a credential, so the shared credential selector decides the +//! transport. The Coordinator narrows it once more: plain HTTP reaches only a +//! numeric loopback address, never the name `localhost`. The DNS-pinned fetch +//! policy then follows the selected transport, never the URL's scheme. + +use registry_platform_httputil::{ + loopback::loopback_address, + select::{select_credential_destination, SelectedDestination, TransportClass}, + FetchUrlPolicy, +}; +use url::{Host, Url}; + +/// `url` selected as a credential-bearing destination the Coordinator admits: +/// https, or plain HTTP to a numeric loopback address. +pub(crate) fn select_endpoint(url: &Url) -> Option { + let selected = select_credential_destination(url, None, &[]).ok()?; + (selected.transport() == TransportClass::VerifiedTls || numeric_loopback(url)) + .then_some(selected) +} + +/// Whether `url`'s host is a loopback address literal, mapped forms included. +pub(crate) fn numeric_loopback(url: &Url) -> bool { + match url.host() { + Some(Host::Ipv4(ip)) => loopback_address(ip.into()), + Some(Host::Ipv6(ip)) => loopback_address(ip.into()), + _ => false, + } +} + +/// The DNS-pinned policy a request to `selected` validates against. The +/// destinations are reviewed deployment bindings, so an institutional https +/// peer may be private; cloud metadata stays denied, and plain HTTP stays on +/// loopback. +pub(crate) fn fetch_policy(selected: &SelectedDestination) -> FetchUrlPolicy { + match selected.transport() { + TransportClass::VerifiedTls => FetchUrlPolicy { + allowed_schemes: vec!["https".into()], + allow_localhost: true, + allow_http_private_network: false, + allow_http_non_loopback: false, + deny_private_ranges: false, + deny_cloud_metadata: true, + }, + // `select_endpoint` never selects private plain text; both plain-text + // classes get the loopback-only policy. + TransportClass::LoopbackPlaintext | TransportClass::PrivateNetworkPlaintext => { + FetchUrlPolicy::https_or_loopback() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_are_https_or_numeric_loopback_http() { + for admitted in [ + "https://directory.example.test/", + "https://10.0.0.8/", + "https://localhost/", + "HTTPS://DIRECTORY.EXAMPLE.TEST/", + // Link-local https is selected; the request-time policy refuses it. + "https://169.254.1.1/", + "http://127.0.0.1:8080/", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]:8080/", + ] { + assert!( + select_endpoint(&admitted.parse().unwrap()).is_some(), + "{admitted}" + ); + } + for refused in [ + "http://localhost:8080/", + "http://LOCALHOST:8080/", + "http://x.localhost/", + "http://localhost./", + "http://10.0.0.1/", + "http://directory.example.test/", + "https://user@directory.example.test/", + "ftp://directory.example.test/", + ] { + assert!( + select_endpoint(&refused.parse().unwrap()).is_none(), + "{refused}" + ); + } + } + + #[test] + fn the_policy_follows_the_selected_transport() { + let https = select_endpoint(&"https://10.0.0.8/".parse().unwrap()).unwrap(); + assert_eq!( + fetch_policy(&https), + FetchUrlPolicy { + allowed_schemes: vec!["https".into()], + allow_localhost: true, + allow_http_private_network: false, + allow_http_non_loopback: false, + deny_private_ranges: false, + deny_cloud_metadata: true, + } + ); + let loopback = select_endpoint(&"http://127.0.0.1:8080/".parse().unwrap()).unwrap(); + assert_eq!(fetch_policy(&loopback), FetchUrlPolicy::https_or_loopback()); + } +} diff --git a/crates/registry-coordinator/src/problem.rs b/crates/registry-coordinator/src/problem.rs index f3ef8d6722..d94ab9f297 100644 --- a/crates/registry-coordinator/src/problem.rs +++ b/crates/registry-coordinator/src/problem.rs @@ -372,7 +372,7 @@ impl ProblemCode { } Self::CheckNotWaiting => "That step is not waiting.", Self::DefinitionRefused => { - "The workflow's workflow definition, one of its mappings or one of its functions refused the request." + "The workflow's workflow definition, one of its mappings or one of its Transforms refused the request." } Self::DeploymentActivationChanged => { "An apply changed the active packages after this service started. Restart it with the runtime file that apply used." @@ -529,7 +529,7 @@ pub(crate) fn for_error(code: &str) -> Option { } code if code.starts_with("definition.") || code.starts_with("mapping.") - || code.starts_with("function.") => + || code.starts_with("transform.") => { ProblemCode::DefinitionRefused } @@ -715,7 +715,7 @@ mod tests { ("deployment.refused", ProblemCode::DeploymentRefused), ("state-key-custody", ProblemCode::DeploymentRefused), ("mapping.branch", ProblemCode::DefinitionRefused), - ("function.arity", ProblemCode::DefinitionRefused), + ("transform.arity", ProblemCode::DefinitionRefused), ("mutation-uncertain", ProblemCode::MutationUncertain), ] { assert_eq!(for_error(internal), Some(public), "{internal}"); diff --git a/crates/registry-coordinator/src/project_check.rs b/crates/registry-coordinator/src/project_check.rs index 3d525d6182..f6ac57909a 100644 --- a/crates/registry-coordinator/src/project_check.rs +++ b/crates/registry-coordinator/src/project_check.rs @@ -126,6 +126,13 @@ fn workflow_binding_diagnostics( format!("/{}", field.replace('.', "/")) } }); + // A related runtime location the refusal names keeps its position here. + let related: Vec<(String, String)> = error + .diagnostics + .iter() + .flat_map(|diagnostic| diagnostic.related.iter()) + .map(|related| (related.path.clone(), related.message.clone())) + .collect(); let mut diagnostic = checked.error_at( runtime::KIND, "coordinator.runtime.workflow-binding", @@ -135,6 +142,9 @@ fn workflow_binding_diagnostics( "Use the same logical connection name in the project and runtime.".into() }), ); + for (path, message) in related { + checked.add_related_key(&mut diagnostic, &path, message); + } // A missing member has no span. Anchor it to its nearest existing runtime // container while retaining the missing path. if diagnostic diff --git a/crates/registry-coordinator/src/protocol.rs b/crates/registry-coordinator/src/protocol.rs index 8ef9776dd0..95c308bae0 100644 --- a/crates/registry-coordinator/src/protocol.rs +++ b/crates/registry-coordinator/src/protocol.rs @@ -71,6 +71,7 @@ impl Operation { | Self::StartProposal | Self::SubmitProposal | Self::ExternalCommand + | Self::InvokeServiceFunction | Self::RequestCollection | Self::RecordReceipt | Self::RequestDisbursement @@ -78,6 +79,12 @@ impl Operation { ) } + /// Calls whose bounded provider response becomes a step result only + /// through the operation's pinned interpretation Transform. + pub fn interprets_response(self) -> bool { + matches!(self, Self::ExternalCommand | Self::InvokeServiceFunction) + } + pub fn is_read(self) -> bool { self.descriptor().effect == crate::operations::EffectKind::Read } @@ -432,7 +439,7 @@ pub trait AdapterSet: Send + Sync { /// Observe a named completion of the exact accepted call. Both arguments /// are protected durable values. The host interprets bounded external - /// reads using the immutable Workflow Function, never an adapter script. + /// reads using the immutable Workflow Transform, never an adapter script. async fn observe_completion( &self, _request: &CallRequest, diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index 349a34a588..43124f7285 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -11,7 +11,7 @@ use std::path::Path; use std::process::ExitCode; -use registry_platform_config::{DeclaredPosture, SecretResolver}; +use registry_platform_config::{DeclaredPosture, PostureReport, SecretResolver}; use registry_platform_provision::cli::{ provision_transport, run_provision, OutputFormat, ProvisionArgs, ProvisionInput, }; @@ -94,9 +94,20 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Some( - secret_text(&resolver, reference, "/database/caBundleRef") - .map_err(|diagnostic| vec![*diagnostic])? - .as_bytes() + registry_platform_config::DatabaseMember::CaBundle + .read(&resolver, reference) + .map_err(|error| { + vec![*refusal( + "/database/caBundleRef", + ®istry_platform_config::describe_secret_failure( + "database.caBundleRef", + reference, + &error, + ), + error.suggested_action(), + )] + })? + .expose_secret() .to_vec(), ), None => None, @@ -112,6 +123,11 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result, Box> { - let secret = resolver.resolve(reference).map_err(|_| { + let secret = resolver.resolve(reference).map_err(|error| { refusal( pointer, - "the referenced secret could not be read", - "Make the secret the runtime file names available to this command.", + ®istry_platform_config::describe_secret_failure( + &pointer.trim_start_matches('/').replace('/', "."), + reference, + &error, + ), + error.suggested_action(), ) })?; let text = std::str::from_utf8(secret.expose_secret()).map_err(|_| { refusal( pointer, "the referenced secret is not UTF-8 text", - "Supply a UTF-8 PostgreSQL URL or PEM file.", + "Supply a UTF-8 PostgreSQL URL.", ) })?; Ok(Zeroizing::new(text.to_owned())) diff --git a/crates/registry-coordinator/src/read_in_force.rs b/crates/registry-coordinator/src/read_in_force.rs index eca262a4bb..0a19ca69a3 100644 --- a/crates/registry-coordinator/src/read_in_force.rs +++ b/crates/registry-coordinator/src/read_in_force.rs @@ -173,7 +173,7 @@ pub(crate) async fn read_in_force( } /// The subject fields a call names, when the mapping spells them out as a -/// literal or as nested fields. A subject built by a Function or read whole +/// literal or as nested fields. A subject built by a Transform or read whole /// from input is not known until the run. fn literal_subject_fields(input: &Mapping) -> Option> { let subject = match input { diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 20084f7317..d633c8616f 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -14,7 +14,7 @@ use registry_platform_httputil::{ use serde::{Deserialize, Deserializer, Serialize}; use serde_json::json; use std::{collections::BTreeMap, path::Path}; -use url::{Host, Url}; +use url::Url; use zeroize::Zeroizing; pub const API_VERSION: &str = "id.registrystack.org/formats/coordinator/runtime/v1alpha1"; @@ -237,6 +237,7 @@ pub enum ConnectionConfig { Payments(PaymentConnectionConfig), Scheduling(Box), ExternalHttp(crate::external_http::ExternalHttpConfig), + ServiceFunction(crate::external_http::ServiceFunctionConfig), Evaluation(crate::decision::DecisionConfig), } registry_platform_yaml::tagged_union!(ConnectionConfig); @@ -423,7 +424,7 @@ impl ConnectionConfig { None, c.result_check_seconds, ), - Self::ExternalHttp(_) | Self::Evaluation(_) => return None, + Self::ExternalHttp(_) | Self::ServiceFunction(_) | Self::Evaluation(_) => return None, }; Some(ProductBinding { product, @@ -445,6 +446,13 @@ impl ConnectionConfig { } } + pub fn service_function(&self) -> Option<&crate::external_http::ServiceFunctionConfig> { + match self { + Self::ServiceFunction(config) => Some(config), + _ => None, + } + } + pub fn decision(&self) -> Option<&crate::decision::DecisionConfig> { match self { Self::Evaluation(config) => Some(config), @@ -463,7 +471,7 @@ impl ConnectionConfig { Self::Payments(c) => Some(&mut c.authorization), Self::Scheduling(c) => Some(&mut c.authorization), Self::CaseworkReviewProducer(c) => Some(&mut c.authorization), - Self::ExternalHttp(_) | Self::Evaluation(_) => None, + Self::ExternalHttp(_) | Self::ServiceFunction(_) | Self::Evaluation(_) => None, } } @@ -496,6 +504,7 @@ impl ConnectionConfig { Self::Payments(_) => "payments", Self::Scheduling(_) => "scheduling", Self::ExternalHttp(_) => "external-http", + Self::ServiceFunction(_) => "service-function", Self::Evaluation(_) => "evaluation", } } @@ -515,6 +524,7 @@ impl Serialize for ConnectionConfig { Self::Payments(c) => ("payments", serde_json::to_value(c)), Self::Scheduling(c) => ("scheduling", serde_json::to_value(c)), Self::ExternalHttp(c) => ("external-http", serde_json::to_value(c)), + Self::ServiceFunction(c) => ("service-function", serde_json::to_value(c)), Self::Evaluation(c) => ("evaluation", serde_json::to_value(c)), }; let mut value = value.map_err(serde::ser::Error::custom)?; @@ -720,6 +730,29 @@ impl RuntimeConfig { ); } } + // A credential collision also points at the member it matches. + for (name, binding) in &loaded.config.connections { + let Some(function) = binding.service_function() else { + continue; + }; + let field = format!("connections.{name}"); + for (member, other, _) in loaded + .config + .function_credential_collisions(&field, function) + { + let member = pointer(&member); + if let Some(diagnostic) = diagnostics + .iter_mut() + .find(|diagnostic| diagnostic.path == member) + { + checked.add_related_key( + diagnostic, + &other, + "the member this credential matches", + ); + } + } + } if let Some(deployment) = &loaded.config.deployment { diagnostics.extend( deployment @@ -837,6 +870,38 @@ impl RuntimeConfig { &self.secret_providers, )); } + } else if let Some(function) = binding.service_function() { + errors.extend(function.findings(&field)); + match (&function.authorization, &function.host_key_ref) { + (Some(authorization), None) => { + errors.extend(authorization.secret_reference_finding( + &format!("{field}.authorization"), + &self.secret_providers, + )); + } + (None, Some(reference)) => { + let member = format!("{field}.hostKeyRef"); + if self + .secret_providers + .check_reference(&member, reference.as_str()) + .is_err() + { + errors.push(config_error( + &member, + "enable the secret provider named by the function host key reference", + )); + } + } + _ => errors.push(config_error( + &field, + "give the service function connection exactly one credential: authorization for an OAuth client, or hostKeyRef for a key only the function host accepts", + )), + } + errors.extend( + self.function_credential_collisions(&field, function) + .into_iter() + .map(|(_, _, error)| error), + ); } else if let Some(binding) = binding.decision() { errors.extend(binding.findings(&field)); if let Some(reference) = binding.token_ref() { @@ -1034,6 +1099,176 @@ impl RuntimeConfig { self.validate_workflow_effect_bindings(workflow) } + /// Every key reference this runtime file gives something other than a + /// service function host, with the JSON pointer of the member that holds + /// it: product, external and evaluation credentials, review completion + /// keys, event source keys, and the deployment's own keys. + pub(crate) fn other_key_references(&self) -> Vec<(String, &SecretReference)> { + let mut keys = Vec::new(); + for (name, binding) in &self.connections { + let at = |member: &str| pointer(&format!("connections.{name}.{member}")); + if let Some(product) = binding.product_binding() { + keys.push(( + at("authorization.signingKeyRef"), + &product.authorization.signing_key_ref, + )); + if let Some(observation) = product.observation_authorization { + keys.push(( + at("observationAuthorization.signingKeyRef"), + &observation.signing_key_ref, + )); + } + if let Some(completion) = product.completion { + keys.push(( + at("completion.hmacSha256KeyRef"), + &completion.hmac_sha256_key_ref, + )); + if let Some(previous) = &completion.previous_hmac_sha256_key_ref { + keys.push((at("completion.previousHmacSha256KeyRef"), previous)); + } + } + } else if let Some(external) = binding.external_http() { + if let Some(authorization) = &external.authorization { + keys.push(( + at("authorization.signingKeyRef"), + &authorization.signing_key_ref, + )); + } + } else if let Some(reference) = binding.decision().and_then(|d| d.token_ref()) { + keys.push((at("authorization.bearer.tokenRef"), reference)); + } + } + for (source, config) in &self.event_sources { + for (workflow, triggers) in &config.triggers { + for (trigger, key) in &triggers.0 { + let at = |member: &str| { + format!( + "/eventSources/{}/triggers/{}/{}/{member}", + registry_platform_yaml::escape_pointer_segment(source), + registry_platform_yaml::escape_pointer_segment(workflow.as_str()), + registry_platform_yaml::escape_pointer_segment(trigger.as_str()), + ) + }; + keys.push((at("hmacSha256KeyRef"), &key.hmac_sha256_key_ref)); + if let Some(previous) = &key.previous_hmac_sha256_key_ref { + keys.push((at("previousHmacSha256KeyRef"), previous)); + } + } + } + } + if let Some(deployment) = &self.deployment { + keys.push(( + "/deployment/auditKeyRef".to_owned(), + &deployment.audit_key_ref, + )); + for (version, reference) in &deployment.state_keys { + keys.push(( + format!( + "/deployment/stateKeys/{}/keyRef", + registry_platform_yaml::escape_pointer_segment(version) + ), + reference, + )); + } + keys.push(( + "/deployment/admissionKeyRef".to_owned(), + &deployment.admission_key_ref, + )); + } + keys + } + + /// Each member of a service function credential that collides with a + /// credential, product audience or key this runtime file gives something + /// else, as the dotted field of the colliding member, the JSON pointer of + /// the member it matches, and the refusal. A resource is compared after + /// normalisation against product, external and task authority resources + /// and the Coordinator's own audience. Startup also compares the resolved + /// key material. Other service function connections are not compared. + fn function_credential_collisions( + &self, + field: &str, + function: &crate::external_http::ServiceFunctionConfig, + ) -> Vec<(String, String, CoordinatorError)> { + let mut resources: Vec<(String, String)> = Vec::new(); + let mut clients: Vec<(&str, String)> = Vec::new(); + for (name, binding) in &self.connections { + let mut credentials: Vec<(&str, &AuthorizationConfig)> = Vec::new(); + if let Some(product) = binding.product_binding() { + credentials.push(("authorization", product.authorization)); + credentials.extend( + product + .observation_authorization + .map(|auth| ("observationAuthorization", auth)), + ); + } else if let Some(external) = binding.external_http() { + credentials.extend( + external + .authorization + .as_ref() + .map(|auth| ("authorization", auth)), + ); + } + for (member, credential) in credentials { + let at = |rest: &str| pointer(&format!("connections.{name}.{member}.{rest}")); + resources.push((normalised_resource(&credential.resource), at("resource"))); + if let Some(task) = &credential.task_authority { + resources.push(( + normalised_resource(&task.bootstrap_resource), + at("taskAuthority.bootstrapResource"), + )); + resources.push(( + normalised_resource(&task.exchange_audience), + at("taskAuthority.exchangeAudience"), + )); + } + clients.push((&credential.client_id, at("clientId"))); + } + } + if let Some(deployment) = &self.deployment { + for (id, issuer) in deployment.authentication.issuers.iter() { + resources.push(( + normalised_resource(&issuer.core.provider.audience), + format!( + "/deployment/authentication/issuers/{}/audience", + registry_platform_yaml::escape_pointer_segment(id.as_str()) + ), + )); + } + } + let keys = self.other_key_references(); + let refusal = |member: &str, other: &str| { + let member = format!("{field}.{member}"); + let error = config_error( + &member, + &format!("give the service function host its own resource, client and key; the value matches {other}, which would let the function act with that authority"), + ); + (member, other.to_owned(), error) + }; + let mut collisions = Vec::new(); + if let Some(own) = &function.authorization { + let resource = normalised_resource(&own.resource); + if let Some((_, other)) = resources.iter().find(|(value, _)| *value == resource) { + collisions.push(refusal("authorization.resource", other)); + } + if let Some((_, other)) = clients.iter().find(|(value, _)| *value == own.client_id) { + collisions.push(refusal("authorization.clientId", other)); + } + if let Some((other, _)) = keys + .iter() + .find(|(_, reference)| **reference == own.signing_key_ref) + { + collisions.push(refusal("authorization.signingKeyRef", other)); + } + } + if let Some(reference) = &function.host_key_ref { + if let Some((other, _)) = keys.iter().find(|(_, value)| *value == reference) { + collisions.push(refusal("hostKeyRef", other)); + } + } + collisions + } + /// Retained Runs require their effect bindings, independently of whether /// the event source that admitted them is still enabled for new starts. fn validate_workflow_effect_bindings( @@ -1091,6 +1326,39 @@ impl RuntimeConfig { call.connection, ))); } + if call.operation == crate::protocol::Operation::InvokeServiceFunction { + let named = workflow + .operations + .get(&call.alias) + .and_then(|operation| operation.service_function.as_deref()); + let bound = self + .connections + .get(&call.connection) + .and_then(ConnectionConfig::service_function) + .map(|binding| binding.function.as_str()); + if bound.is_some() && named != bound { + return Err(CoordinatorError::new( + "workflow-binding", + format!( + "the connection does not bind the service function {}", + named.unwrap_or("the operation names") + ), + ) + .at( + "workflow.yaml", + format!("/operations/{}/serviceFunction", call.alias), + ) + .suggest(format!( + "Name the function bound as connections.{}.function in runtime.yaml, or add one service-function connection for this function.", + call.connection + )) + .related( + "runtime.yaml", + &pointer(&format!("connections.{}.function", call.connection)), + "the function the connection binds", + )); + } + } if call.operation == crate::protocol::Operation::ExternalCommand && self .connections @@ -1181,6 +1449,38 @@ impl RuntimeConfig { identities.insert(name, identity); continue; } + if let Some(binding) = self + .connections + .get(name) + .and_then(ConnectionConfig::service_function) + { + let mut identity = serde_json::to_value(binding).map_err(|_| { + config_error("connections", "correct the service function binding model") + })?; + if let Some(auth) = identity + .get_mut("authorization") + .and_then(serde_json::Value::as_object_mut) + { + auth.remove("signingKeyRef"); + if let Some(scopes) = auth + .get_mut("scopes") + .and_then(serde_json::Value::as_array_mut) + { + scopes.sort_by(|a, b| a.as_str().cmp(&b.as_str())); + } + } + // Rotating the host key changes no binding, as rotating a + // signing key does not. + if let Some(binding) = identity.as_object_mut() { + if binding.remove("hostKeyRef").is_some() { + binding.insert("credential".into(), json!("host-key")); + } + } + identity["product"] = json!("service-function"); + identity["abi"] = json!("coordinator-service-function/v1"); + identities.insert(name, identity); + continue; + } let binding = self.connections[name] .product_binding() .expect("validated product binding"); @@ -1287,6 +1587,35 @@ fn runtime_id_collision_diagnostics( diagnostics } +/// The form a resource indicator is compared in: a URL with its scheme and +/// host in lower case, its default port dropped and one trailing `/` removed +/// from its path, or a URN with its `urn:` scheme and namespace identifier in +/// lower case. Any other identifier is compared exactly. +fn normalised_resource(resource: &str) -> String { + match Url::parse(resource) { + Ok(url) if url.has_host() => { + let text = url.to_string(); + match text.strip_suffix('/') { + Some(trimmed) if url.query().is_none() && url.fragment().is_none() => { + trimmed.to_owned() + } + _ => text, + } + } + _ => { + let mut parts = resource.splitn(3, ':'); + match (parts.next(), parts.next(), parts.next()) { + (Some(scheme), Some(namespace), Some(rest)) + if scheme.eq_ignore_ascii_case("urn") => + { + format!("urn:{}:{rest}", namespace.to_ascii_lowercase()) + } + _ => resource.to_owned(), + } + } + } +} + fn config_error(field: &str, action: &str) -> CoordinatorError { CoordinatorError::new( "coordinator.runtime-config.refused", @@ -1295,17 +1624,8 @@ fn config_error(field: &str, action: &str) -> CoordinatorError { .at("runtime.yaml", pointer(field)) .suggest(action) } -fn is_loopback(url: &Url) -> bool { - match url.host() { - Some(Host::Ipv4(ip)) => registry_platform_httputil::loopback::loopback_address(ip.into()), - Some(Host::Ipv6(ip)) => registry_platform_httputil::loopback::loopback_address(ip.into()), - _ => false, - } -} - fn check_endpoint(url: &Url) -> Result<()> { - let loopback = is_loopback(url); - if !(url.scheme() == "https" || (loopback && url.scheme() == "http")) + if crate::outbound::select_endpoint(url).is_none() || !url.username().is_empty() || url.password().is_some() || url.query().is_some() @@ -1451,7 +1771,7 @@ fn request_link<'de, D: Deserializer<'de>>(d: D) -> std::result::Result Result Result { - if call.operation != crate::protocol::Operation::ExternalCommand { + if !call.operation.interprets_response() { return Err(error( "scenario.reply", format!("/replies/{step}/{index}"), format!("step {step} calls {operation}, which takes no provider response reply"), - "Use response only for external.command/v1; use success for this operation's output.", + "Use response only for external.command/v1 or service.invoke-function/v1; use success for this operation's output.", )); } definition.operation_contract(call)? @@ -1007,7 +1007,7 @@ fn execute(definition: &Definition, scenario: &Scenario) -> Result Result { terminal = Some(value); break; }, crate::protocol::CompletionObservation::Pending { .. } => { now += chrono::Duration::seconds(i64::from(*interval_seconds)); }, - _ => return Err(error("scenario.wait-observation", format!("/waits/{step}/responses/{index}"), "the pinned polling interpretation did not establish a valid observation", "Correct the interpretation Function and response correlation under the named completion contract.")), + _ => return Err(error("scenario.wait-observation", format!("/waits/{step}/responses/{index}"), "the pinned polling interpretation did not establish a valid observation", "Correct the interpretation Transform and response correlation under the named completion contract.")), } } if let Some(value) = terminal { @@ -1867,7 +1867,7 @@ fn disbursement_acceptance(value: &Value) -> Option String { } /// The status of a synthetic command response the worker would never hand to -/// the interpretation Function, with the reply that models what the worker +/// the interpretation Transform, with the reply that models what the worker /// does instead. The worker reads the status before any body, so a scenario -/// cannot show the Function reading a redirect, a 429 or a server failure. +/// cannot show the Transform reading a redirect, a 429 or a server failure. fn uninterpreted_status(response: &Value) -> Option<(String, &'static str)> { use crate::external_http::{command_status, CommandStatus}; let Some(status) = response diff --git a/crates/registry-coordinator/src/worker.rs b/crates/registry-coordinator/src/worker.rs index 4675f79121..6b11b8b0a3 100644 --- a/crates/registry-coordinator/src/worker.rs +++ b/crates/registry-coordinator/src/worker.rs @@ -733,11 +733,9 @@ impl Worker { }, }; // A command's provider response becomes its step result only - // through the project's pinned interpretation Function. + // through the project's pinned interpretation Transform. let result = match result { - CallOutcome::Success(response) - if request.operation == crate::protocol::Operation::ExternalCommand => - { + CallOutcome::Success(response) if request.operation.interprets_response() => { crate::external_http::interpret_command( &definition, call, diff --git a/crates/registry-coordinator/tests/authored_project.rs b/crates/registry-coordinator/tests/authored_project.rs index 44e9355c97..ed49346dff 100644 --- a/crates/registry-coordinator/tests/authored_project.rs +++ b/crates/registry-coordinator/tests/authored_project.rs @@ -28,8 +28,8 @@ fn project() -> Value { "type": "finish", "outcome": "accepted", "output": { - "type": "function", - "function": "identity", + "type": "transform", + "transform": "identity", "inputs": { "arg0": { "type": "input" @@ -70,8 +70,8 @@ fn declared_refusal_project() -> Value { "type": "call", "operation": "invoke-breg-action", "input": { - "type": "function", - "function": "command", + "type": "transform", + "transform": "command", "inputs": { "arg0": { "type": "input" @@ -174,10 +174,10 @@ fn authored_project_converts_to_the_versioned_snapshot_abi() { fn project_check_keeps_a_positioned_duplicate_function_title_warning() { let root = tempfile::tempdir().unwrap(); let mut authored = declare_test_functions(&project()); - authored["functions"]["identity"]["label"] = json!("Identity function"); - let mut copy = authored["functions"]["identity"].clone(); + authored["transforms"]["identity"]["label"] = json!("Identity function"); + let mut copy = authored["transforms"]["identity"].clone(); copy["label"] = json!("identity function"); - authored["functions"]["identity-copy"] = copy; + authored["transforms"]["identity-copy"] = copy; let bytes = serde_json::to_vec(&authored).unwrap(); fs::write( root.path().join("functions.rhai"), @@ -191,10 +191,10 @@ fn project_check_keeps_a_positioned_duplicate_function_title_warning() { let finding = warnings .diagnostics() .iter() - .find(|diagnostic| diagnostic.code == "coordinator.project.duplicate-function-label") + .find(|diagnostic| diagnostic.code == "coordinator.project.duplicate-transform-label") .expect("the duplicate title warning survives project compilation"); - assert_eq!(finding.path, "/functions/identity-copy/label"); - assert_eq!(finding.related[0].path, "/functions/identity/label"); + assert_eq!(finding.path, "/transforms/identity-copy/label"); + assert_eq!(finding.related[0].path, "/transforms/identity/label"); assert!(finding.message.contains("`identity`")); assert!(finding.message.contains("`identity-copy`")); assert!(!finding.message.contains("Identity function")); @@ -204,10 +204,10 @@ fn project_check_keeps_a_positioned_duplicate_function_title_warning() { fn project_check_keeps_duplicate_title_warnings_beside_compile_errors() { let root = tempfile::tempdir().unwrap(); let mut authored = declare_test_functions(&project()); - authored["functions"]["identity"]["label"] = json!("Identity function"); - let mut copy = authored["functions"]["identity"].clone(); + authored["transforms"]["identity"]["label"] = json!("Identity function"); + let mut copy = authored["transforms"]["identity"].clone(); copy["label"] = json!("identity function"); - authored["functions"]["identity-copy"] = copy; + authored["transforms"]["identity-copy"] = copy; authored["workflow"]["steps"]["done"] = json!({ "type": "call", "operation": "missing-operation", @@ -220,7 +220,7 @@ fn project_check_keeps_duplicate_title_warnings_beside_compile_errors() { let error = authoring::parse_project(&path, fs::read(&path).unwrap()) .expect_err("the missing operation refuses compilation"); for code in [ - "coordinator.project.duplicate-function-label", + "coordinator.project.duplicate-transform-label", "coordinator.definition.operation", ] { assert!( @@ -237,7 +237,7 @@ fn project_check_keeps_duplicate_title_warnings_beside_compile_errors() { fn project_check_refuses_separator_lookalikes_in_the_function_namespace() { let root = tempfile::tempdir().unwrap(); let mut authored = project(); - authored["functions"] = json!({ + authored["transforms"] = json!({ "identity-fn": { "runtime": "rhai", "source": "functions.rhai", @@ -259,10 +259,10 @@ fn project_check_refuses_separator_lookalikes_in_the_function_namespace() { let finding = error .diagnostics .iter() - .find(|diagnostic| diagnostic.code == "coordinator.project.function-id-collision") + .find(|diagnostic| diagnostic.code == "coordinator.project.transform-id-collision") .expect("the function collision has its own finding"); - assert_eq!(finding.path, "/functions/identity_fn"); - assert_eq!(finding.related[0].path, "/functions/identity-fn"); + assert_eq!(finding.path, "/transforms/identity_fn"); + assert_eq!(finding.related[0].path, "/transforms/identity-fn"); assert!(finding.message.contains("`identity-fn`")); assert!(finding.message.contains("`identity_fn`")); } @@ -433,7 +433,7 @@ fn declared_refusal_is_available_only_on_its_edge_and_not_after_a_mixed_join() { .remove("refused"); joined["workflow"]["steps"]["joined"] = json!({ "type":"finish", "outcome":"joined", "output":{ - "type":"function", "function":"identity", "inputs": {"arg0": {"type":"step", "step":"act"}} + "type":"transform", "transform":"identity", "inputs": {"arg0": {"type":"step", "step":"act"}} } }); joined["workflow"]["outcomes"] = json!({"joined":{}}); @@ -569,7 +569,7 @@ fn reads_and_evaluations_accept_on_failure_but_mutations_refuse_it() { "apiVersion":"id.registrystack.org/formats/coordinator/project/v1alpha1", "kind":"CoordinatorProject", "project":{"id":"evaluation-failure-route","version":"1"}, - "functions":{"command":{ + "transforms":{"command":{ "runtime":"rhai","source":"functions.rhai","entrypoint":"command", "inputs":{"arg0":{"type":"object"}}, "output":{"operationInput":"evaluate"} @@ -579,7 +579,7 @@ fn reads_and_evaluations_accept_on_failure_but_mutations_refuse_it() { "input":{"type":"object"},"deadlineSeconds":60,"start":"act", "steps":{ "act":{"type":"call","operation":"evaluate", - "input":{"type":"function","function":"command","inputs":{"arg0":{"type":"input"}}}, + "input":{"type":"transform","transform":"command","inputs":{"arg0":{"type":"input"}}}, "next":"accepted","onFailure":"refused"}, "accepted":{"type":"finish","outcome":"accepted"}, "refused":{"type":"finish","outcome":"refused"} @@ -636,7 +636,7 @@ fn a_failure_route_has_no_call_output_and_names_a_declared_step() { project["workflow"]["steps"]["refused"] = json!({ "type":"finish", "outcome":"refused", - "output":{"type":"function","function":"identity","inputs":{"arg0":{"type":"step","step":"act"}}} + "output":{"type":"transform","transform":"identity","inputs":{"arg0":{"type":"step","step":"act"}}} }); project["workflow"]["outcomes"]["refused"] = json!({}); write_project(root.path(), &project, source); @@ -706,7 +706,7 @@ fn function_compile_diagnostics_keep_the_function_file_and_position() { .err() .expect("must refuse syntax"); let finding = &error.diagnostics[0]; - assert_eq!(finding.code, "coordinator.function.definition"); + assert_eq!(finding.code, "coordinator.transform.definition"); assert_eq!(finding.path, ""); let source = finding.source.as_ref().unwrap(); assert!(source.file.ends_with("functions.rhai")); @@ -746,7 +746,7 @@ fn linked_function_source_refusal_points_to_the_authored_reference() { .err() .expect("a linked source must refuse"); let finding = error.diagnostics.first().expect("a positioned finding"); - assert_eq!(finding.path, "/functions/identity/source"); + assert_eq!(finding.path, "/transforms/identity/source"); assert!(finding .source .as_ref() @@ -770,7 +770,7 @@ fn missing_function_source_keeps_the_operational_exit_and_authored_position() { .err() .expect("missing source must refuse"); assert_eq!(error.exit_code, 3); - assert_eq!(error.diagnostics[0].path, "/functions/identity/source"); + assert_eq!(error.diagnostics[0].path, "/transforms/identity/source"); assert!(error.diagnostics[0] .source .as_ref() @@ -786,7 +786,7 @@ fn execution_member_diagnostics_preserve_authored_step_names() { let mut project = project(); project["workflow"]["start"] = json!(name); project["workflow"]["steps"] = json!({name: { - "type":"wait-until", "waitUntil":{"type":"function", "function":"identity", "inputs": {"arg0": {"type":"input"}}}, + "type":"wait-until", "waitUntil":{"type":"transform", "transform":"identity", "inputs": {"arg0": {"type":"input"}}}, "next":"missing" }}); write_project( @@ -883,7 +883,7 @@ fn project_schema_matches_local_keys_bounds_and_foreign_schema_members() { assert!(schema["properties"].get("functionsFile").is_none()); for (pointer, minimum, maximum) in [ ("/properties/operations", 0, 64), - ("/properties/functions", 0, 128), + ("/properties/transforms", 0, 128), ("/properties/types", 0, 128), ("/$defs/AuthoredWorkflow/properties/steps", 1, 64), ("/$defs/AuthoredWorkflow/properties/outcomes", 1, 64), @@ -904,11 +904,11 @@ fn project_schema_matches_local_keys_bounds_and_foreign_schema_members() { .collect::>(); assert_eq!( tags, - ["function", "fields", "compare", "input", "step", "literal"] + ["transform", "fields", "compare", "input", "step", "literal"] ); let function = variants .iter() - .find(|variant| variant["properties"]["type"]["const"] == "function") + .find(|variant| variant["properties"]["type"]["const"] == "transform") .unwrap(); assert_eq!(function["properties"]["inputs"]["maxProperties"], 16); assert_eq!(schema["$defs"]["Fields"]["maxProperties"], 64); @@ -1111,9 +1111,9 @@ fn authoring_schemas_describe_every_member_and_form() { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -1135,6 +1135,6 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } diff --git a/crates/registry-coordinator/tests/authoring.rs b/crates/registry-coordinator/tests/authoring.rs index 5dd36350b5..1244874aff 100644 --- a/crates/registry-coordinator/tests/authoring.rs +++ b/crates/registry-coordinator/tests/authoring.rs @@ -34,14 +34,14 @@ fn authored_value(source: &str) -> Value { } fn computed_workflow() -> String { let mut workflow = authored_value(WORKFLOW); - workflow["functions"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after", + workflow["transforms"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after", "inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"string","format":"date-time"}}); - workflow["functions"]["read-request"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"read_request", + workflow["transforms"]["read-request"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"read_request", "inputs":{"input":{"typeRef":"workflow-input"}},"output":{"operationInput":"applications-read-record"}}); workflow["workflow"]["steps"]["due"]["waitUntil"] = - json!({"type":"function","function":"send-after","inputs":{"input":{"type":"input"}}}); + json!({"type":"transform","transform":"send-after","inputs":{"input":{"type":"input"}}}); workflow["workflow"]["steps"]["read-application"]["input"] = - json!({"type":"function","function":"read-request","inputs":{"input":{"type":"input"}}}); + json!({"type":"transform","transform":"read-request","inputs":{"input":{"type":"input"}}}); workflow.to_string() } fn computed_source() -> String { @@ -69,6 +69,44 @@ fn refused(result: registry_coordinator::Result) -> CoordinatorError } } +#[test] +fn authored_transforms_use_their_own_vocabulary_but_keep_the_frozen_snapshot_format() { + let authored = authored_value(WORKFLOW); + assert!(authored["transforms"]["notice-route"].is_object()); + assert!(authored.get("functions").is_none()); + let definition = fixture(); + let report = definition.explain().unwrap(); + assert!(report["transforms"]["notice-route"].is_object()); + assert!(report.get("functions").is_none()); + let permission = report["steps"] + .as_array() + .unwrap() + .iter() + .find(|step| step["id"] == "permission") + .unwrap(); + assert_eq!(permission["mapping"]["transform"], "notice-route"); + assert!(permission["mapping"].get("function").is_none()); + let snapshot = definition.snapshot().unwrap(); + let frozen: Value = serde_json::from_str(&snapshot).unwrap(); + assert!(frozen["workflow"]["functions"]["notice-route"].is_object()); + assert_eq!( + frozen["workflow"]["steps"]["permission"]["choose"]["function"], + "notice-route" + ); + let restored = Definition::from_snapshot(&snapshot).unwrap(); + assert_eq!(restored.snapshot().unwrap(), snapshot); + assert_eq!(restored.digest, definition.digest); +} + +#[test] +fn retired_function_declaration_points_to_transforms() { + let legacy = WORKFLOW.replace("\ntransforms:", "\nfunctions:"); + let error = refused(load(&legacy, SOURCE)); + assert!(error.diagnostics.iter().any(|diagnostic| { + diagnostic.path == "/functions" && diagnostic.suggested_action.contains("transforms") + })); +} + #[test] fn synthetic_fixture_maps_current_permission_and_receipt() { let definition = fixture(); @@ -121,14 +159,14 @@ fn synthetic_fixture_maps_current_permission_and_receipt() { fn shared_mapping_is_validated_only_for_the_executing_branch() { let workflow = json!({ "apiVersion":"id.registrystack.org/formats/coordinator/project/v1alpha1","kind":"CoordinatorProject","project":{"id":"shared-mapping","version":"1"}, - "functions":{ + "transforms":{ "branch":{"runtime":"rhai","source":"functions.rhai","entrypoint":"branch","inputs":{"input":{"type":"object"}},"output":{"type":"string","enum":["number","text"]}}, "value":{"runtime":"rhai","source":"functions.rhai","entrypoint":"value","inputs":{"input":{"type":"object"}},"output":{}} },"workflow":{"input":{"type":"object","required":["choice","value"],"properties":{"choice":{"enum":["number","text"]},"value":{}},"additionalProperties":false},"deadlineSeconds":3600,"start":"select", "steps":{ - "select":{"type":"choose","choose":{"type":"function","function":"branch","inputs":{"input":{"type":"input"}}},"cases":{"number":"finish-number","text":"finish-text"}}, - "finish-number":{"type":"finish","outcome":"number","output":{"type":"function","function":"value","inputs":{"input":{"type":"input"}}}}, - "finish-text":{"type":"finish","outcome":"text","output":{"type":"function","function":"value","inputs":{"input":{"type":"input"}}}} + "select":{"type":"choose","choose":{"type":"transform","transform":"branch","inputs":{"input":{"type":"input"}}},"cases":{"number":"finish-number","text":"finish-text"}}, + "finish-number":{"type":"finish","outcome":"number","output":{"type":"transform","transform":"value","inputs":{"input":{"type":"input"}}}}, + "finish-text":{"type":"finish","outcome":"text","output":{"type":"transform","transform":"value","inputs":{"input":{"type":"input"}}}} },"outcomes":{"number":{"type":"integer"},"text":{"type":"string"}}} }); let definition = load( @@ -283,7 +321,10 @@ fn bad_graphs_and_whole_value_references_refuse() { json!("arbitrary-http"), ), ("/workflow/deadlineSeconds", json!("é")), - ("/functions/notice-route/source", json!("../functions.rhai")), + ( + "/transforms/notice-route/source", + json!("../functions.rhai"), + ), ("/workflow/deadlineSeconds", json!("${DEADLINE}")), ] { let mut workflow = base.clone(); @@ -345,7 +386,7 @@ fn branch_timestamp_schema_and_missing_values_refuse_without_values() { let error = definition .evaluate("permission", &input(), &outputs) .unwrap_err(); - assert_eq!(error.code, "function.output"); + assert_eq!(error.code, "transform.output"); assert!(!error.to_string().contains(CANARY)); let definition = fixture(); assert_eq!( @@ -375,7 +416,7 @@ fn branch_timestamp_schema_and_missing_values_refuse_without_values() { .initial_due(&input(), instant("2026-10-09T09:00:00Z")) .unwrap_err() .code, - "function.output" + "transform.output" ); } @@ -390,7 +431,7 @@ fn pure_profile_has_no_clock_sleep_or_io_and_limits_computation() { &source.replace("input.sendAfter", expression), )); assert_eq!( - error.code, "coordinator.function.unknown-call", + error.code, "coordinator.transform.unknown-call", "{expression}" ); } @@ -405,7 +446,7 @@ fn pure_profile_has_no_clock_sleep_or_io_and_limits_computation() { .evaluate("due", &input(), &BTreeMap::new()) .unwrap_err() .code, - "function.resource-limit" + "transform.resource-limit" ); } let definition = load( @@ -636,14 +677,14 @@ fn resource_limits_include_recursion_input_values_and_non_object_commands() { .evaluate("due", &input(), &BTreeMap::new()) .unwrap_err() .code, - "function.resource-limit" + "transform.resource-limit" ); let definition = fixture(); let mut excessive = input(); excessive["sendAfter"] = json!("x".repeat(16385)); assert_eq!( definition.validate_input(&excessive).unwrap_err().code, - "function.value-limit" + "transform.value-limit" ); let definition = load( &workflow, @@ -658,7 +699,7 @@ fn resource_limits_include_recursion_input_values_and_non_object_commands() { .evaluate("read-application", &input(), &BTreeMap::new()) .unwrap_err() .code, - "function.output" + "transform.output" ); } @@ -721,10 +762,10 @@ fn authoring_diagnostics_locate_graph_reference_and_functions_without_runtime_va &source.replace("fn send_after(input)", "fn send_after(input, extra)"), )); // The step that calls the function is where the mismatch is placed. - assert_eq!(error.code, "coordinator.function.definition"); + assert_eq!(error.code, "coordinator.transform.definition"); assert_eq!( error.field.as_deref(), - Some("/functions/send-after/entrypoint") + Some("/transforms/send-after/entrypoint") ); assert!(error.diagnostics[0] .source diff --git a/crates/registry-coordinator/tests/authoring_findings.rs b/crates/registry-coordinator/tests/authoring_findings.rs index 61298639b1..84213d3742 100644 --- a/crates/registry-coordinator/tests/authoring_findings.rs +++ b/crates/registry-coordinator/tests/authoring_findings.rs @@ -172,7 +172,7 @@ fn a_function_returning_an_undeclared_label_is_reported_at_its_step_by_check_and let findings = check["diagnostics"].as_array().unwrap(); assert_eq!(findings.len(), 1, "{check}"); let finding = &findings[0]; - assert_eq!(finding["code"], "coordinator.function.output"); + assert_eq!(finding["code"], "coordinator.transform.output"); assert_eq!(finding["path"], "/workflow/steps/permission/choose"); assert!(finding["source"]["file"] .as_str() @@ -181,7 +181,7 @@ fn a_function_returning_an_undeclared_label_is_reported_at_its_step_by_check_and assert_eq!(finding["source"]["line"], workflow_line("choose:") + 1); let message = finding["message"].as_str().unwrap(); for expected in [ - "function notice-route returned a value of class string", + "Transform notice-route returned a value of class string", "declared output schema refuses it", ] .into_iter() @@ -215,14 +215,14 @@ fn a_rhai_failure_names_its_kind_and_position_offline() { let (check, test) = refused(&root); assert_eq!(check["diagnostics"], test["diagnostics"], "{check}\n{test}"); let finding = &check["diagnostics"][0]; - assert_eq!(finding["code"], "coordinator.function.execution"); + assert_eq!(finding["code"], "coordinator.transform.execution"); assert_eq!(finding["path"], "/workflow/steps/permission/choose"); assert_eq!(finding["source"]["line"], workflow_line("choose:") + 1); let message = finding["message"].as_str().unwrap(); // The kind of failure and its position in functions.rhai, never the // engine's own words, which may repeat the values it was given. assert!( - message.contains("function notice-route failed: a property is missing in function notice_route at line 6, column "), + message.contains("Transform notice-route failed: a property is missing in function notice_route at line 6, column "), "{message}" ); assert!(!message.contains("member"), "{message}"); @@ -245,10 +245,10 @@ fn a_thrown_rhai_error_names_its_kind_and_position_but_no_value() { let (check, test) = refused(&root); assert_eq!(check["diagnostics"], test["diagnostics"], "{check}\n{test}"); let finding = &check["diagnostics"][0]; - assert_eq!(finding["code"], "coordinator.function.execution"); + assert_eq!(finding["code"], "coordinator.transform.execution"); let message = finding["message"].as_str().unwrap(); assert!( - message.contains("function notice-route failed: an error was thrown in function notice_route at line 6, column "), + message.contains("Transform notice-route failed: an error was thrown in function notice_route at line 6, column "), "{message}" ); assert_unrepeated(&root, &[MARKER, RECORD_ID]); @@ -273,7 +273,7 @@ fn a_failure_in_a_called_function_is_placed_in_that_function() { let message = check["diagnostics"][0]["message"].as_str().unwrap(); assert!( message.contains( - "function notice-route failed: an error was thrown in function helper at line 10, column 5" + "Transform notice-route failed: an error was thrown in function helper at line 10, column 5" ), "{message}" ); @@ -548,18 +548,18 @@ fn a_refused_step_value_is_named_by_its_class_and_rule_never_by_value() { let mut functions = FUNCTIONS.to_owned(); let expected = match kind { "wait" => { - workflow["functions"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"string"}}); - workflow["workflow"]["steps"]["due"]["waitUntil"] = json!({"type":"function","function":"send-after","inputs":{"input":{"type":"input"}}}); + workflow["transforms"]["send-after"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"send_after","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"string"}}); + workflow["workflow"]["steps"]["due"]["waitUntil"] = json!({"type":"transform","transform":"send-after","inputs":{"input":{"type":"input"}}}); functions.push_str(&format!( "\nfn send_after(args) {{ \"{MARKER}\" + args.input.applicationId }}" )); - "function send-after returned a value of class string; expected an RFC 3339 instant with an offset" + "Transform send-after returned a value of class string; expected an RFC 3339 instant with an offset" } "finish" => { - workflow["functions"]["accepted-output"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"accepted_output","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"object"}}); - workflow["workflow"]["steps"]["accepted"]["output"] = json!({"type":"function","function":"accepted-output","inputs":{"input":{"type":"input"}}}); + workflow["transforms"]["accepted-output"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"accepted_output","inputs":{"input":{"typeRef":"workflow-input"}},"output":{"type":"object"}}); + workflow["workflow"]["steps"]["accepted"]["output"] = json!({"type":"transform","transform":"accepted-output","inputs":{"input":{"type":"input"}}}); functions.push_str(&format!("\nfn accepted_output(args) {{ #{{messageId: \"{MARKER}\" + args.input.applicationId}} }}")); - "function accepted-output returned a value of class object; the message-accepted outcome schema refuses it at /messageId by its rule /properties/messageId/format" + "Transform accepted-output returned a value of class object; the message-accepted outcome schema refuses it at /messageId by its rule /properties/messageId/format" } _ => { fs::write( @@ -747,13 +747,13 @@ fn a_connection_name_is_bound_at_deployment_and_changes_the_semantic_revision() #[test] fn an_unknown_function_is_reported_at_its_step_with_the_declared_functions() { let mut workflow = authored_value(); - workflow["workflow"]["steps"]["notify"]["input"]["function"] = json!("notice-reqest"); + workflow["workflow"]["steps"]["notify"]["input"]["transform"] = json!("notice-reqest"); let findings = checked_value(workflow); assert_eq!(findings.len(), 1); finding( &findings, - "/workflow/steps/notify/input/function", - "coordinator.mapping.function", + "/workflow/steps/notify/input/transform", + "coordinator.mapping.transform", &["notice-reqest", "notice-request", "notice-route"], ); } @@ -770,8 +770,8 @@ fn a_function_called_with_the_wrong_inputs_is_reported_at_its_step() { finding( &findings, "/workflow/steps/notify/input/inputs", - "coordinator.mapping.function", - &["named Function inputs", "signature"], + "coordinator.mapping.transform", + &["named Transform inputs", "signature"], ); } @@ -855,7 +855,7 @@ fn authored_semantic_errors_and_warnings_share_one_file_budget() { fn check_reports_every_independent_error_in_one_run() { let mut workflow = authored_value(); workflow["workflow"]["start"] = json!("begin"); - workflow["workflow"]["steps"]["permission"]["choose"]["function"] = json!("notice-rout"); + workflow["workflow"]["steps"]["permission"]["choose"]["transform"] = json!("notice-rout"); workflow["workflow"]["steps"]["skipped"]["outcome"] = json!("no-permission"); let findings = checked_value(workflow); let mut paths = findings @@ -868,7 +868,7 @@ fn check_reports_every_independent_error_in_one_run() { [ "/workflow/outcomes/no-current-permission", "/workflow/start", - "/workflow/steps/permission/choose/function", + "/workflow/steps/permission/choose/transform", "/workflow/steps/skipped/outcome" ], "{findings:#?}" diff --git a/crates/registry-coordinator/tests/breg_action_native.rs b/crates/registry-coordinator/tests/breg_action_native.rs index d0c6dc75cd..cf80d52ccb 100644 --- a/crates/registry-coordinator/tests/breg_action_native.rs +++ b/crates/registry-coordinator/tests/breg_action_native.rs @@ -390,7 +390,7 @@ types: operations: act: {uses: breg.invoke-action/v1, connection: applications, action: {contract: source, id: update-item}} notify: {uses: messaging.submit-message/v1, connection: notices} -functions: +transforms: action_request: runtime: rhai source: functions.rhai @@ -417,17 +417,17 @@ workflow: act: type: call operation: act - input: {type: function, function: action_request, inputs: {input: {type: input}}} + input: {type: transform, transform: action_request, inputs: {input: {type: input}}} next: notify notify: type: call operation: notify - input: {type: function, function: notice_request, inputs: {action: {type: step, step: act}}} + input: {type: transform, transform: notice_request, inputs: {action: {type: step, step: act}}} next: done done: type: finish outcome: accepted - output: {type: function, function: result, inputs: {action: {type: step, step: act}, notice: {type: step, step: notify}}} + output: {type: transform, transform: result, inputs: {action: {type: step, step: act}, notice: {type: step, step: notify}}} outcomes: accepted: {typeRef: accepted-output} "#).unwrap(); diff --git a/crates/registry-coordinator/tests/caller_contract.rs b/crates/registry-coordinator/tests/caller_contract.rs index ed8fe5e54f..ab1e632305 100644 --- a/crates/registry-coordinator/tests/caller_contract.rs +++ b/crates/registry-coordinator/tests/caller_contract.rs @@ -651,7 +651,7 @@ fn human_check_prints_the_explicit_setting_with_its_pointer() { assert!(output.status.success()); let stdout = String::from_utf8(output.stdout).unwrap(); assert!(stdout.lines().any(|line| line == format!( - "Explicit production setting platform.posture.jwt-access-token at {ISSUERS}/main/accessTokenType. admits access tokens typed JWT. ID tokens stay refused." + "Explicit production setting platform.posture.jwt-access-token at {ISSUERS}/main/accessTokenType. Admits access tokens typed JWT. ID tokens stay refused." )), "{stdout}"); } diff --git a/crates/registry-coordinator/tests/canonical_model.rs b/crates/registry-coordinator/tests/canonical_model.rs index 69c54e5720..34ccf333af 100644 --- a/crates/registry-coordinator/tests/canonical_model.rs +++ b/crates/registry-coordinator/tests/canonical_model.rs @@ -10,10 +10,10 @@ fn project() -> Value { "project": {"id":"typed-workflow","version":"1"}, "types": {"request": {"type":"object","additionalProperties":false,"required":["text"], "properties":{"text":{"type":"string"}}}}, - "functions": {"render": {"runtime":"rhai","source":"functions.rhai","entrypoint":"render", + "transforms": {"render": {"runtime":"rhai","source":"functions.rhai","entrypoint":"render", "inputs":{"request":{"typeRef":"request"}},"output":{"type":"string"}}}, "workflow": {"input":{"typeRef":"request"},"deadlineSeconds":3600,"start":"done", - "steps":{"done":{"type":"finish","outcome":"rendered","output":{"type":"function","function":"render","inputs":{"request":{"type":"input"}}}}}, + "steps":{"done":{"type":"finish","outcome":"rendered","output":{"type":"transform","transform":"render","inputs":{"request":{"type":"input"}}}}}, "outcomes":{"rendered":{"type":"string"}}} }) } @@ -57,7 +57,7 @@ fn named_function_inputs_are_typed_and_the_snapshot_restores_without_sources() { let error = definition .evaluate("done", &json!({"text":42}), &BTreeMap::new()) .unwrap_err(); - assert_eq!(error.code, "function.input"); + assert_eq!(error.code, "transform.input"); assert!(!error.message.contains("42")); } @@ -69,10 +69,10 @@ fn presentation_version_and_unreferenced_definitions_do_not_change_workflow_revi edited["project"]["description"] = json!("Shows a text."); edited["project"]["version"] = json!("next"); edited["workflow"]["steps"]["done"]["label"] = json!("Show the text"); - edited["functions"]["render"]["label"] = json!("Render a notice"); + edited["transforms"]["render"]["label"] = json!("Render a notice"); edited["types"]["request"]["properties"]["text"]["description"] = json!("Public text"); edited["types"]["unrelated"] = json!({"type":"integer"}); - edited["functions"]["unrelated"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"render", + edited["transforms"]["unrelated"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"render", "inputs":{"ignored":{"type":"integer"}},"output":{"type":"string"}}); let edited = load(&edited, SOURCE).unwrap(); assert_eq!(initial.digest, edited.digest); @@ -150,14 +150,14 @@ fn an_event_trigger_label_and_description_do_not_change_workflow_revision() { fn a_title_is_refused_with_label_as_its_replacement() { for (pointer, set) in [ ("/title", "project"), - ("/functions/render/title", "function"), + ("/transforms/render/title", "transform"), ("/workflow/steps/done/title", "step"), ("/operations/read-job/title", "operation"), ] { let mut edited = project(); match set { "project" => edited["title"] = json!("Readable workflow"), - "function" => edited["functions"]["render"]["title"] = json!("Render a notice"), + "transform" => edited["transforms"]["render"]["title"] = json!("Render a notice"), "operation" => { edited["operations"] = json!({"read-job":{"title":"Read the job","uses":"external.get/v1","connection":"jobs"}}); } @@ -185,11 +185,11 @@ fn changed_function_code_or_limits_changes_workflow_revision() { .digest ); let mut edited = project(); - edited["functions"]["render"]["limits"] = json!({"operations":500}); + edited["transforms"]["render"]["limits"] = json!({"operations":500}); let edited = load(&edited, SOURCE).unwrap(); assert_ne!(initial.digest, edited.digest); assert_eq!( - edited.explain().unwrap()["functions"]["render"]["limits"]["operations"], + edited.explain().unwrap()["transforms"]["render"]["limits"]["operations"], 500 ); } @@ -207,7 +207,7 @@ fn signature_names_and_closed_output_are_enforced_without_rendering_values() { let error = definition .evaluate("done", &json!({"text":"private-canary"}), &BTreeMap::new()) .unwrap_err(); - assert_eq!(error.code, "function.output"); + assert_eq!(error.code, "transform.output"); assert!(!error.message.contains("private-canary")); } @@ -225,8 +225,8 @@ fn schema_references_resolve_nested_properties_and_preserve_reference_sites() { ); assert!(references["/workflow/input/typeRef"]["source"]["line"].is_number()); assert_eq!( - references["/workflow/steps/done/output/function"]["target"], - "/functions/render" + references["/workflow/steps/done/output/transform"]["target"], + "/transforms/render" ); } @@ -255,13 +255,13 @@ fn schema_cycles_mixtures_and_undeclared_references_point_to_authored_fields() { #[test] fn the_default_profile_has_no_clock_and_narrowing_cannot_widen_it() { let error = refused(&project(), "fn render(inputs) { timestamp().to_string() }"); - assert_eq!(error.code, "coordinator.function.unknown-call"); + assert_eq!(error.code, "coordinator.transform.unknown-call"); let mut edited = project(); - edited["functions"]["render"]["limits"] = json!({"operations":100001}); + edited["transforms"]["render"]["limits"] = json!({"operations":100001}); let error = refused(&edited, SOURCE); assert_eq!( error.diagnostics[0].path, - "/functions/render/limits/operations" + "/transforms/render/limits/operations" ); assert_eq!(error.diagnostics[0].code, "config.out-of-range"); } @@ -287,7 +287,7 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { let mut edited = project(); edited["operations"] = json!({"read-job":{"uses":"external.get/v1","connection":"jobs","responseSchema":{"type":"object","required":["status","body"],"additionalProperties":false,"properties":{"status":{"type":"integer"},"body":{"type":"object"}}}, "completions":{"terminal":{"type":"bounded-poll","interpret":"observe","intervalSeconds":30}}}}); - edited["functions"] = json!({"observe":{"runtime":"rhai","source":"functions.rhai","entrypoint":"observe", + edited["transforms"] = json!({"observe":{"runtime":"rhai","source":"functions.rhai","entrypoint":"observe", "inputs":{"command":{"operationInput":"read-job"},"response":{"operationOutput":"read-job"}},"output":{"oneOf":[ {"type":"object","additionalProperties":false,"required":["state"],"properties":{"state":{"type":"string","const":"pending"}}}, {"type":"object","additionalProperties":false,"required":["state","result"],"properties":{"state":{"type":"string","const":"complete"},"result":{"type":"string"}}}, @@ -341,7 +341,7 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { assert!(definition .validate_outcome("terminal", &json!({"state":"pending"})) .is_err()); - edited["functions"]["observe"]["output"]["oneOf"][1]["title"] = + edited["transforms"]["observe"]["output"]["oneOf"][1]["title"] = json!("A successful job observation"); let retitled = load(&edited, "fn observe(inputs) { #{state: \"pending\"} }").unwrap(); assert_eq!(definition.digest, retitled.digest); @@ -350,7 +350,7 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { "type":"object","required":["id"],"additionalProperties":false, "properties":{"id":{"$ref":"#/$defs/identifier"}} }); - edited["functions"]["observe"]["output"]["oneOf"][1]["properties"]["result"] = + edited["transforms"]["observe"]["output"]["oneOf"][1]["properties"]["result"] = json!({"typeRef":"job-result"}); let referenced = load(&edited, "fn observe(inputs) { #{state: \"pending\"} }").unwrap(); referenced @@ -371,10 +371,10 @@ fn poll_completion_uses_base_schemas_then_resolves_typed_terminal_output() { restored .validate_outcome("terminal", &json!({"state":"refused","code":"job-failed"})) .unwrap(); - edited["functions"]["observe"]["output"] = + edited["transforms"]["observe"]["output"] = json!({"completionOutput":{"operation":"read-job","name":"terminal"}}); let error = refused(&edited, "fn observe(inputs) { #{state: \"pending\"} }"); - assert_eq!(error.diagnostics[0].path, "/functions/observe/output"); + assert_eq!(error.diagnostics[0].path, "/transforms/observe/output"); } #[cfg(feature = "schema")] @@ -397,7 +397,7 @@ fn whole_schema_references_rebase_local_definitions_when_embedded() { "$defs":{"text":{"type":"string","minLength":2}}, "properties":{"value":{"$ref":"#/$defs/text"}}}); edited["types"]["request"]["properties"]["text"] = json!({"typeRef":"message"}); - edited["functions"]["render"]["output"] = json!({"typeRef":"message"}); + edited["transforms"]["render"]["output"] = json!({"typeRef":"message"}); edited["workflow"]["outcomes"]["rendered"] = json!({"typeRef":"message"}); let definition = load(&edited, SOURCE).unwrap(); assert!(definition @@ -416,7 +416,7 @@ fn whole_schema_references_rebase_local_definitions_when_embedded() { #[test] fn function_source_assets_cannot_escape_the_project() { let mut edited = project(); - edited["functions"]["render"]["source"] = json!("../outside.rhai"); + edited["transforms"]["render"]["source"] = json!("../outside.rhai"); let error = refused(&edited, SOURCE); assert!(error.message.contains("relative path")); } diff --git a/crates/registry-coordinator/tests/cli_authoring.rs b/crates/registry-coordinator/tests/cli_authoring.rs index 81df08b754..fc36973895 100644 --- a/crates/registry-coordinator/tests/cli_authoring.rs +++ b/crates/registry-coordinator/tests/cli_authoring.rs @@ -201,7 +201,7 @@ fn init_check_and_explain_work_without_database_or_signing_keys() { ]); assert!(explained.status.success()); let result: Value = serde_json::from_slice(&explained.stdout).unwrap(); - assert!(result["functions"] + assert!(result["transforms"] .as_object() .unwrap() .values() diff --git a/crates/registry-coordinator/tests/decision_runtime.rs b/crates/registry-coordinator/tests/decision_runtime.rs index 4deebb2b74..d29ba52444 100644 --- a/crates/registry-coordinator/tests/decision_runtime.rs +++ b/crates/registry-coordinator/tests/decision_runtime.rs @@ -301,3 +301,105 @@ fn decision_runtime_preserves_unknown_key_positions_and_defers_environment_value .all(|finding| finding.severity != registry_platform_yaml::Severity::Error)); assert!(checked.defers("/connections/assessor/baseUrl")); } + +// Transport selection. These pin the decision destinations a deployment +// admits and how a refused or unreachable one is answered, whatever selects +// the transport. + +fn with_base(base: &str, authorization: Value) -> Value { + let mut d = document(); + d["connections"]["assessor"]["baseUrl"] = json!(base); + d["connections"]["assessor"]["authorization"] = authorization; + d +} + +fn bearer() -> Value { + json!({"bearer":{"tokenRef":"secret:env/UNRESOLVED_DECISION_TEST_TOKEN","principal":"fixture-account"}}) +} + +#[test] +fn decision_destinations_admit_https_and_numeric_loopback_http_only() { + for base in [ + "https://decision.example.test/tenant", + "https://10.0.0.8/tenant", + "http://127.0.0.1:8080/tenant", + "http://127.1.2.3/tenant", + "http://[::1]:8080/tenant", + "http://[::ffff:127.0.0.1]:8080/tenant", + ] { + load(&with_base(base, bearer())).unwrap_or_else(|_| panic!("{base} is admitted")); + } + for base in [ + "http://localhost:8080/tenant", + "http://decision.example.test/tenant", + "http://10.0.0.1/tenant", + "http://user@127.0.0.1/tenant", + "ftp://decision.example.test/tenant", + ] { + assert!( + load(&with_base(base, bearer())).is_err(), + "{base} is refused" + ); + } +} + +#[test] +fn local_decision_authorization_stays_on_numeric_loopback() { + load(&with_base( + "http://127.0.0.1:8080/tenant", + json!({"local":{}}), + )) + .unwrap(); + load(&with_base("http://[::1]:8080/tenant", json!({"local":{}}))).unwrap(); + for base in [ + "https://decision.example.test/tenant", + "https://localhost/tenant", + "http://localhost:8080/tenant", + ] { + assert!( + load(&with_base(base, json!({"local":{}}))).is_err(), + "local authorization is refused at {base}" + ); + } +} + +/// Evaluate once against `base` with a bearer credential that never resolves, +/// so a destination checked before credentials answers its own outcome. +async fn evaluate_unresolved_credential(base: &str) -> CallOutcome { + let adapters = HttpAdapters::new(&load(&with_base(base, bearer())).unwrap()).unwrap(); + let request = CallRequest { + operation_contract: None, + connection: "assessor".into(), + operation: Operation::EvaluateDecision, + input: json!({"state":{"summary":"synthetic"},"questions":{"ready":{"type":"predicate","instructions":"Ready?"}}}), + idempotency_key: None, + }; + let Ok(Some(prepared)) = adapters.prepare(&request).await else { + panic!("inert preparation must succeed") + }; + adapters.call_prepared(&request, Some(&prepared)).await +} + +#[tokio::test] +async fn a_metadata_decision_destination_is_refused_before_acquiring_credentials() { + for base in [ + "https://169.254.169.254/tenant", + "https://[::ffff:169.254.169.254]/tenant", + ] { + let outcome = evaluate_unresolved_credential(base).await; + assert!( + matches!(&outcome, CallOutcome::Refused { code } if code == "decision-invalid-command"), + "{base} is refused before credentials" + ); + } +} + +#[tokio::test] +async fn an_unresolvable_decision_destination_is_unavailable_before_credentials() { + let outcome = + evaluate_unresolved_credential("https://coordinator-transport.invalid/tenant").await; + assert!( + matches!(&outcome, CallOutcome::Retryable { code, .. } if code == "decision-unavailable"), + "an unresolvable destination is unavailable" + ); +} diff --git a/crates/registry-coordinator/tests/external_command_project.rs b/crates/registry-coordinator/tests/external_command_project.rs index a2dd79412d..16b5ef7a7b 100644 --- a/crates/registry-coordinator/tests/external_command_project.rs +++ b/crates/registry-coordinator/tests/external_command_project.rs @@ -249,17 +249,17 @@ fn the_interpretation_takes_the_command_and_its_bounded_response() { #[test] fn the_interpretation_declares_accepted_and_only_known_states() { let findings = refused(&[("const: accepted", "const: complete")]); - finding(&findings, "/functions/bill-outcome/output", &["accepted"]); + finding(&findings, "/transforms/bill-outcome/output", &["accepted"]); let findings = refused(&[("enum: [account-closed]", "minLength: 1")]); finding( &findings, - "/functions/bill-outcome/output", + "/transforms/bill-outcome/output", &["closed enum"], ); let findings = refused(&[("const: uncertain", "const: pending")]); - finding(&findings, "/functions/bill-outcome/output", &["uncertain"]); + finding(&findings, "/transforms/bill-outcome/output", &["uncertain"]); } #[test] diff --git a/crates/registry-coordinator/tests/external_http.rs b/crates/registry-coordinator/tests/external_http.rs index 5108fef85a..f6671d8131 100644 --- a/crates/registry-coordinator/tests/external_http.rs +++ b/crates/registry-coordinator/tests/external_http.rs @@ -518,3 +518,56 @@ fn offline_contract_refuses_unsafe_urls_paths_and_external_schema_fetches() { .to_string() .contains("sensitive-invalid-resource-canary")); } + +// Transport selection. These pin the destinations a reviewed external +// connection admits and how a refused or unreachable one is answered, whatever +// selects the transport. + +#[test] +fn external_destinations_admit_https_and_numeric_loopback_http_only() { + for base in [ + "https://directory.example.test/", + "https://10.0.0.8/", + "https://[fd00::8]/", + "http://127.0.0.1:8080/", + "http://127.1.2.3/", + "http://[::1]:8080/", + "http://[::ffff:127.0.0.1]:8080/", + ] { + config(base) + .validate() + .unwrap_or_else(|_| panic!("{base} is admitted")); + } + for base in [ + "http://localhost:8080/", + "http://directory.example.test/", + "http://10.0.0.1/", + "http://192.168.1.4/", + "http://user@127.0.0.1/", + "ftp://directory.example.test/", + ] { + let mut admitted = config("https://directory.example.test/"); + admitted.base_url = base.parse().unwrap(); + assert!(admitted.validate().is_err(), "{base} is refused"); + } +} + +#[tokio::test] +async fn a_mapped_metadata_address_is_refused_before_acquiring_credentials() { + let mut config = config("https://[::ffff:169.254.169.254]"); + config.authorization = Some(authorization()); + let connection = ExternalHttpConnection::new(&config, Some(Arc::new(SlowTokens))).unwrap(); + assert!( + matches!(connection.get(&json!({"path":"offices"}), false).await, + CallOutcome::Refused { code } if code == "external-destination-refused") + ); +} + +#[tokio::test] +async fn an_unresolvable_destination_is_unavailable_not_refused() { + let connection = connection(&config("https://coordinator-transport.invalid")); + assert!(matches!( + connection.get(&json!({"path":"offices"}), false).await, + CallOutcome::Retryable { code, .. } if code == "external-unavailable" + )); +} diff --git a/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml b/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml index a2207e13fe..93f1742130 100644 --- a/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml +++ b/crates/registry-coordinator/tests/fixtures/external-command/workflow.yaml @@ -50,7 +50,7 @@ types: properties: state: {type: string, const: uncertain} -functions: +transforms: bill-request: runtime: rhai source: functions.rhai @@ -84,8 +84,8 @@ workflow: type: call operation: create-bill input: - type: function - function: bill-request + type: transform + transform: bill-request inputs: request: {type: input} next: billed diff --git a/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml b/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml index 6285eec536..3acfdfe8f6 100644 --- a/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml +++ b/crates/registry-coordinator/tests/fixtures/review-wait/workflow.yaml @@ -14,7 +14,7 @@ types: applicationVersion: {type: string, minLength: 1, maxLength: 64} applicationDigest: {type: string, pattern: "^sha256:[0-9a-f]{64}$"} email: {type: string, format: email} -functions: +transforms: review-request: runtime: rhai source: functions.rhai @@ -41,7 +41,7 @@ workflow: submit-review: type: call operation: submit-review-request - input: {type: function, function: review-request, inputs: {input: {type: input}}} + input: {type: transform, transform: review-request, inputs: {input: {type: input}}} next: await-review await-review: type: wait-for @@ -62,7 +62,7 @@ workflow: notify: type: call operation: submit-message - input: {type: function, function: notice-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} + input: {type: transform, transform: notice-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} next: notice-sent notice-sent: type: finish diff --git a/crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml new file mode 100644 index 0000000000..bfed482cd8 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/drafted.yaml @@ -0,0 +1,24 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: drafted +admittedAt: '2026-12-01T00:00:00Z' +input: + reference: application-001 +replies: + draft: + - type: response + value: + status: 200 + body: + draftId: draft-001 +expect: + path: + - draft + - drafted + state: completed + outcome: + type: named + value: drafted + output: + draftId: draft-001 diff --git a/crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml new file mode 100644 index 0000000000..da5ba94519 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/not-eligible.yaml @@ -0,0 +1,24 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: not-eligible +admittedAt: '2026-12-01T00:00:00Z' +input: + reference: application-002 +replies: + draft: + - type: response + value: + status: 422 + body: + reason: not-eligible +expect: + path: + - draft + - not-drafted + state: completed + outcome: + type: named + value: not-drafted + output: + refusalCode: not-eligible diff --git a/crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml new file mode 100644 index 0000000000..13b5d006da --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/fixtures/unrecognised-answer-holds.yaml @@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: unrecognised-answer-holds +admittedAt: '2026-12-01T00:00:00Z' +input: + reference: application-003 +replies: + draft: + - type: response + value: + status: 403 + body: {} +expect: + path: + - draft + state: uncertain diff --git a/crates/registry-coordinator/tests/fixtures/service-function/functions.rhai b/crates/registry-coordinator/tests/fixtures/service-function/functions.rhai new file mode 100644 index 0000000000..edda0e484b --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/functions.rhai @@ -0,0 +1,18 @@ +// Pure Function ABI: one typed object of named inputs, one typed output. +fn draft_request(args) { + #{reference: args.request.reference} +} + +// Only a recognised answer settles the call. Anything else is uncertain, so +// the run holds for same-command recovery instead of guessing. +fn draft_outcome(args) { + let status = args.response.status; + let body = args.response.body; + if status == 200 && "draftId" in body { + return #{state: "accepted", result: #{draftId: body.draftId}}; + } + if status == 422 && "reason" in body && body.reason == "not-eligible" { + return #{state: "refused", code: "not-eligible"}; + } + #{state: "uncertain"} +} diff --git a/crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml b/crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml new file mode 100644 index 0000000000..4122e81e01 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/runtime.yaml @@ -0,0 +1,26 @@ +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +secretProviders: + environment: {} + file: {root: /run/secrets/coordinator} +database: + runtimeUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL + migrationUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL +namespace: coordinator_notices +connections: + notices: + type: service-function + baseUrl: http://127.0.0.1:9020/ + function: draft-notice + authorization: + tokenEndpoint: http://127.0.0.1:8090/token + clientAssertionAudience: http://127.0.0.1:8090 + clientId: coordinator-functions + signingKeyRef: secret:file/function-client-key + resource: urn:example:notice-functions + scopes: [functions:invoke] + responseSchema: + type: object + required: [status, body] + properties: + status: {type: integer} diff --git a/crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml b/crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml new file mode 100644 index 0000000000..6527be60c3 --- /dev/null +++ b/crates/registry-coordinator/tests/fixtures/service-function/workflow.yaml @@ -0,0 +1,106 @@ +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: notice-draft + version: "1" + +types: + notice-input: + type: object + additionalProperties: false + required: [reference] + properties: + reference: {type: string, minLength: 1, maxLength: 64} + draft-response: + type: object + additionalProperties: false + required: [status, body] + properties: + status: {type: integer, minimum: 200, maximum: 499} + body: + type: object + additionalProperties: false + properties: + draftId: {type: string, minLength: 1, maxLength: 64} + reason: {type: string, minLength: 1, maxLength: 64} + draft: + type: object + additionalProperties: false + required: [draftId] + properties: + draftId: {type: string, minLength: 1, maxLength: 64} + draft-outcome: + oneOf: + - type: object + additionalProperties: false + required: [state, result] + properties: + state: {type: string, const: accepted} + result: {typeRef: draft} + - type: object + additionalProperties: false + required: [state, code] + properties: + state: {type: string, const: refused} + code: {type: string, enum: [not-eligible]} + - type: object + additionalProperties: false + required: [state] + properties: + state: {type: string, const: uncertain} + +transforms: + draft-request: + runtime: rhai + source: functions.rhai + entrypoint: draft_request + inputs: + request: {typeRef: notice-input} + output: {operationInput: draft-notice} + draft-outcome: + runtime: rhai + source: functions.rhai + entrypoint: draft_outcome + inputs: + command: {operationInput: draft-notice} + response: {operationOutput: draft-notice} + output: {typeRef: draft-outcome} + +operations: + draft-notice: + uses: service.invoke-function/v1 + connection: notices + serviceFunction: draft-notice + responseSchema: {typeRef: draft-response} + interpret: draft-outcome + +workflow: + input: {typeRef: notice-input} + deadlineSeconds: 900 + start: draft + steps: + draft: + label: Draft the notice + type: call + operation: draft-notice + input: + type: transform + transform: draft-request + inputs: + request: {type: input} + next: drafted + onDeclaredRefusal: not-drafted + drafted: + type: finish + outcome: drafted + output: + type: fields + fields: + draftId: {type: step, step: draft, path: /draftId} + not-drafted: + type: finish + outcome: not-drafted + output: {type: step, step: draft} + outcomes: + drafted: {typeRef: draft} + not-drafted: {operationRefusal: draft-notice} diff --git a/crates/registry-coordinator/tests/helper_functions.rs b/crates/registry-coordinator/tests/helper_functions.rs index a6f3ad9342..2b85025ef4 100644 --- a/crates/registry-coordinator/tests/helper_functions.rs +++ b/crates/registry-coordinator/tests/helper_functions.rs @@ -10,12 +10,12 @@ fn write_project(root: &Path, source: &str) { let workflow = json!({ "apiVersion": authoring::API_VERSION, "kind": authoring::KIND, "project": {"id": "helpers", "version": "1"}, - "functions": { + "transforms": { "probe": {"runtime":"rhai","source":"functions.rhai","entrypoint":"probe","inputs":{"request":{"type":"object"}},"output":{}} }, "workflow": {"input": {"type": "object"}, "deadlineSeconds": 86400, "start": "done", "steps": { - "done": {"type": "finish", "outcome": "measured", "output": {"type": "function", "function": "probe", "inputs": {"request":{"type": "input"}}}} + "done": {"type": "finish", "outcome": "measured", "output": {"type": "transform", "transform": "probe", "inputs": {"request":{"type": "input"}}}} }, "outcomes": {"measured": {}} } }); @@ -131,7 +131,7 @@ fn helpers_that_make_longer_strings_stay_inside_the_string_budget() { ] { let source = body.replace("aaaaaaaa", &"a".repeat(1024)); let error = run(&source, json!({})).unwrap_err(); - assert_eq!(error.code, "function.resource-limit", "{body}"); + assert_eq!(error.code, "transform.resource-limit", "{body}"); } } @@ -147,7 +147,7 @@ fn an_oversized_replace_reaches_a_loaded_project_as_a_resource_limit_refusal() { json!({"big": big}), ) .unwrap_err(); - assert_eq!(error.code, "function.resource-limit"); + assert_eq!(error.code, "transform.resource-limit"); } #[test] @@ -155,7 +155,7 @@ fn a_call_to_a_name_the_profile_lacks_is_refused_at_load_with_its_position_and_a let error = load("parse_decimal(inputs.request.digits)") .err() .expect("unknown helper is refused"); - assert_eq!(error.code, "coordinator.function.unknown-call"); + assert_eq!(error.code, "coordinator.transform.unknown-call"); assert!( error.message.contains("`parse_decimal`"), "{}", @@ -166,7 +166,7 @@ fn a_call_to_a_name_the_profile_lacks_is_refused_at_load_with_its_position_and_a .suggested_action .as_deref() .unwrap() - .contains("coordinatorctl explain functions"), + .contains("coordinatorctl explain transforms"), "{error:?}" ); let source = error.diagnostics[0] @@ -197,7 +197,7 @@ fn every_unknown_call_is_reported_and_known_calls_and_local_functions_pass() { .as_array() .unwrap() .iter() - .filter(|d| d["code"] == "coordinator.function.unknown-call") + .filter(|d| d["code"] == "coordinator.transform.unknown-call") .map(|d| d["message"].as_str().unwrap().to_owned()) .collect::>(); assert_eq!(findings.len(), 3, "{report}"); @@ -214,7 +214,7 @@ fn every_unknown_call_is_reported_and_known_calls_and_local_functions_pass() { #[test] fn explain_functions_lists_the_helpers_of_the_profile() { - let output = cli(&["--format", "json", "explain", "functions"]); + let output = cli(&["--format", "json", "explain", "transforms"]); assert!( output.status.success(), "{}", @@ -267,10 +267,10 @@ fn explain_functions_lists_the_helpers_of_the_profile() { assert!(report["interpreterAbi"].as_str().unwrap().contains("/v3;")); assert_eq!(report["limits"]["stringBytes"], 16384); - let human = cli(&["explain", "functions"]); + let human = cli(&["explain", "transforms"]); assert!(human.status.success()); let text = String::from_utf8(human.stdout).unwrap(); - assert!(text.starts_with("Pure function helpers"), "{text}"); + assert!(text.starts_with("Transform helpers"), "{text}"); assert!(text.contains("parse_int"), "{text}"); assert!(text.contains("Notes:"), "{text}"); assert!(text.contains("global::NAME"), "{text}"); @@ -291,7 +291,7 @@ fn explain_without_a_project_names_the_argument_and_its_help_lists_the_topic() { let help = cli(&["explain", "--help"]); assert!(help.status.success()); let text = String::from_utf8(help.stdout).unwrap(); - assert!(text.contains("functions"), "{text}"); + assert!(text.contains("transforms"), "{text}"); assert!(text.contains("--project"), "{text}"); } @@ -307,7 +307,7 @@ fn pad_with_an_empty_padding_string_is_refused_instead_of_looping() { ), ] { let error = within(10, move || run(body, request)).unwrap_err(); - assert_eq!(error.code, "function.execution", "{body}"); + assert_eq!(error.code, "transform.execution", "{body}"); } } @@ -332,7 +332,7 @@ fn pad_with_a_string_fills_to_the_length_and_stops_at_the_budget() { r#"let s = ""; s.pad(9223372036854775807, "ab"); s"#, ] { let error = within(10, move || run(body, json!({}))).unwrap_err(); - assert_eq!(error.code, "function.resource-limit", "{body}"); + assert_eq!(error.code, "transform.resource-limit", "{body}"); } } @@ -413,9 +413,9 @@ fn package_string_helpers_end_on_empty_zero_and_extreme_arguments() { if let Err(error) = outcome { assert!( [ - "function.execution", - "function.resource-limit", - "function.output" + "transform.execution", + "transform.resource-limit", + "transform.output" ] .contains(&error.code.as_ref()), "{call}: {error:?}" @@ -451,7 +451,7 @@ fn only_math_whose_result_is_the_same_on_every_host_is_available() { let error = load(name) .err() .unwrap_or_else(|| panic!("{name} is available")); - assert_eq!(error.code, "coordinator.function.unknown-call", "{name}"); + assert_eq!(error.code, "coordinator.transform.unknown-call", "{name}"); } let value = run( r#" @@ -492,7 +492,7 @@ fn a_result_holding_nan_or_infinity_is_refused_not_turned_into_null() { "parse_float(\"NaN\")", ] { let error = run(body, json!({})).unwrap_err(); - assert_eq!(error.code, "function.execution", "{body}"); + assert_eq!(error.code, "transform.execution", "{body}"); } // Finite numbers, and a NaN that is only tested, still pass. assert_eq!( @@ -511,7 +511,7 @@ fn a_function_that_curries_is_refused_at_check_with_a_way_forward() { let Err(error) = Definition::load(root.path()) else { panic!("a Function that curries was accepted"); }; - assert_eq!(error.code, "coordinator.function.definition"); + assert_eq!(error.code, "coordinator.transform.definition"); assert!(error.message.contains("curry"), "{}", error.message); let hint = error.suggested_action.as_deref().unwrap_or_default(); assert!(hint.contains("curry"), "{hint}"); @@ -527,8 +527,8 @@ fn a_refusal_in_a_shared_source_is_reported_once() { ); let path = root.path().join("workflow.yaml"); let mut workflow: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); - workflow["functions"]["other"] = workflow["functions"]["probe"].clone(); - workflow["functions"]["other"]["entrypoint"] = json!("other"); + workflow["transforms"]["other"] = workflow["transforms"]["probe"].clone(); + workflow["transforms"]["other"]["entrypoint"] = json!("other"); fs::write(&path, workflow.to_string()).unwrap(); let output = cli(&[ "--format", @@ -542,7 +542,7 @@ fn a_refusal_in_a_shared_source_is_reported_once() { .as_array() .unwrap() .iter() - .filter(|d| d["code"] == "coordinator.function.definition") + .filter(|d| d["code"] == "coordinator.transform.definition") .count(); assert_eq!(refusals, 1, "{report}"); } @@ -563,7 +563,7 @@ fn unknown_call_names(source: &str) -> Vec { .map(Vec::as_slice) .unwrap_or_default() .iter() - .filter(|d| d["code"] == "coordinator.function.unknown-call") + .filter(|d| d["code"] == "coordinator.transform.unknown-call") .map(|d| { let message = d["message"].as_str().unwrap(); message.split('`').nth(1).unwrap().to_owned() diff --git a/crates/registry-coordinator/tests/instant_functions.rs b/crates/registry-coordinator/tests/instant_functions.rs index 401441fae4..57b6bde8cf 100644 --- a/crates/registry-coordinator/tests/instant_functions.rs +++ b/crates/registry-coordinator/tests/instant_functions.rs @@ -15,14 +15,14 @@ fn project(functions: &str) -> tempfile::TempDir { let workflow = json!({ "apiVersion": authoring::API_VERSION, "kind": authoring::KIND, "project": {"id": "instants", "version": "1"}, - "functions": { + "transforms": { "due": {"runtime":"rhai","source":"functions.rhai","entrypoint":"due","inputs":{"request":{"type":"object"}},"output":{"type":"string","format":"date-time"}}, "elapsed": {"runtime":"rhai","source":"functions.rhai","entrypoint":"elapsed","inputs":{"request":{"type":"object"}},"output":{"type":"integer"}} }, "workflow": {"input": {"type": "object"}, "deadlineSeconds": 86400, "start": "due", "steps": { - "due": {"type": "wait-until", "waitUntil": {"type": "function", "function": "due", "inputs": {"request":{"type": "input"}}}, "next": "done"}, - "done": {"type": "finish", "outcome": "measured", "output": {"type": "function", "function": "elapsed", "inputs": {"request":{"type": "input"}}}} + "due": {"type": "wait-until", "waitUntil": {"type": "transform", "transform": "due", "inputs": {"request":{"type": "input"}}}, "next": "done"}, + "done": {"type": "finish", "outcome": "measured", "output": {"type": "transform", "transform": "elapsed", "inputs": {"request":{"type": "input"}}}} }, "outcomes": {"measured": {"type": "integer"}} } }); @@ -52,7 +52,7 @@ fn between(at: &str, other: &str) -> registry_coordinator::Result { definition().evaluate("done", &json!({"at": at, "other": other}), &BTreeMap::new()) } -const REFUSED: &str = "the function could not evaluate its supplied values"; +const REFUSED: &str = "the Transform could not evaluate its supplied values"; #[test] fn add_seconds_moves_an_instant_and_writes_it_in_utc() { @@ -107,7 +107,7 @@ fn an_instant_or_result_outside_rfc_3339_is_a_function_failure_that_omits_the_va ]; for refusal in refusals { let error = refusal.err().unwrap(); - assert_eq!(error.code, "function.execution"); + assert_eq!(error.code, "transform.execution"); assert_eq!(error.message, REFUSED); let rendered = serde_json::to_string(&json!({ "message": error.message, "field": error.field, @@ -136,5 +136,5 @@ fn the_function_profile_reads_no_clock() { let error = Definition::load(project(&functions).path()) .err() .expect("a call to the clock is refused"); - assert_eq!(error.code, "coordinator.function.unknown-call"); + assert_eq!(error.code, "coordinator.transform.unknown-call"); } diff --git a/crates/registry-coordinator/tests/mapping_checks.rs b/crates/registry-coordinator/tests/mapping_checks.rs index cd9e038297..f8c555749c 100644 --- a/crates/registry-coordinator/tests/mapping_checks.rs +++ b/crates/registry-coordinator/tests/mapping_checks.rs @@ -289,7 +289,7 @@ fn a_mapping_that_fits_every_schema_loads() { #[test] fn open_members_accept_any_path_beneath_them() { let mut project = project(); - project["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "combine", "inputs": {"arg0": {"type": "input", "path": "/labels/lname"}, "arg1": {"type": "input", "path": "/labels/other"}, "arg2": {"type": "input", "path": "/tree/child/child/child/name"}, "arg3": {"type": "input", "path": "/slots/3"}, "arg4": {"type": "input", "path": "/extra/any/depth"}, "arg5": {"type": "step", "step": "read", "path": "/data/domainData/any/0/depth"}, "arg6": {"type": "step", "step": "read", "path": "/data/extension"}, "arg7": {"type": "step", "step": "read", "path": "/links/self"}, "arg8": {"type": "step", "step": "lookup", "path": "/body/0/a~1b"}}}); + project["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "combine", "inputs": {"arg0": {"type": "input", "path": "/labels/lname"}, "arg1": {"type": "input", "path": "/labels/other"}, "arg2": {"type": "input", "path": "/tree/child/child/child/name"}, "arg3": {"type": "input", "path": "/slots/3"}, "arg4": {"type": "input", "path": "/extra/any/depth"}, "arg5": {"type": "step", "step": "read", "path": "/data/domainData/any/0/depth"}, "arg6": {"type": "step", "step": "read", "path": "/data/extension"}, "arg7": {"type": "step", "step": "read", "path": "/links/self"}, "arg8": {"type": "step", "step": "lookup", "path": "/body/0/a~1b"}}}); load(&project, "fn combine(__named) { let a = __named.arg0; let b = __named.arg1; let c = __named.arg2; let d = __named.arg3; let e = __named.arg4; let f = __named.arg5; let g = __named.arg6; let h = __named.arg7; let i = __named.arg8; () }").unwrap(); } @@ -335,7 +335,7 @@ fn a_path_the_operation_output_does_not_declare_is_refused() { #[test] fn function_arguments_have_their_paths_checked_and_nothing_else() { let mut project = project(); - project["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "combine", "inputs": {"arg0": {"type": "input", "path": "/count"}, "arg1": {"type": "input", "path": "/tree/child/nmae"}}}); + project["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "combine", "inputs": {"arg0": {"type": "input", "path": "/count"}, "arg1": {"type": "input", "path": "/tree/child/nmae"}}}); assert_finding( &refused(&project), "coordinator.mapping.path", @@ -642,9 +642,9 @@ fn an_admitted_snapshot_is_not_held_to_the_static_checks() { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -666,6 +666,6 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } diff --git a/crates/registry-coordinator/tests/mapping_grammar.rs b/crates/registry-coordinator/tests/mapping_grammar.rs index 1218d1b570..bcb4464fdb 100644 --- a/crates/registry-coordinator/tests/mapping_grammar.rs +++ b/crates/registry-coordinator/tests/mapping_grammar.rs @@ -214,7 +214,7 @@ fn references_and_fields_carry_plumbing_without_a_function() { #[test] fn function_arguments_accept_paths_and_literals() { let mut project = project(); - project["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "combine", "inputs": {"arg0": {"type": "input", "path": "/applicationId"}, "arg1": {"type": "literal", "value": {"nested": [1, true, null]}}, "arg2": {"type": "step", "step": "read", "path": "/data"}, "arg3": {"type": "step", "step": "read"}}}); + project["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "combine", "inputs": {"arg0": {"type": "input", "path": "/applicationId"}, "arg1": {"type": "literal", "value": {"nested": [1, true, null]}}, "arg2": {"type": "step", "step": "read", "path": "/data"}, "arg3": {"type": "step", "step": "read"}}}); let definition = load( &project, "fn combine(__named) { let id = __named.arg0; let literal = __named.arg1; let data = __named.arg2; let whole = __named.arg3; let count = if literal.nested.len() == 3 && literal.nested[1] { \"3\" } else { \"?\" }; #{ record: data.recordId + \":\" + id + \":\" + count + \":\" + whole.meta.datasetId, note: () } }", @@ -319,21 +319,21 @@ fn a_malformed_pointer_is_refused_at_its_member() { fn an_input_names_its_form_function_or_fields() { for (value, path, code, message, action) in [ ( - json!({"function": "f", "inputs": {}}), + json!({"transform": "f", "inputs": {}}), "/workflow/steps/read/input", "config.missing-key", "the member `type` is missing; it names which form this mapping takes", - "Add `type` with one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "Add `type` with one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( json!({"type": "unknown"}), "/workflow/steps/read/input/type", "config.unknown-variant", - "expected one of `function`, `fields`, `compare`, `input`, `step`, `literal`", - "Use one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "expected one of `transform`, `fields`, `compare`, `input`, `step`, `literal`", + "Use one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( - json!({"type": "function", "function": "f"}), + json!({"type": "transform", "transform": "f"}), "/workflow/steps/read/input", "config.missing-key", "the required member `inputs` is missing", @@ -347,11 +347,11 @@ fn an_input_names_its_form_function_or_fields() { "Add `fields`.", ), ( - json!({"type": "function", "function": "f", "inputs": {}, "fields": {}}), + json!({"type": "transform", "transform": "f", "inputs": {}, "fields": {}}), "/workflow/steps/read/input/fields", "config.unknown-key", "`fields` is not a member of this mapping", - "Remove `fields`; the accepted keys are `type`, `function`, `inputs`.", + "Remove `fields`; the accepted keys are `type`, `transform`, `inputs`.", ), ] { let mut project = project(); @@ -368,18 +368,18 @@ fn an_input_names_its_form_function_or_fields() { fn a_selector_names_its_form_function_or_one_reference() { for (value, path, code, message, action) in [ ( - json!({"function": "f", "inputs": {}}), + json!({"transform": "f", "inputs": {}}), "/workflow/steps/route/choose", "config.missing-key", "the member `type` is missing; it names which form this mapping takes", - "Add `type` with one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "Add `type` with one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( json!({"type": "unknown"}), "/workflow/steps/route/choose/type", "config.unknown-variant", - "expected one of `function`, `fields`, `compare`, `input`, `step`, `literal`", - "Use one of `function`, `fields`, `compare`, `input`, `step`, `literal`.", + "expected one of `transform`, `fields`, `compare`, `input`, `step`, `literal`", + "Use one of `transform`, `fields`, `compare`, `input`, `step`, `literal`.", ), ( json!({"type": "step"}), @@ -410,11 +410,11 @@ fn a_selector_names_its_form_function_or_one_reference() { "Remove `path`; the accepted keys are `type`, `value`.", ), ( - json!({"type": "function", "function": "f", "inputs": {}, "path": "/x"}), + json!({"type": "transform", "transform": "f", "inputs": {}, "path": "/x"}), "/workflow/steps/route/choose/path", "config.unknown-key", "`path` is not a member of this mapping", - "Remove `path`; the accepted keys are `type`, `function`, `inputs`.", + "Remove `path`; the accepted keys are `type`, `transform`, `inputs`.", ), ] { let mut project = project(); @@ -554,9 +554,9 @@ fn reference_selectors_keep_their_result_contracts() { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -578,6 +578,6 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } diff --git a/crates/registry-coordinator/tests/nested_fields.rs b/crates/registry-coordinator/tests/nested_fields.rs index be3265a61f..e5d3b9085c 100644 --- a/crates/registry-coordinator/tests/nested_fields.rs +++ b/crates/registry-coordinator/tests/nested_fields.rs @@ -137,9 +137,9 @@ fn only(error: &CoordinatorError) -> &Diagnostic { fn declare_test_functions(project: &Value) -> Value { fn mapping(value: &Value, functions: &mut serde_json::Map) { if let Some(object) = value.as_object() { - if object.get("type") == Some(&json!("function")) { + if object.get("type") == Some(&json!("transform")) { if let (Some(name), Some(inputs)) = ( - object.get("function").and_then(Value::as_str), + object.get("transform").and_then(Value::as_str), object.get("inputs").and_then(Value::as_object), ) { let signature = inputs @@ -157,7 +157,7 @@ fn declare_test_functions(project: &Value) -> Value { let mut project = project.clone(); let mut functions = serde_json::Map::new(); mapping(&project["workflow"]["steps"], &mut functions); - project["functions"] = Value::Object(functions); + project["transforms"] = Value::Object(functions); project } @@ -342,7 +342,7 @@ fn a_nested_member_reads_only_outputs_available_on_every_route() { fn a_nested_member_never_holds_a_function() { let mut project = project(); project["workflow"]["steps"]["lookup"]["input"]["fields"]["query"]["fields"]["page"] = - json!({"type": "function", "function": "page", "inputs": {}}); + json!({"type": "transform", "transform": "page", "inputs": {}}); let error = parse_refused(&project); let finding = &error.diagnostics[0]; assert_eq!(finding.code, "config.unknown-variant"); @@ -357,7 +357,7 @@ fn a_nested_member_never_holds_a_function() { // Function inputs stay plain references. let mut project = self::project(); - project["workflow"]["steps"]["lookup"]["input"] = json!({"type": "function", "function": "build", "inputs": { + project["workflow"]["steps"]["lookup"]["input"] = json!({"type": "transform", "transform": "build", "inputs": { "page": {"type": "fields", "fields": {}} }}); let error = parse_refused(&project); @@ -377,11 +377,11 @@ fn a_nested_member_never_holds_a_function() { fn a_nested_mapping_freezes_the_input_a_function_would_build() { let declarative = load(&project(), "").unwrap(); let mut computed = project(); - computed["workflow"]["steps"]["lookup"]["input"] = json!({"type": "function", "function": "build_query", "inputs": { + computed["workflow"]["steps"]["lookup"]["input"] = json!({"type": "transform", "transform": "build_query", "inputs": { "page": {"type": "input", "path": "/page"}, "record": {"type": "step", "step": "read", "path": "/data/recordId"} }}); - computed["workflow"]["steps"]["done"]["output"] = json!({"type": "function", "function": "build_outcome", "inputs": { + computed["workflow"]["steps"]["done"]["output"] = json!({"type": "transform", "transform": "build_outcome", "inputs": { "id": {"type": "input", "path": "/applicationId"}, "record": {"type": "step", "step": "read", "path": "/data/recordId"} }}); @@ -485,7 +485,7 @@ fn a_snapshot_refuses_unknown_members_of_a_nested_mapping() { reference_with_fields["fields"]["page"]["fields"] = json!({}); let mut function_shaped = query.clone(); function_shaped["fields"]["page"] = - json!({"type": "function", "function": "page", "inputs": {}}); + json!({"type": "transform", "transform": "page", "inputs": {}}); let mut wrong_case = query.clone(); wrong_case["type"] = json!("Fields"); for (case, query) in [ diff --git a/crates/registry-coordinator/tests/postgres_state.rs b/crates/registry-coordinator/tests/postgres_state.rs index 1c628b45b0..49c065fcba 100644 --- a/crates/registry-coordinator/tests/postgres_state.rs +++ b/crates/registry-coordinator/tests/postgres_state.rs @@ -49,7 +49,7 @@ kind: CoordinatorProject project: {id: synthetic-declared-refusal, version: v1} contracts: applications: {type: breg, source: applications.json} -functions: +transforms: action: runtime: rhai source: functions.rhai @@ -75,14 +75,14 @@ workflow: action: type: call operation: invoke-breg-action - input: {type: function, function: action, inputs: {input: {type: input}}} + input: {type: transform, transform: action, inputs: {input: {type: input}}} next: applied onDeclaredRefusal: refused applied: {type: finish, outcome: applied} refused: type: finish outcome: refused - output: {type: function, function: keep, inputs: {value: {type: step, step: action}}} + output: {type: transform, transform: keep, inputs: {value: {type: step, step: action}}} outcomes: applied: {type: 'null'} refused: {operationRefusal: invoke-breg-action} @@ -99,7 +99,7 @@ kind: CoordinatorProject project: {id: synthetic-declared-refusal-deadline, version: v1} contracts: applications: {type: breg, source: applications.json} -functions: +transforms: action: runtime: rhai source: functions.rhai @@ -125,13 +125,13 @@ workflow: action: type: call operation: invoke-breg-action - input: {type: function, function: action, inputs: {input: {type: input}}} + input: {type: transform, transform: action, inputs: {input: {type: input}}} next: applied onDeclaredRefusal: later later: type: call operation: invoke-breg-action - input: {type: function, function: action, inputs: {input: {type: input}}} + input: {type: transform, transform: action, inputs: {input: {type: input}}} next: applied applied: {type: finish, outcome: applied} outcomes: @@ -143,7 +143,7 @@ kind: CoordinatorProject project: id: synthetic-reminder version: v1 -functions: +transforms: timer: runtime: rhai source: functions.rhai @@ -214,8 +214,8 @@ workflow: wait: type: wait-until waitUntil: - type: function - function: timer + type: transform + transform: timer inputs: input: type: input @@ -224,8 +224,8 @@ workflow: type: call operation: read-record input: - type: function - function: record + type: transform + transform: record inputs: input: type: input @@ -233,8 +233,8 @@ workflow: choose: type: choose choose: - type: function - function: permission + type: transform + transform: permission inputs: record: type: step @@ -246,8 +246,8 @@ workflow: type: call operation: submit-message input: - type: function - function: message + type: transform + transform: message inputs: record: type: step @@ -257,8 +257,8 @@ workflow: type: finish outcome: sent output: - type: function - function: receipt + type: transform + transform: receipt inputs: message: type: step @@ -311,7 +311,7 @@ async fn harness() -> Harness { .unwrap(); std::fs::write(project.path().join("applications.json"), include_str!("../../../products/coordinator/examples/governed-action-follow-up/generated/applications.contract.json")).unwrap(); std::fs::write(project.path().join("workflow.yaml"), WORKFLOW).expect("workflow"); - std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("functions"); + std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("transforms"); let definition = Definition::load(project.path()).expect("valid synthetic definition"); Harness { url, @@ -1865,7 +1865,7 @@ async fn a_call_input_outside_the_operation_input_is_refused_before_dispatch_wit // A permissive Function result still cannot bypass the host's exact // Operation contract or freeze an invalid command. let mut workflow = authored_workflow_value(WORKFLOW); - workflow["functions"]["message"]["output"] = json!({"type":"object"}); + workflow["transforms"]["message"]["output"] = json!({"type":"object"}); std::fs::write(h.project.path().join("workflow.yaml"), workflow.to_string()).unwrap(); let definition = Definition::load(h.project.path()).unwrap(); let run = h @@ -1925,7 +1925,7 @@ async fn invalid_dictionary_values_never_disclose_member_names_or_dispatch() { apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: synthetic-dictionary-privacy, version: '1'} -functions: +transforms: request: runtime: rhai source: functions.rhai @@ -1949,7 +1949,7 @@ workflow: read: type: call operation: read-job - input: {type: function, function: request, inputs: {request: {type: input}}} + input: {type: transform, transform: request, inputs: {request: {type: input}}} next: done done: {type: finish, outcome: done} outcomes: {done: {type: 'null'}} @@ -3946,36 +3946,36 @@ async fn invalid_following_wait(prior: &str, body: &str) -> Harness { let mut workflow = authored_workflow_value(WORKFLOW); let mut steps = serde_json::Map::new(); let input_mapping = - json!({"type":"function","function":"record","inputs":{"input":{"type":"input"}}}); + json!({"type":"transform","transform":"record","inputs":{"input":{"type":"input"}}}); let start = match prior { "read" => { steps.insert("read".into(),json!({"type":"call","operation":"read-record","input":input_mapping,"next":"later"})); "read" } "choose" => { - steps.insert("choose".into(),json!({"type":"choose","choose":{"type":"function","function":"choose-input","inputs":{"input":{"type":"input"}}},"cases":{"yes":"later"}})); + steps.insert("choose".into(),json!({"type":"choose","choose":{"type":"transform","transform":"choose-input","inputs":{"input":{"type":"input"}}},"cases":{"yes":"later"}})); "choose" } "wait" => { - steps.insert("wait".into(),json!({"type":"wait-until","waitUntil":{"type":"function","function":"timer","inputs":{"input":{"type":"input"}}},"next":"later"})); + steps.insert("wait".into(),json!({"type":"wait-until","waitUntil":{"type":"transform","transform":"timer","inputs":{"input":{"type":"input"}}},"next":"later"})); "wait" } "message" => { steps.insert("read".into(),json!({"type":"call","operation":"read-record","input":input_mapping,"next":"message"})); - steps.insert("message".into(),json!({"type":"call","operation":"submit-message","input":{"type":"function","function":"message","inputs":{"record":{"type":"step","step":"read"}}},"next":"later"})); + steps.insert("message".into(),json!({"type":"call","operation":"submit-message","input":{"type":"transform","transform":"message","inputs":{"record":{"type":"step","step":"read"}}},"next":"later"})); "read" } _ => panic!("unknown test prior step"), }; - steps.insert("later".into(),json!({"type":"wait-until","waitUntil":{"type":"function","function":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"future-read"})); + steps.insert("later".into(),json!({"type":"wait-until","waitUntil":{"type":"transform","transform":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"future-read"})); steps.insert( "future-read".into(), json!({"type":"call","operation":"read-record","input":input_mapping,"next":"done"}), ); steps.insert("done".into(), json!({"type":"finish","outcome":"done"})); workflow["workflow"] = json!({"input":{"type":"object"},"deadlineSeconds":3600,"start":start,"steps":steps,"outcomes":{"done":{"type":"null"}}}); - workflow["functions"]["choose-input"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"choose_input","inputs":{"input":{"type":"object"}},"output":{"type":"string","enum":["yes"]}}); - workflow["functions"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); + workflow["transforms"]["choose-input"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"choose_input","inputs":{"input":{"type":"object"}},"output":{"type":"string","enum":["yes"]}}); + workflow["transforms"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); std::fs::write(h.project.path().join("workflow.yaml"), workflow.to_string()).unwrap(); std::fs::write(h.project.path().join("functions.rhai"),format!("{FUNCTIONS}\nfn choose_input(args) {{ \"yes\" }}\nfn broken_wait(args) {{let input=args.input; {body}}}")).unwrap(); h.definition = Definition::load(h.project.path()).unwrap(); @@ -4681,9 +4681,8 @@ async fn interrupted_mutation(kind: &str, prepared: bool) -> (Harness, Uuid, Arc .as_object_mut() .unwrap() .remove("read"); - document["workflow"]["steps"]["message"]["input"] = - json!({"type":"function","function":"pre-io-command","inputs":{"input":{"type":"input"}}}); - document["functions"]["pre-io-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pre_io_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":"submit-message"}}); + document["workflow"]["steps"]["message"]["input"] = json!({"type":"transform","transform":"pre-io-command","inputs":{"input":{"type":"input"}}}); + document["transforms"]["pre-io-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pre_io_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":"submit-message"}}); if kind == "appointment" { document["operations"]["submit-message"]["uses"] = json!("scheduling.create-appointment/v1"); diff --git a/crates/registry-coordinator/tests/process_restart.rs b/crates/registry-coordinator/tests/process_restart.rs index 6c16e8afd6..a2fd1c955a 100644 --- a/crates/registry-coordinator/tests/process_restart.rs +++ b/crates/registry-coordinator/tests/process_restart.rs @@ -346,7 +346,7 @@ async fn exited_decision_workers_hold_unknown_results_and_reuse_completed_result apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: process-decision, version: '1'} -functions: +transforms: decision-request: runtime: rhai source: functions.rhai @@ -371,11 +371,11 @@ workflow: evaluate: type: call operation: evaluate - input: {type: function, function: decision-request, inputs: {input: {type: input}}} + input: {type: transform, transform: decision-request, inputs: {input: {type: input}}} next: wait wait: type: wait-until - waitUntil: {type: function, function: timer, inputs: {input: {type: input}}} + waitUntil: {type: transform, transform: timer, inputs: {input: {type: input}}} next: done done: type: finish diff --git a/crates/registry-coordinator/tests/product_contract_imports.rs b/crates/registry-coordinator/tests/product_contract_imports.rs index e716c5faf4..88f563997d 100644 --- a/crates/registry-coordinator/tests/product_contract_imports.rs +++ b/crates/registry-coordinator/tests/product_contract_imports.rs @@ -299,10 +299,9 @@ fn template_import_checks_computed_data_and_keeps_local_schema_references() { project["contracts"] = json!({"notices": {"type": "messaging", "source": "contract.json"}}); project["operations"]["request"]["template"] = json!({"contract": "notices", "id": "licence-issued", "version": "1"}); - project["functions"] = json!({"message": {"runtime": "rhai", "source": "functions.rhai", "entrypoint": "message", + project["transforms"] = json!({"message": {"runtime": "rhai", "source": "functions.rhai", "entrypoint": "message", "inputs": {"input": {"type": "object"}}, "output": {"type": "object"}}}); - project["workflow"]["steps"]["call"]["input"] = - json!({"type": "function", "function": "message", "inputs": {"input": {"type": "input"}}}); + project["workflow"]["steps"]["call"]["input"] = json!({"type": "transform", "transform": "message", "inputs": {"input": {"type": "input"}}}); fs::write( root.path().join("functions.rhai"), "fn message(args) { args.input }", diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs index f2637fa03d..a19b55ff2a 100644 --- a/crates/registry-coordinator/tests/provision_cli.rs +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -344,6 +344,20 @@ fn the_runtime_file_may_be_given_before_the_verb() { ); } +/// An unset URL secret is refused with the shared reason and the fix the +/// secret error names, as every provision tool words it. +fn assert_unavailable_reason_and_fix(output: &std::process::Output) { + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("no readable secret of that name exists under the configured provider"), + "{stderr}" + ); + assert!( + stderr.contains("Create the secret under the configured provider, or correct the name."), + "{stderr}" + ); +} + #[test] fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { let directory = tempfile::tempdir().unwrap(); @@ -359,6 +373,7 @@ fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { "coordinator.runtime-config.refused", "/database/runtimeUrlRef", ); + assert_unavailable_reason_and_fix(&output); } #[test] @@ -376,6 +391,7 @@ fn an_unreadable_migration_url_secret_is_refused_without_a_password() { "coordinator.runtime-config.refused", "/database/migrationUrlRef", ); + assert_unavailable_reason_and_fix(&output); } #[test] @@ -384,12 +400,15 @@ fn a_certificate_authority_file_that_is_not_text_is_refused() { let runtime = runtime_file(directory.path()); let root_pem = directory.path().join("secrets/postgres-root.pem"); fs::write(&root_pem, [0xff, 0xfe, 0xfd]).unwrap(); + fs::set_permissions(&root_pem, fs::Permissions::from_mode(0o600)).unwrap(); let output = provision(&runtime, &["--print-sql"]); assert_refused( &output, "coordinator.runtime-config.refused", "/database/caBundleRef", ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("not UTF-8 text"), "{stderr}"); } #[test] diff --git a/crates/registry-coordinator/tests/recovery_audit.rs b/crates/registry-coordinator/tests/recovery_audit.rs index 7069cccdd7..dbd1bdcb03 100644 --- a/crates/registry-coordinator/tests/recovery_audit.rs +++ b/crates/registry-coordinator/tests/recovery_audit.rs @@ -132,7 +132,7 @@ async fn harness() -> Harness { r#"apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: recovery-audit, version: v1} -functions: +transforms: timer: runtime: rhai source: functions.rhai @@ -146,7 +146,7 @@ workflow: steps: wait: type: wait-until - waitUntil: {type: function, function: timer, inputs: {input: {type: input}}} + waitUntil: {type: transform, transform: timer, inputs: {input: {type: input}}} next: done done: {type: finish, outcome: done} outcomes: {done: {type: 'null'}} diff --git a/crates/registry-coordinator/tests/review_wait_postgres.rs b/crates/registry-coordinator/tests/review_wait_postgres.rs index 60e91ceb2a..b7f369d83d 100644 --- a/crates/registry-coordinator/tests/review_wait_postgres.rs +++ b/crates/registry-coordinator/tests/review_wait_postgres.rs @@ -290,7 +290,7 @@ async fn harness_with_options(on_timeout: bool, on_cancel: bool, cleanup_wait: b workflow_with_cancel(on_timeout, on_cancel, cleanup_wait), ) .expect("workflow"); - std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("functions"); + std::fs::write(project.path().join("functions.rhai"), FUNCTIONS).expect("transforms"); let definition = Definition::load(project.path()).expect("valid synthetic definition"); Harness { url, diff --git a/crates/registry-coordinator/tests/runtime_config.rs b/crates/registry-coordinator/tests/runtime_config.rs index 8a499cc6d5..4762697ffe 100644 --- a/crates/registry-coordinator/tests/runtime_config.rs +++ b/crates/registry-coordinator/tests/runtime_config.rs @@ -806,7 +806,7 @@ fn init_writes_eight_entries_for_an_offline_checkable_project_and_never_overwrit let explanation = definition.explain().unwrap(); assert_eq!(explanation["workflowRevision"], definition.digest); assert!(explanation["operations"].is_object()); - assert!(explanation["functions"].is_object()); + assert!(explanation["transforms"].is_object()); assert_eq!(explanation["steps"].as_array().unwrap().len(), 6); assert_eq!(explanation["limits"]["operations"], 100000); fs::write(path.join("functions.rhai"), CANARY).unwrap(); @@ -926,7 +926,7 @@ fn appointment_workflow_refuses_ordinary_authority_before_admission_or_activatio ) .unwrap(); read_only["workflow"]["start"] = json!("metadata"); - read_only.as_object_mut().unwrap().remove("functions"); + read_only.as_object_mut().unwrap().remove("transforms"); read_only["operations"] .as_object_mut() .unwrap() diff --git a/crates/registry-coordinator/tests/scheduling_event_native.rs b/crates/registry-coordinator/tests/scheduling_event_native.rs index 00d18ca87b..56daa20b4f 100644 --- a/crates/registry-coordinator/tests/scheduling_event_native.rs +++ b/crates/registry-coordinator/tests/scheduling_event_native.rs @@ -286,7 +286,7 @@ fn write_project(root: &Path) { "appointmentId":{"type":"string","format":"uuid"}, "state":{"type":"string","enum":["confirmed","cancelled"]} }}}, - "functions":{"notice-request":{"runtime":"rhai","source":"functions.rhai","entrypoint":"notice_request", + "transforms":{"notice-request":{"runtime":"rhai","source":"functions.rhai","entrypoint":"notice_request", "inputs":{"input":{"typeRef":"lifecycle-input"}},"output":{"operationInput":"send-message"}}}, "operations":{"send-message":{"uses":"messaging.submit-message/v1","connection":"notices"}}, "workflow":{ @@ -313,7 +313,7 @@ fn write_project(root: &Path) { "deadlineSeconds":300, "start":"notify", "steps":{ - "notify":{"type":"call","operation":"send-message","input":{"type":"function","function":"notice-request","inputs":{"input":{"type":"input"}}},"next":"accepted"}, + "notify":{"type":"call","operation":"send-message","input":{"type":"transform","transform":"notice-request","inputs":{"input":{"type":"input"}}},"next":"accepted"}, "accepted":{"type":"finish","outcome":"message-accepted","output":{"type":"fields","fields":{"messageId":{"type":"step","step":"notify","path":"/id"}}}} }, "outcomes":{"message-accepted":{"type":"object","additionalProperties":false,"required":["messageId"],"properties":{"messageId":{"type":"string","format":"uuid"}}}} diff --git a/crates/registry-coordinator/tests/service_function.rs b/crates/registry-coordinator/tests/service_function.rs new file mode 100644 index 0000000000..4b7b2ad10b --- /dev/null +++ b/crates/registry-coordinator/tests/service_function.rs @@ -0,0 +1,998 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `service.invoke-function/v1` over a loopback function host: one POST to the +//! one function the deployment binds, under the connection's own function-host +//! credential. That credential is never a product's, so the function holds no +//! record authority of its own. +use std::sync::Arc; + +use registry_coordinator::{ + contracts::contract, + external_http::{ExternalHttpConnection, ServiceFunctionConfig}, + protocol::{CallOutcome, Operation}, + runtime::{RuntimeConfig, API_VERSION, KIND}, +}; +use registry_platform_httputil::client::StaticToken; +use serde_json::{json, Value}; +use wiremock::{ + matchers::{body_json, header, method, path}, + Mock, MockServer, ResponseTemplate, +}; + +const REQUEST_ID: &str = "synthetic-function-request-id"; +const TOKEN: &str = "synthetic-function-host-token-canary"; + +fn response_schema() -> Value { + json!({ + "type":"object", "required":["status","body"], "additionalProperties":false, + "properties":{ + "status":{"type":"integer","minimum":100,"maximum":599}, + "body":{"anyOf":[{"type":"null"},{"type":"object","maxProperties":8}]} + } + }) +} + +fn function_authorization() -> Value { + json!({ + "tokenEndpoint":"http://127.0.0.1:9999/token", "clientId":"coordinator-functions", + "clientAssertionAudience":"http://127.0.0.1:9999", + "signingKeyRef":"secret:file/function-client-key", + "resource":"urn:example:notice-functions", + "scopes":["functions:invoke"] + }) +} + +fn binding(base: &str) -> Value { + json!({ + "baseUrl":base, "function":"draft-notice", + "authorization":function_authorization(), + "responseSchema":response_schema() + }) +} + +fn connection(base: &str) -> ExternalHttpConnection { + let config: ServiceFunctionConfig = serde_json::from_value(binding(base)).unwrap(); + let tokens = Arc::new(StaticToken::new(TOKEN).unwrap()); + ExternalHttpConnection::service_function(&config, tokens).unwrap() +} + +fn describe(outcome: &CallOutcome) -> String { + match outcome { + CallOutcome::Success(reply) => format!("success:{}", reply["status"]), + CallOutcome::Uncertain { code } => format!("uncertain:{code}"), + CallOutcome::Refused { code } => format!("refused:{code}"), + CallOutcome::Retryable { code, .. } => format!("retryable:{code}"), + CallOutcome::UncertainRetryable { code, .. } => format!("uncertain-retryable:{code}"), + _ => "other".into(), + } +} + +fn body() -> Value { + json!({"reference":"application-body-canary"}) +} + +#[tokio::test] +async fn a_call_posts_to_the_bound_function_with_the_function_host_credential() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/service/functions/draft-notice")) + .and(header("idempotency-key", REQUEST_ID)) + .and(header("content-type", "application/json")) + .and(header("authorization", format!("Bearer {TOKEN}").as_str())) + .and(body_json(body())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&server) + .await; + let connection = connection(&format!("{}/service/", server.uri())); + match connection.command(&body(), REQUEST_ID, false).await { + CallOutcome::Success(reply) => { + assert_eq!(reply, json!({"status":200,"body":{"draftId":"draft-001"}})); + assert_eq!( + contract(Operation::InvokeServiceFunction).check_output(&reply), + Ok(()) + ); + } + _ => panic!("the bound function answers"), + } + server.verify().await; +} + +#[tokio::test] +async fn a_refusal_is_handed_to_the_interpretation_and_a_redirect_is_not_followed() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(403).set_body_json(json!({}))) + .expect(1) + .mount(&server) + .await; + let refused = connection(&server.uri()) + .command(&body(), REQUEST_ID, false) + .await; + // The status reaches the pinned interpretation; the host claims no failure. + assert!( + matches!(&refused, CallOutcome::Success(reply) if reply["status"] == 403), + "{}", + describe(&refused) + ); + + let redirecting = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with( + ResponseTemplate::new(307).insert_header("location", "/functions/publish-notice"), + ) + .expect(1) + .mount(&redirecting) + .await; + let redirected = connection(&redirecting.uri()) + .command(&body(), REQUEST_ID, false) + .await; + assert!( + matches!(&redirected, CallOutcome::Uncertain { code } if code == "external-redirect"), + "{}", + describe(&redirected) + ); + assert_eq!(redirecting.received_requests().await.unwrap().len(), 1); +} + +#[test] +fn the_function_name_is_one_local_identifier() { + for invalid in ["../admin", "draft/notice", "Draft", "", "a?b"] { + let mut document = binding("https://functions.example.test/"); + document["function"] = json!(invalid); + assert!( + serde_json::from_value::(document).is_err(), + "{invalid}" + ); + } +} + +fn breg_connection() -> Value { + json!({ + "type":"breg", "baseUrl":"http://127.0.0.1:9021", "profile":"coordinator", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-registry", + "signingKeyRef":"secret:file/registry-client-key", + "resource":"urn:example:registry", + "scopes":["records:write"] + } + }) +} + +fn runtime_document() -> Value { + let mut function = binding("http://127.0.0.1:9020/"); + function["type"] = json!("service-function"); + json!({ + "apiVersion":API_VERSION,"kind":KIND, + "secretProviders":{"environment":{}}, + "database":{ + "runtimeUrlRef":"secret:env/COORDINATOR_FUNCTION_TEST_UNRESOLVED_DATABASE", + "migrationUrlRef":"secret:env/COORDINATOR_FUNCTION_TEST_UNRESOLVED_DATABASE" + }, + "namespace":"coordinator_function_test", + "connections":{"notices":function, "registry":breg_connection()} + }) +} + +fn load(document: &Value) -> registry_coordinator::Result { + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + let mut document = document.clone(); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + RuntimeConfig::load(&path) +} + +#[test] +fn the_bound_function_is_part_of_the_binding_digest() { + let accepted = load(&runtime_document()).unwrap(); + let digest = accepted.binding_digest().unwrap(); + let mut changed = runtime_document(); + changed["connections"]["notices"]["function"] = json!("publish-notice"); + assert_ne!(load(&changed).unwrap().binding_digest().unwrap(), digest); +} + +#[test] +fn a_service_function_connection_requires_its_own_credential() { + let mut anonymous = runtime_document(); + anonymous["connections"]["notices"] + .as_object_mut() + .unwrap() + .remove("authorization"); + assert!(load(&anonymous).is_err()); + + let mut task = runtime_document(); + task["connections"]["notices"]["authorization"]["taskAuthority"] = json!({ + "baseUrl":"http://127.0.0.1:9022", "issuer":"https://identity.example.test", + "subject":"coordinator", "exchangeAudience":"urn:example:tasks", + "bootstrapResource":"urn:example:tasks" + }); + let error = load(&task) + .err() + .expect("a function call cannot acquire task authority"); + assert!( + error.field.as_deref().unwrap().contains("taskAuthority"), + "{error:?}" + ); +} + +#[test] +fn a_service_function_credential_is_never_a_product_credential() { + // The function host token must not be one a product accepts, and the + // connection must not reuse a product connection's client identity or key. + for (member, value) in [ + ("resource", "urn:example:registry"), + ("clientId", "coordinator-registry"), + ("signingKeyRef", "secret:file/registry-client-key"), + ] { + let mut document = runtime_document(); + document["connections"]["notices"]["authorization"][member] = json!(value); + let error = load(&document) + .err() + .unwrap_or_else(|| panic!("a reused product {member} is refused")); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains(&format!("/connections/notices/authorization/{member}")), + "{member}: {error:?}" + ); + assert!( + error + .suggested_action + .as_deref() + .is_some_and(|action| action.contains("registry")), + "{member}: {error:?}" + ); + } +} + +/// A runtime whose function connection carries a static host key instead of +/// an OAuth client, the way `rstack dev` and an operator recipe supply one. +fn host_key_document(base: &str) -> Value { + let mut document = runtime_document(); + let notices = &mut document["connections"]["notices"]; + notices["baseUrl"] = json!(base); + notices.as_object_mut().unwrap().remove("authorization"); + notices["hostKeyRef"] = json!("secret:file/function-host-key"); + document +} + +#[tokio::test] +async fn a_host_key_credential_is_sent_as_the_bearer_to_the_bound_function() { + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .and(header( + "authorization", + format!("Bearer {HOST_KEY}").as_str(), + )) + .and(header("idempotency-key", REQUEST_ID)) + .and(body_json(body())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&server) + .await; + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + let key = directory.join("function-host-key"); + std::fs::write(&key, HOST_KEY).unwrap(); + std::fs::set_permissions(&key, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap(); + let mut document = host_key_document(&format!("{}/", server.uri())); + document["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + let config = RuntimeConfig::load(&path).unwrap(); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let request = registry_coordinator::protocol::CallRequest { + connection: "notices".into(), + operation: Operation::InvokeServiceFunction, + input: body(), + idempotency_key: Some(REQUEST_ID.into()), + operation_contract: None, + }; + let outcome = + registry_coordinator::protocol::AdapterSet::call_attempt(&adapters, &request, None, false) + .await; + assert!( + matches!(&outcome, CallOutcome::Success(reply) if reply["status"] == 200), + "{}", + describe(&outcome) + ); + server.verify().await; +} + +#[test] +fn a_function_connection_names_exactly_one_credential() { + assert!(load(&host_key_document("http://127.0.0.1:9020/")).is_ok()); + + let mut both = host_key_document("http://127.0.0.1:9020/"); + both["connections"]["notices"]["authorization"] = function_authorization(); + let error = load(&both).err().expect("two credentials are refused"); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/notices"), + "{error:?}" + ); + + let mut neither = host_key_document("http://127.0.0.1:9020/"); + neither["connections"]["notices"] + .as_object_mut() + .unwrap() + .remove("hostKeyRef"); + assert!( + load(&neither).is_err(), + "an anonymous function connection is refused" + ); +} + +#[test] +fn a_host_key_is_never_a_product_signing_key() { + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["notices"]["hostKeyRef"] = json!("secret:file/registry-client-key"); + let error = load(&document) + .err() + .expect("a product signing key reused as a host key is refused"); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/notices/hostKeyRef"), + "{error:?}" + ); +} + +/// The refusal for one function resource, against the given runtime. +fn resource_refusal(mut document: Value, resource: &str) -> registry_coordinator::CoordinatorError { + document["connections"]["notices"]["authorization"]["resource"] = json!(resource); + load(&document) + .err() + .unwrap_or_else(|| panic!("the function resource {resource} is refused")) +} + +#[test] +fn a_function_resource_is_compared_after_normalisation() { + let mut document = runtime_document(); + document["connections"]["registry"]["authorization"]["resource"] = + json!("https://breg.example.org"); + for spelling in [ + "https://breg.example.org/", + "https://BREG.example.org", + "HTTPS://breg.example.org", + "https://breg.example.org:443/", + ] { + let error = resource_refusal(document.clone(), spelling); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/notices/authorization/resource"), + "{spelling}: {error:?}" + ); + // The remedy names the colliding connection, never a value. + let action = error.suggested_action.as_deref().unwrap_or_default(); + assert!(action.contains("registry"), "{spelling}: {action}"); + assert!(!action.contains("breg.example.org"), "{spelling}: {action}"); + } + // Another path on the same origin is another resource. + document["connections"]["notices"]["authorization"]["resource"] = + json!("https://breg.example.org/functions"); + load(&document).unwrap(); +} + +#[test] +fn a_function_resource_is_never_a_casework_or_exchange_audience() { + let mut document = runtime_document(); + document["connections"]["registry"]["authorization"]["taskAuthority"] = json!({ + "baseUrl":"https://casework.example.org", "issuer":"https://casework.example.org", + "subject":"coordinator", "exchangeAudience":"https://issuer.example.org/oauth/token", + "bootstrapResource":"urn:example:casework" + }); + for audience in [ + "urn:example:casework", + "https://issuer.example.org/oauth/token", + ] { + resource_refusal(document.clone(), audience); + } +} + +#[test] +fn a_function_resource_is_never_a_scheduling_messaging_or_external_audience() { + let mut document = runtime_document(); + let connections = document["connections"].as_object_mut().unwrap(); + connections.insert( + "bookings".into(), + json!({ + "type":"scheduling", "baseUrl":"http://127.0.0.1:9022", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-bookings", + "signingKeyRef":"secret:file/bookings-client-key", + "resource":"urn:example:scheduling", "scopes":["scheduling:book"], + "taskAuthority":{ + "baseUrl":"https://casework.example.org", "issuer":"https://casework.example.org", + "subject":"coordinator", "exchangeAudience":"urn:example:exchange", + "bootstrapResource":"urn:example:casework" + } + }, + "observationAuthorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-bookings", + "signingKeyRef":"secret:file/bookings-client-key", + "resource":"urn:example:scheduling", "scopes":["scheduling:read"] + } + }), + ); + connections.insert( + "letters".into(), + json!({ + "type":"messaging", "baseUrl":"http://127.0.0.1:9023", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-letters", + "signingKeyRef":"secret:file/letters-client-key", + "resource":"urn:example:messaging", "scopes":["messaging:send"] + } + }), + ); + connections.insert( + "legacy".into(), + json!({ + "type":"external-http", "baseUrl":"https://legacy.example.org/", + "paths":["requests/status"], "commandPath":"requests", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-legacy", + "signingKeyRef":"secret:file/legacy-client-key", + "resource":"https://legacy.example.org", "scopes":["requests:create"] + }, + "responseSchema":{"type":"object"} + }), + ); + load(&document).unwrap(); + for (audience, connection) in [ + // An observation credential shares its primary resource by rule. + ("urn:example:scheduling", "bookings"), + ("urn:example:messaging", "letters"), + ("https://legacy.example.org/", "legacy"), + ] { + let error = resource_refusal(document.clone(), audience); + let action = error.suggested_action.as_deref().unwrap_or_default(); + assert!(action.contains(connection), "{audience}: {action}"); + } + let mut document = document.clone(); + document["connections"]["notices"]["authorization"]["clientId"] = json!("coordinator-letters"); + assert!(load(&document).is_err(), "a messaging client is refused"); +} + +#[test] +fn a_function_resource_is_never_the_coordinator_audience() { + let example = + include_str!("../../../products/coordinator/examples/delayed-follow-up/runtime.yaml"); + let function = " drafts:\n type: service-function\n baseUrl: http://127.0.0.1:9020/\n function: draft-notice\n authorization:\n tokenEndpoint: http://127.0.0.1:8090/token\n clientAssertionAudience: http://127.0.0.1:8090\n clientId: coordinator-functions\n signingKeyRef: secret:file/function-key\n resource: RESOURCE\n scopes: [functions:invoke]\n responseSchema: {type: object}\n"; + let write = |resource: &str| { + let root = tempfile::tempdir().unwrap(); + let path = root.path().canonicalize().unwrap().join("runtime.yaml"); + let text = example.replacen( + "connections:\n", + &format!("connections:\n{}", function.replace("RESOURCE", resource)), + 1, + ); + std::fs::write(&path, text).unwrap(); + RuntimeConfig::load(&path) + }; + write("urn:example:notice-functions").unwrap(); + let error = write("urn:example:coordinator") + .err() + .expect("the Coordinator's own audience is refused"); + assert!( + error + .field + .as_deref() + .unwrap_or_default() + .contains("/connections/drafts/authorization/resource"), + "{error:?}" + ); +} + +#[test] +fn a_taskauthority_refusal_names_the_service_function_remedy() { + let mut document = runtime_document(); + document["connections"]["notices"]["authorization"]["taskAuthority"] = json!({ + "baseUrl":"http://127.0.0.1:9022", "issuer":"https://identity.example.test", + "subject":"coordinator", "exchangeAudience":"urn:example:tasks", + "bootstrapResource":"urn:example:tasks" + }); + let error = load(&document).err().unwrap(); + let action = error.suggested_action.as_deref().unwrap_or_default(); + assert!(action.contains("service function"), "{action}"); + assert!(!action.contains("external GET"), "{action}"); +} + +/// Two distinct private signing keys. +const KEY: &str = registry_platform_testing::fixtures::ED25519_PRIVATE_JWK; +const OTHER_KEY: &str = registry_platform_testing::fixtures::ED25519_ROTATED_PRIVATE_JWK; + +/// A runtime file in a private secret directory holding the named secrets. +fn with_secrets(document: &Value, secrets: &[(&str, &str)]) -> (tempfile::TempDir, RuntimeConfig) { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + for (name, value) in secrets { + let path = directory.join(name); + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let mut document = document.clone(); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + let config = RuntimeConfig::load(&path).unwrap(); + (root, config) +} + +#[test] +fn the_same_signing_key_under_another_reference_is_refused_at_startup() { + let shared = KEY; + let (_root, config) = with_secrets( + &runtime_document(), + &[ + ("function-client-key", shared), + ("registry-client-key", shared), + ], + ); + let error = registry_coordinator::adapters::HttpAdapters::new(&config) + .err() + .expect("one key behind two references is refused"); + assert!(error.message.contains("notices"), "{error:?}"); + assert!(error.message.contains("registry"), "{error:?}"); + assert!(!error.message.contains(shared)); + + let (_root, config) = with_secrets( + &runtime_document(), + &[ + ("function-client-key", OTHER_KEY), + ("registry-client-key", shared), + ], + ); + registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); +} + +fn call(operation: Operation, key: Option<&str>) -> registry_coordinator::protocol::CallRequest { + registry_coordinator::protocol::CallRequest { + connection: "notices".into(), + operation, + input: body(), + idempotency_key: key.map(str::to_owned), + operation_contract: None, + } +} + +#[tokio::test] +async fn the_runtime_routes_a_function_call_with_its_oauth_token_and_frozen_request_id() { + use registry_coordinator::protocol::AdapterSet; + let token = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token":"fixture-function-token", "token_type":"Bearer", "expires_in":60, + "issued_token_type":"urn:ietf:params:oauth:token-type:access_token" + }))) + .mount(&token) + .await; + let host = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .and(header("authorization", "Bearer fixture-function-token")) + .and(header("idempotency-key", REQUEST_ID)) + .and(body_json(body())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&host) + .await; + let mut document = runtime_document(); + document["connections"]["notices"]["baseUrl"] = json!(format!("{}/", host.uri())); + document["connections"]["notices"]["authorization"]["tokenEndpoint"] = + json!(format!("{}/token", token.uri())); + let (_root, config) = with_secrets( + &document, + &[ + ("function-client-key", OTHER_KEY), + ("registry-client-key", KEY), + ], + ); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let outcome = adapters + .call_attempt( + &call(Operation::InvokeServiceFunction, Some(REQUEST_ID)), + None, + false, + ) + .await; + assert!( + matches!(&outcome, CallOutcome::Success(reply) if reply["status"] == 200), + "{}", + describe(&outcome) + ); + // A call without its frozen request id, and any other operation on the + // function connection, is refused before anything is sent. + for (operation, key) in [ + (Operation::InvokeServiceFunction, None), + (Operation::ExternalCommand, Some(REQUEST_ID)), + (Operation::ExternalGet, None), + ] { + let refused = adapters.call(&call(operation, key)).await; + assert!( + matches!(&refused, CallOutcome::Refused { .. }), + "{}: {}", + operation.as_str(), + describe(&refused) + ); + } + host.verify().await; +} + +#[tokio::test] +async fn a_lost_acknowledgement_is_uncertain_and_the_same_request_id_is_sent_again() { + use registry_coordinator::protocol::AdapterSet; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let mut seen = Vec::new(); + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 4096]; + while !buffer.windows(4).any(|window| window == b"\r\n\r\n") { + let read = socket.read(&mut chunk).await.unwrap(); + assert!(read > 0); + buffer.extend_from_slice(&chunk[..read]); + } + let head = String::from_utf8_lossy(&buffer).to_string(); + assert!( + head.starts_with("POST /functions/draft-notice HTTP/1.1\r\n"), + "{head}" + ); + let key = head + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("idempotency-key") + .then(|| value.trim().to_owned()) + }) + .unwrap(); + seen.push(key); + if attempt == 0 { + drop(socket); + continue; + } + let reply = br#"{"draftId":"draft-001"}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + reply.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); + socket.write_all(reply).await.unwrap(); + socket.shutdown().await.unwrap(); + } + seen + }); + let document = host_key_document(&format!("http://{address}/")); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let request = call(Operation::InvokeServiceFunction, Some(REQUEST_ID)); + let first = adapters.call_attempt(&request, None, false).await; + assert!( + matches!(&first, CallOutcome::Uncertain { code } if code == "transport-uncertain"), + "{}", + describe(&first) + ); + let second = adapters.call_attempt(&request, None, true).await; + assert!( + matches!(&second, CallOutcome::Success(reply) if reply["status"] == 200), + "{}", + describe(&second) + ); + let seen = tokio::time::timeout(std::time::Duration::from_secs(10), server) + .await + .unwrap() + .unwrap(); + assert_eq!(seen, [REQUEST_ID, REQUEST_ID]); +} + +#[tokio::test] +async fn a_busy_answer_on_the_final_attempt_holds_instead_of_retrying() { + use registry_coordinator::protocol::AdapterSet; + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let host = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(503)) + .expect(2) + .mount(&host) + .await; + let (_root, config) = with_secrets( + &host_key_document(&format!("{}/", host.uri())), + &[ + ("function-host-key", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let adapters = registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); + let request = call(Operation::InvokeServiceFunction, Some(REQUEST_ID)); + let early = adapters.call_attempt(&request, None, false).await; + assert!( + matches!(&early, CallOutcome::UncertainRetryable { code, .. } if code == "external-unavailable"), + "{}", + describe(&early) + ); + let last = adapters.call_attempt(&request, None, true).await; + assert!( + matches!(&last, CallOutcome::Uncertain { code } if code == "external-uncertain"), + "{}", + describe(&last) + ); + host.verify().await; +} + +/// The diagnostics `check` reports for a runtime document, with their +/// related locations. +fn checked(document: &Value) -> Vec { + let root = tempfile::tempdir().unwrap(); + let directory = root.path().canonicalize().unwrap(); + let mut document = document.clone(); + document["secretProviders"]["file"] = json!({"root":directory}); + let path = directory.join("runtime.yaml"); + std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap(); + RuntimeConfig::check_file(&path, true).diagnostics +} + +/// The one diagnostic at `path`, which must name `related` as the colliding +/// location. +fn collision(document: &Value, path: &str, related: &str) { + let diagnostics = checked(document); + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.path == path) + .unwrap_or_else(|| panic!("no diagnostic at {path}: {diagnostics:#?}")); + assert!( + found.related.iter().any(|other| other.path == related), + "{path} names {related}: {found:#?}" + ); +} + +#[test] +fn a_credential_collision_names_the_colliding_member_as_related() { + let mut document = runtime_document(); + document["connections"]["notices"]["authorization"]["resource"] = json!("urn:example:registry"); + collision( + &document, + "/connections/notices/authorization/resource", + "/connections/registry/authorization/resource", + ); +} + +#[test] +fn a_function_resource_is_compared_with_any_trailing_slash_and_urn_case() { + let mut document = runtime_document(); + document["connections"]["registry"]["authorization"]["resource"] = + json!("https://breg.example.org/v1"); + resource_refusal(document.clone(), "https://breg.example.org/v1/"); + document["connections"]["registry"]["authorization"]["resource"] = + json!("urn:example:registry"); + resource_refusal(document.clone(), "URN:Example:registry"); + // The namespace-specific part of a URN keeps its case. + document["connections"]["notices"]["authorization"]["resource"] = json!("urn:example:REGISTRY"); + load(&document).unwrap(); +} + +fn evaluation_connection(token: &str) -> Value { + json!({ + "type":"evaluation", "protocol":"system-one", "baseUrl":"http://127.0.0.1:9024/", + "model":"synthetic-model", + "authorization":{"bearer":{"tokenRef":token, "principal":"coordinator"}} + }) +} + +#[test] +fn a_host_key_is_never_an_evaluation_completion_or_event_key() { + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["decide"] = evaluation_connection("secret:file/function-host-key"); + collision( + &document, + "/connections/notices/hostKeyRef", + "/connections/decide/authorization/bearer/tokenRef", + ); + + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["review"] = json!({ + "type":"casework-review-producer", "baseUrl":"http://127.0.0.1:9025", + "profile":"producer", "producer":"coordinator", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-review", "signingKeyRef":"secret:file/review-client-key", + "resource":"urn:example:casework", "scopes":["casework:review"] + }, + "completion":{"recipientBinding":"coordinator-v1", "hmacSha256KeyRef":"secret:file/function-host-key"} + }); + collision( + &document, + "/connections/notices/hostKeyRef", + "/connections/review/completion/hmacSha256KeyRef", + ); + + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["eventSources"] = json!({"registry-events": { + "source":"https://events.example.org", + "triggers":{"notice-draft":{"on-change":{"hmacSha256KeyRef":"secret:file/function-host-key"}}} + }}); + collision( + &document, + "/connections/notices/hostKeyRef", + "/eventSources/registry-events/triggers/notice-draft/on-change/hmacSha256KeyRef", + ); +} + +#[test] +fn a_host_key_is_never_a_deployment_key() { + let example = + include_str!("../../../products/coordinator/examples/delayed-follow-up/runtime.yaml"); + let function = " drafts:\n type: service-function\n baseUrl: http://127.0.0.1:9020/\n function: draft-notice\n hostKeyRef: KEY\n responseSchema: {type: object}\n"; + for (key, related) in [ + ("secret:file/audit-key", "/deployment/auditKeyRef"), + ("secret:file/state-key-1", "/deployment/stateKeys/1/keyRef"), + ("secret:file/admission-key", "/deployment/admissionKeyRef"), + ] { + let root = tempfile::tempdir().unwrap(); + let path = root.path().canonicalize().unwrap().join("runtime.yaml"); + std::fs::write( + &path, + example.replacen( + "connections:\n", + &format!("connections:\n{}", function.replace("KEY", key)), + 1, + ), + ) + .unwrap(); + let diagnostics = RuntimeConfig::check_file(&path, true).diagnostics; + let found = diagnostics + .iter() + .find(|diagnostic| diagnostic.path == "/connections/drafts/hostKeyRef") + .unwrap_or_else(|| panic!("{key}: {diagnostics:#?}")); + assert!( + found.related.iter().any(|other| other.path == related), + "{key}: {found:#?}" + ); + } +} + +#[test] +fn rotating_the_host_key_keeps_the_binding_and_changing_the_credential_kind_does_not() { + let document = host_key_document("http://127.0.0.1:9020/"); + let digest = load(&document).unwrap().binding_digest().unwrap(); + let mut rotated = document.clone(); + rotated["connections"]["notices"]["hostKeyRef"] = json!("secret:file/function-host-key-2"); + assert_eq!(load(&rotated).unwrap().binding_digest().unwrap(), digest); + assert_ne!( + load(&runtime_document()).unwrap().binding_digest().unwrap(), + digest + ); +} + +#[test] +fn a_binary_key_elsewhere_in_the_runtime_does_not_stop_a_function_host_from_starting() { + // Binary key files hold random bytes, NUL included. Comparing the + // function host key with them must read them as bytes, not as text. + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + document["connections"]["review"] = json!({ + "type":"casework-review-producer", "baseUrl":"http://127.0.0.1:9022", + "profile":"coordinator-producer", "producer":"coordinator", + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientAssertionAudience":"http://127.0.0.1:9999", + "clientId":"coordinator-producer", + "signingKeyRef":"secret:file/review-client-key", + "resource":"urn:example:review", + "scopes":["casework:review"] + }, + "completion":{ + "recipientBinding":"coordinator-v1", + "hmacSha256KeyRef":"secret:file/review-completion-key" + } + }); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", "synthetic-function-host-key-canary"), + ("review-client-key", KEY), + ( + "review-completion-key", + "binary\0completion-key-0123456789abcdef", + ), + ], + ); + registry_coordinator::adapters::HttpAdapters::new(&config).unwrap(); +} + +#[test] +fn the_same_host_key_or_jwk_under_another_form_is_refused_at_startup() { + const HOST_KEY: &str = "synthetic-function-host-key-canary"; + let mut document = host_key_document("http://127.0.0.1:9020/"); + document["connections"]["decide"] = evaluation_connection("secret:file/decision-token"); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", HOST_KEY), + ("decision-token", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let error = registry_coordinator::adapters::HttpAdapters::new(&config) + .err() + .expect("one host key behind two references is refused"); + assert!(error.message.contains("decide"), "{error:?}"); + + // The host key is sent without its trailing newline, so a file that + // differs only by that newline holds the same key. + let host_key_line = format!("{HOST_KEY}\n"); + let (_root, config) = with_secrets( + &document, + &[ + ("function-host-key", &host_key_line), + ("decision-token", HOST_KEY), + ("registry-client-key", KEY), + ], + ); + let error = registry_coordinator::adapters::HttpAdapters::new(&config) + .err() + .expect("a host key and the same key without its newline are refused"); + assert!(error.message.contains("decide"), "{error:?}"); + + // The same JWK written again with its members in another order and + // spacing is the same key. + let parsed: serde_json::Map = serde_json::from_str(KEY).unwrap(); + let reordered = + serde_json::to_string_pretty(&parsed.into_iter().rev().collect::>()) + .unwrap(); + assert_ne!(reordered, KEY); + let (_root, config) = with_secrets( + &runtime_document(), + &[ + ("function-client-key", &reordered), + ("registry-client-key", KEY), + ], + ); + assert!(registry_coordinator::adapters::HttpAdapters::new(&config).is_err()); +} diff --git a/crates/registry-coordinator/tests/service_function_postgres.rs b/crates/registry-coordinator/tests/service_function_postgres.rs new file mode 100644 index 0000000000..bd6304ee9b --- /dev/null +++ b/crates/registry-coordinator/tests/service_function_postgres.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: Apache-2.0 +//! `service.invoke-function/v1` over real HTTP and durable PostgreSQL: the +//! run records the step and its typed result, the function host receives the +//! frozen request id and the function host credential, and nothing an operator +//! reads carries the request body, request id or credential. +#![cfg(feature = "postgres-test")] + +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use registry_coordinator::{ + definition::Definition, + external_http::{ExternalHttpConnection, ServiceFunctionConfig}, + protocol::{AdapterSet, CallOutcome, CallRequest, Operation}, + store::Store, + worker::Worker, +}; +use registry_platform_httputil::client::StaticToken; +use serde_json::{json, Value}; +use uuid::Uuid; +use wiremock::{ + matchers::{body_json, header, header_exists, method, path}, + Mock, MockServer, ResponseTemplate, +}; + +const REFERENCE: &str = "application-body-canary"; +const TOKEN: &str = "synthetic-function-host-token-canary"; +const BINDING: &str = "service-function-binding"; + +/// The runtime's service function adapter, recording each frozen request id. +struct FunctionAdapter { + connection: ExternalHttpConnection, + keys: Arc>>, +} + +#[async_trait] +impl AdapterSet for FunctionAdapter { + fn binding_digest(&self) -> &str { + BINDING + } + + async fn call(&self, request: &CallRequest) -> CallOutcome { + self.call_attempt(request, None, false).await + } + + async fn call_attempt( + &self, + request: &CallRequest, + prepared: Option<&[u8]>, + final_attempt: bool, + ) -> CallOutcome { + assert_eq!(request.operation, Operation::InvokeServiceFunction); + assert_eq!(request.connection, "notices"); + assert!( + prepared.is_none(), + "a function call has no prepared evidence" + ); + let key = request + .idempotency_key + .clone() + .expect("a function call carries its frozen request id"); + self.keys.lock().unwrap().push(key.clone()); + self.connection + .command(&request.input, &key, final_attempt) + .await + } +} + +struct Harness { + _project: tempfile::TempDir, + definition: Definition, + store: Arc, + keys: Arc>>, +} + +impl Harness { + async fn new() -> Self { + let project = tempfile::tempdir().unwrap(); + let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/service-function"); + for name in ["workflow.yaml", "functions.rhai"] { + std::fs::copy(source.join(name), project.path().join(name)).unwrap(); + } + let definition = Definition::load(project.path()).expect("the function fixture compiles"); + let url = std::env::var("COORDINATOR_TEST_DATABASE_URL") + .expect("disposable PostgreSQL is required"); + let namespace = format!("coordinator_{}", Uuid::new_v4().simple()); + let store = Arc::new(Store::connect(&url, &namespace).await.unwrap()); + store.migrate().await.unwrap(); + Self { + _project: project, + definition, + store, + keys: Arc::default(), + } + } + + /// The operator's binding: the host, function and credential come only + /// from here. + fn worker(&self, base: &str) -> Worker { + let config: ServiceFunctionConfig = serde_json::from_value(json!({ + "baseUrl":base, "function":"draft-notice", + "responseSchema":{"type":"object"}, + "authorization":{ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientId":"coordinator-functions", + "clientAssertionAudience":"http://127.0.0.1:9999", + "signingKeyRef":"secret:file/function-client-key", + "resource":"urn:example:notice-functions", "scopes":["functions:invoke"] + } + })) + .unwrap(); + let tokens = Arc::new(StaticToken::new(TOKEN).unwrap()); + let adapters = Arc::new(FunctionAdapter { + connection: ExternalHttpConnection::service_function(&config, tokens).unwrap(), + keys: self.keys.clone(), + }); + Worker::new(self.store.clone(), adapters) + } + + async fn run(&self, base: &str) -> Value { + let run = self + .store + .admit( + &self.definition, + json!({"reference":REFERENCE}), + "service-function-producer", + &Uuid::new_v4().to_string(), + BINDING, + ) + .await + .unwrap(); + let worker = self.worker(base); + let mut quiet = false; + for _ in 0..8 { + if !worker.tick().await.unwrap() { + quiet = true; + break; + } + } + assert!(quiet, "bounded workflow did not quiesce"); + let inspection = + serde_json::to_value(self.store.inspect(run, BINDING).await.unwrap()).unwrap(); + let status = serde_json::to_string(&self.store.status(run).await.unwrap()).unwrap(); + let keys = self.keys.lock().unwrap().clone(); + assert_eq!(keys.len(), 1, "one frozen request is sent once"); + for text in [inspection.to_string(), status] { + assert!(!text.contains(REFERENCE)); + assert!(!text.contains(TOKEN)); + assert!(!text.contains(keys[0].as_str())); + } + inspection + } +} + +#[tokio::test] +async fn an_accepted_function_call_records_the_step_and_its_typed_result() { + let h = Harness::new().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .and(header_exists("idempotency-key")) + .and(header("authorization", format!("Bearer {TOKEN}").as_str())) + .and(body_json(json!({"reference":REFERENCE}))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"draftId":"draft-001"}))) + .expect(1) + .mount(&server) + .await; + let inspection = h.run(&server.uri()).await; + assert_eq!(inspection["run"]["state"], "finished"); + assert_eq!(inspection["run"]["outcome"], "drafted"); + assert_eq!(inspection["run"]["output"], json!({"draftId":"draft-001"})); + let effect = &inspection["effects"][0]; + assert_eq!(effect["state"], "accepted"); + assert_eq!(effect["step"], "draft"); + assert_eq!(effect["operation"]["id"], "service.invoke-function/v1"); + assert_eq!(effect["operation"]["product"], "service-function"); + let received = server.received_requests().await.unwrap(); + assert_eq!( + received[0].headers["idempotency-key"].to_str().unwrap(), + h.keys.lock().unwrap()[0], + "the function host receives the frozen request id" + ); +} + +#[tokio::test] +async fn a_declared_refusal_takes_the_workflow_refusal_route() { + let h = Harness::new().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(422).set_body_json(json!({"reason":"not-eligible"}))) + .expect(1) + .mount(&server) + .await; + let inspection = h.run(&server.uri()).await; + assert_eq!(inspection["run"]["outcome"], "not-drafted"); + assert_eq!( + inspection["run"]["output"], + json!({"refusalCode":"not-eligible"}) + ); + assert_eq!( + inspection["effects"], + json!([]), + "a refusal claims no effect" + ); +} + +#[tokio::test] +async fn an_authority_refusal_the_interpretation_does_not_recognise_holds_the_run() { + let h = Harness::new().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/functions/draft-notice")) + .respond_with(ResponseTemplate::new(403).set_body_json(json!({}))) + .expect(1) + .mount(&server) + .await; + let inspection = h.run(&server.uri()).await; + assert_eq!(inspection["run"]["state"], "attention", "{inspection}"); + assert_eq!(inspection["run"]["uncertain"], true); + assert_eq!(inspection["run"]["failureCode"], "external-uncertain"); + assert_eq!(inspection["effects"][0]["step"], "draft"); + assert_eq!(inspection["effects"][0]["state"], "unknown"); + assert_eq!(inspection["recovery"]["retryAllowed"], true); +} diff --git a/crates/registry-coordinator/tests/service_function_project.rs b/crates/registry-coordinator/tests/service_function_project.rs new file mode 100644 index 0000000000..f6d76b4f9e --- /dev/null +++ b/crates/registry-coordinator/tests/service_function_project.rs @@ -0,0 +1,397 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Authoring, checking and synthetic scenarios for +//! `service.invoke-function/v1`. A project names one service function, a pure +//! Transform that builds its body, and a +//! pure Transform that interprets the answer. The runtime file alone binds the +//! function host, the function and the credential. +use registry_coordinator::{ + definition::{Definition, Step}, + protocol::Operation, + scenarios, +}; +use serde_json::{json, Value}; +use std::{fs, path::Path, process::Command}; + +const WORKFLOW: &str = include_str!("fixtures/service-function/workflow.yaml"); +const FUNCTIONS: &str = include_str!("fixtures/service-function/functions.rhai"); +const RUNTIME: &str = include_str!("fixtures/service-function/runtime.yaml"); +const FIXTURE_DRAFTED: &str = include_str!("fixtures/service-function/fixtures/drafted.yaml"); +const FIXTURE_NOT_ELIGIBLE: &str = + include_str!("fixtures/service-function/fixtures/not-eligible.yaml"); +const FIXTURE_HOLDS: &str = + include_str!("fixtures/service-function/fixtures/unrecognised-answer-holds.yaml"); + +fn replaced(text: &str, replacements: &[(&str, &str)]) -> String { + let mut text = text.to_owned(); + for (from, to) in replacements { + assert!(text.contains(from), "{from}"); + text = text.replacen(from, to, 1); + } + text +} + +fn project(root: &Path, replacements: &[(&str, &str)]) { + fs::write(root.join("workflow.yaml"), replaced(WORKFLOW, replacements)).unwrap(); + fs::write(root.join("functions.rhai"), FUNCTIONS).unwrap(); +} + +fn cli(arguments: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_coordinatorctl")) + .args(arguments) + .env_remove("COORDINATOR_TEST_DATABASE_URL") + .output() + .unwrap() +} + +fn check(root: &Path) -> (i32, Value) { + let output = cli(&[ + "--format", + "json", + "check", + "--project", + root.to_str().unwrap(), + ]); + let report = serde_json::from_slice(&output.stdout).unwrap_or_else(|_| { + panic!( + "a JSON check report: {}", + String::from_utf8_lossy(&output.stdout) + ) + }); + (output.status.code().unwrap(), report) +} + +/// The findings `check` reports for a project that must be refused. +fn refused(replacements: &[(&str, &str)]) -> Vec { + let root = tempfile::tempdir().unwrap(); + project(root.path(), replacements); + let (exit, report) = check(root.path()); + assert_eq!(exit, 1, "{report}"); + report["diagnostics"].as_array().unwrap().clone() +} + +fn finding<'a>(findings: &'a [Value], path: &str, expected: &[&str]) -> &'a Value { + let found = findings + .iter() + .find(|finding| finding["path"] == path) + .unwrap_or_else(|| panic!("no finding at {path}: {findings:#?}")); + let message = found["message"].as_str().unwrap(); + for text in expected { + assert!(message.contains(text), "{text}: {message}"); + } + found +} + +/// The project checked against one runtime file. +fn check_with_runtime(runtime: &str) -> (i32, Value) { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + fs::write(root.path().join("runtime.yaml"), runtime).unwrap(); + check(root.path()) +} + +fn binding_finding(runtime: &str) -> Value { + let (exit, report) = check_with_runtime(runtime); + assert_eq!(exit, 1, "{report}"); + report["diagnostics"] + .as_array() + .unwrap() + .iter() + .find(|finding| finding["code"] == "coordinator.runtime.workflow-binding") + .unwrap_or_else(|| panic!("no workflow binding finding: {report}")) + .clone() +} + +#[test] +fn a_named_service_function_checks_and_explains_without_its_destination() { + let (exit, report) = check_with_runtime(RUNTIME); + assert_eq!(exit, 0, "{report}"); + let rendered = report.to_string(); + assert!(!rendered.contains("FUNCTION_CLIENT_KEY"), "{rendered}"); + + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let output = cli(&[ + "--format", + "json", + "explain", + "--project", + root.path().to_str().unwrap(), + ]); + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(!text.contains("127.0.0.1"), "{text}"); + let explained: Value = serde_json::from_str(&text).unwrap(); + let draft = explained["steps"] + .as_array() + .unwrap() + .iter() + .find(|step| step["id"] == "draft") + .unwrap(); + assert_eq!(draft["uses"], "service.invoke-function/v1"); + assert_eq!(draft["product"], "service-function"); + assert_eq!(draft["mutating"], true); + assert_eq!(draft["recovery"], "same-command"); + assert_eq!(draft["onDeclaredRefusal"], "not-drafted"); + assert_eq!( + explained["operations"]["draft-notice"]["serviceFunction"], + "draft-notice" + ); + let http = &explained["operationContracts"]["service.invoke-function/v1"]["limits"]["http"]; + assert_eq!(http["maximumRequestBytes"], 65_536); + assert_eq!(http["redirects"], "refused"); +} + +#[test] +fn the_named_function_is_part_of_the_operation_revision() { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let operation = &definition.workflow.operations["draft-notice"]; + assert_eq!(operation.uses, Operation::InvokeServiceFunction); + assert_eq!(operation.service_function.as_deref(), Some("draft-notice")); + + let other = tempfile::tempdir().unwrap(); + project( + other.path(), + &[( + "serviceFunction: draft-notice", + "serviceFunction: publish-notice", + )], + ); + let renamed = Definition::load(other.path()).unwrap(); + assert_ne!( + renamed.workflow.operations["draft-notice"].revision, + operation.revision + ); + + // A restored snapshot cannot swap the named function. + let snapshot = definition.snapshot().unwrap(); + let swapped = snapshot.replacen( + "\"serviceFunction\":\"draft-notice\"", + "\"serviceFunction\":\"publish-notice\"", + 1, + ); + assert_ne!(swapped, snapshot); + assert!(Definition::from_snapshot(&swapped).is_err()); +} + +#[test] +fn a_missing_function_name_is_refused_at_the_operation() { + let findings = refused(&[(" serviceFunction: draft-notice\n", "")]); + finding( + &findings, + "/operations/draft-notice/serviceFunction", + &["service.invoke-function/v1", "serviceFunction"], + ); +} + +#[test] +fn a_function_name_must_be_a_local_identifier() { + let findings = refused(&[("serviceFunction: draft-notice", "serviceFunction: ../admin")]); + assert!( + findings.iter().any(|finding| finding["path"] + .as_str() + .unwrap_or_default() + .starts_with("/operations/draft-notice/serviceFunction")), + "{findings:#?}" + ); +} + +#[test] +fn only_the_service_function_operation_names_a_function() { + let findings = refused(&[( + "uses: service.invoke-function/v1", + "uses: external.command/v1", + )]); + finding( + &findings, + "/operations/draft-notice/serviceFunction", + &["only service.invoke-function/v1"], + ); +} + +#[test] +fn the_interpretation_is_required_on_the_service_function() { + let findings = refused(&[(" interpret: draft-outcome\n", "")]); + finding( + &findings, + "/operations/draft-notice/interpret", + &["service.invoke-function/v1", "interpret"], + ); +} + +#[test] +fn an_unbound_function_name_is_refused_against_the_runtime_binding() { + let unbound = + binding_finding(&RUNTIME.replace("function: draft-notice", "function: publish-notice")); + assert_eq!(unbound["path"], "/operations/draft-notice/serviceFunction"); + assert!( + unbound["related"].as_array().is_some_and(|related| related + .iter() + .any(|other| other["path"] == "/connections/notices/function")), + "{unbound}" + ); + assert!( + unbound["message"] + .as_str() + .unwrap() + .contains("draft-notice"), + "{unbound}" + ); + + // No connection of the workflow's logical name. + let missing = binding_finding(&RUNTIME.replace(" notices:", " other-notices:")); + assert_eq!(missing["path"], "/connections/notices"); + + // An external HTTP connection cannot carry a service function call. + let external = binding_finding(&replaced( + RUNTIME, + &[ + ("type: service-function", "type: external-http"), + ( + " function: draft-notice\n", + " paths: [drafts]\n commandPath: drafts\n", + ), + ], + )); + assert_eq!(external["path"], "/connections/notices"); +} + +#[test] +fn the_workflow_cannot_name_a_destination_or_credential() { + for member in [ + " baseUrl: http://127.0.0.1:9030/\n", + " function: publish-notice\n", + " headers: {Authorization: Bearer x}\n", + " authorization: {token: x}\n", + ] { + let findings = refused(&[( + " interpret: draft-outcome\n", + &format!(" interpret: draft-outcome\n{member}"), + )]); + assert!( + findings.iter().any(|finding| finding["path"] + .as_str() + .unwrap_or_default() + .starts_with("/operations/draft-notice")), + "{member}: {findings:#?}" + ); + } +} + +fn scenario_reports(fixture: &str) -> Vec { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let document = scenarios::decode(fixture, "fixture.yaml").unwrap(); + scenarios::check(&definition, &document).unwrap() +} + +#[test] +fn scenarios_record_the_step_through_the_pinned_interpretation() { + let drafted = scenario_reports(FIXTURE_DRAFTED).remove(0); + assert_eq!(drafted.state, "completed"); + assert_eq!(drafted.output, Some(json!({"draftId":"draft-001"}))); + assert_eq!(drafted.call_attempts["draft"], 1); + assert_eq!(drafted.frozen_commands, 1); + + let refused = scenario_reports(FIXTURE_NOT_ELIGIBLE).remove(0); + assert_eq!(refused.outcome.as_deref(), Some("not-drafted")); + assert_eq!(refused.output, Some(json!({"refusalCode":"not-eligible"}))); + + // An authority refusal the interpretation does not recognise holds the + // run instead of reading as a settled answer. + let held = scenario_reports(FIXTURE_HOLDS).remove(0); + assert_eq!(held.state, "uncertain"); + assert_eq!(held.path, ["draft"]); +} + +#[test] +fn a_function_reply_reaches_its_result_only_through_the_interpret_transform() { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let source = replaced( + FIXTURE_DRAFTED, + &[( + " - type: response\n value:\n status: 200\n body:\n draftId: draft-001\n", + " - type: success\n value: {draftId: draft-001}\n", + )], + ); + let document = scenarios::decode(&source, "fixture.yaml").unwrap(); + let error = scenarios::check(&definition, &document) + .err() + .expect("a synthetic result skips the interpretation"); + assert_eq!(error.code, "scenario.reply"); + assert!( + error.message.contains("service.invoke-function/v1"), + "{}", + error.message + ); +} + +#[test] +fn the_step_output_is_the_accepted_result() { + let root = tempfile::tempdir().unwrap(); + project(root.path(), &[]); + let definition = Definition::load(root.path()).unwrap(); + let Some(Step::Call { call, .. }) = definition.workflow.steps.get("draft") else { + panic!("draft is a call"); + }; + let contract = definition.operation_contract(call).unwrap(); + assert!(contract + .check_output(&json!({"draftId":"draft-001"})) + .is_ok()); + assert!(contract + .check_output(&json!({"status":200,"body":{"draftId":"draft-001"}})) + .is_err()); + assert!(contract + .check_refusal(&json!({"refusalCode":"not-eligible"})) + .is_ok()); +} + +#[test] +fn unresolved_routed_straight_to_a_service_function_is_refused() { + // The function's effect is unknown to Coordinator, so "not found, so call + // the function" is refused as "not found, so create" is. + let findings = refused(&[ + ( + "operations:\n", + "operations:\n find:\n uses: breg.lookup-record/v1\n connection: register\n", + ), + (" start: draft\n", " start: lookup\n"), + ( + " steps:\n", + concat!( + " steps:\n", + " lookup:\n", + " type: call\n", + " operation: find\n", + " input:\n", + " type: fields\n", + " fields:\n", + " entity: {type: literal, value: notices}\n", + " selector: {type: literal, value: by-reference}\n", + " values:\n", + " type: fields\n", + " fields:\n", + " reference: {type: input, path: /reference}\n", + " next: known\n", + " onDeclaredRefusal: draft\n", + " known:\n", + " type: finish\n", + " outcome: known\n", + ), + ), + ( + " outcomes:\n", + " outcomes:\n known: {type: \"null\"}\n", + ), + ]); + assert!( + findings + .iter() + .any(|finding| finding["code"] == "coordinator.definition.unresolved-route"), + "{findings:#?}" + ); +} diff --git a/crates/registry-coordinator/tests/static_key_set.rs b/crates/registry-coordinator/tests/static_key_set.rs index 6e5d8f8330..266a899028 100644 --- a/crates/registry-coordinator/tests/static_key_set.rs +++ b/crates/registry-coordinator/tests/static_key_set.rs @@ -30,7 +30,7 @@ async fn build(document: &Value) -> Result<(), registry_coordinator::Coordinator fs::write(&file, document.to_string()).unwrap(); fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); let secrets = SecretProvidersConfig { - file: Some(FileSecretProviderConfig { root: root_path }), + file: Some(FileSecretProviderConfig::new(root_path)), environment: None, }; let envelope = RuntimeEnvelope { diff --git a/crates/registry-coordinator/tests/support/breg_service.rs b/crates/registry-coordinator/tests/support/breg_service.rs index 8f4bded57e..960b9f5294 100644 --- a/crates/registry-coordinator/tests/support/breg_service.rs +++ b/crates/registry-coordinator/tests/support/breg_service.rs @@ -176,11 +176,11 @@ impl Breg { "fields":[{"id":"owner", "type":"string", "required":true, "maximumLength":80, "classification":"internal"}, {"id":"label", "type":"string", "required":true, "minimumLength":1, "maximumLength":80, "classification":"internal"}]}}, "datasets":{"synthetic-items": {}}, - "functions":{"update-item-plan": {"runtime":"rhai","source":"scripts/update-item.rhai","entrypoint":"plan","abi":"registry.action-plan/v1"}}, + "transforms":{"update-item-plan": {"runtime":"rhai","source":"scripts/update-item.rhai","entrypoint":"plan","abi":"registry.action-plan/v1"}}, "actions":{"update-item": { "execution":{"mode":"immediate"}, "inputs":[ {"id":"target", "apiName":"targetId", "type":"reference", "target":"item", "required":true, "classification":"internal"}, {"id":"label", "type":"string", "required":true, "minimumLength":1, "maximumLength":80, "classification":"internal"}], - "plan":{"type":"function", "function":"update-item-plan", "inputs":["target","label"], + "plan":{"type":"transform", "transform":"update-item-plan", "inputs":["target","label"], "refusals":[{"code":"label-not-eligible", "label":"The label is not eligible."}], "writes":[{"id":"item", "target":{"fromInput":"target"}, "operation":"patch", "fields":["label"]}]}}}, "accessProfiles":{ diff --git a/crates/registry-coordinator/tests/support/decision_evaluation.rs b/crates/registry-coordinator/tests/support/decision_evaluation.rs index 0c8cbb1a55..5c32c9b7d2 100644 --- a/crates/registry-coordinator/tests/support/decision_evaluation.rs +++ b/crates/registry-coordinator/tests/support/decision_evaluation.rs @@ -7,7 +7,7 @@ const DECISION_WORKFLOW: &str = r#" apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: synthetic-decision, version: '1'} -functions: +transforms: decision-request: runtime: rhai source: functions.rhai @@ -26,7 +26,7 @@ workflow: evaluate: type: call operation: evaluate - input: {type: function, function: decision-request, inputs: {input: {type: input}}} + input: {type: transform, transform: decision-request, inputs: {input: {type: input}}} next: done done: type: finish @@ -250,9 +250,9 @@ async fn completed_decision_is_reused_after_restart_and_downstream_mapping_failu let mut h = decision_harness().await; if broken_wait { let mut document = authored_workflow_value(DECISION_WORKFLOW); - document["functions"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); + document["transforms"]["broken-wait"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"broken_wait","inputs":{"input":{"type":"object"}},"output":{}}); document["workflow"]["steps"]["evaluate"]["next"] = json!("later"); - document["workflow"]["steps"]["later"] = json!({"type":"wait-until","waitUntil":{"type":"function","function":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"done"}); + document["workflow"]["steps"]["later"] = json!({"type":"wait-until","waitUntil":{"type":"transform","transform":"broken-wait","inputs":{"input":{"type":"input"}}},"next":"done"}); std::fs::write(h.project.path().join("workflow.yaml"), document.to_string()).unwrap(); std::fs::write( h.project.path().join("functions.rhai"), diff --git a/crates/registry-coordinator/tests/support/leased_wait_deadline.rs b/crates/registry-coordinator/tests/support/leased_wait_deadline.rs index 641d71e2b6..4d0b089bb9 100644 --- a/crates/registry-coordinator/tests/support/leased_wait_deadline.rs +++ b/crates/registry-coordinator/tests/support/leased_wait_deadline.rs @@ -15,7 +15,7 @@ kind: CoordinatorProject project: id: leased-timer version: v1 -functions: +transforms: timer: runtime: rhai source: functions.rhai @@ -35,11 +35,11 @@ workflow: steps: wait: type: wait-until - waitUntil: {type: function, function: timer, inputs: {input: {type: input}}} + waitUntil: {type: transform, transform: timer, inputs: {input: {type: input}}} next: choose choose: type: choose - choose: {type: function, function: choice, inputs: {input: {type: input}}} + choose: {type: transform, transform: choice, inputs: {input: {type: input}}} cases: {done: done} done: {type: finish, outcome: done} outcomes: @@ -175,7 +175,7 @@ async fn leased_finish_preserves_outcome_under_restore_review_and_after_retentio apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 kind: CoordinatorProject project: {id: leased-finish, version: v1} -functions: +transforms: keep: runtime: rhai source: functions.rhai @@ -190,7 +190,7 @@ workflow: done: type: finish outcome: done - output: {type: function, function: keep, inputs: {input: {type: input}}} + output: {type: transform, transform: keep, inputs: {input: {type: input}}} outcomes: done: {type: object} "#, diff --git a/crates/registry-coordinator/tests/support/mod.rs b/crates/registry-coordinator/tests/support/mod.rs index bcbf639a78..9a60cbf788 100644 --- a/crates/registry-coordinator/tests/support/mod.rs +++ b/crates/registry-coordinator/tests/support/mod.rs @@ -80,9 +80,7 @@ pub fn config( event_sources: BTreeMap::new(), deployment: None, secret_providers: SecretProvidersConfig { - file: Some(FileSecretProviderConfig { - root: root.to_path_buf(), - }), + file: Some(FileSecretProviderConfig::new(root.to_path_buf())), environment: Some(EnvironmentSecretProviderConfig {}), }, database: registry_platform_config::DatabaseConfig { diff --git a/crates/registry-coordinator/tests/support/restore_pending.rs b/crates/registry-coordinator/tests/support/restore_pending.rs index a4423a1f36..61680764a0 100644 --- a/crates/registry-coordinator/tests/support/restore_pending.rs +++ b/crates/registry-coordinator/tests/support/restore_pending.rs @@ -32,12 +32,12 @@ async fn pending_work(kind: &str, at: chrono::DateTime) -> (Harness, Uuid, .remove("read"); let operation = "submit-message"; document["workflow"]["steps"]["message"]["operation"] = json!(operation); - document["workflow"]["steps"]["message"]["input"] = json!({"type":"function","function":"pending-command","inputs":{"input":{"type":"input"}}}); + document["workflow"]["steps"]["message"]["input"] = json!({"type":"transform","transform":"pending-command","inputs":{"input":{"type":"input"}}}); if kind == "appointment" { document["operations"][operation] = json!({"uses":"scheduling.create-appointment/v1","connection":"messages"}); } - document["functions"]["pending-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pending_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":operation}}); + document["transforms"]["pending-command"] = json!({"runtime":"rhai","source":"functions.rhai","entrypoint":"pending_command","inputs":{"input":{"type":"object"}},"output":{"operationInput":operation}}); let functions = h.project.path().join("functions.rhai"); let source = std::fs::read_to_string(&functions).unwrap(); std::fs::write( diff --git a/crates/registry-coordinator/tests/support/snapshot_boundary.rs b/crates/registry-coordinator/tests/support/snapshot_boundary.rs index 740cfa8786..f936001652 100644 --- a/crates/registry-coordinator/tests/support/snapshot_boundary.rs +++ b/crates/registry-coordinator/tests/support/snapshot_boundary.rs @@ -15,11 +15,11 @@ pub fn project_at_snapshot_size(path: &Path, size: usize) { let mut workflow = json!({ "apiVersion": "id.registrystack.org/formats/coordinator/project/v1alpha1", "kind": "CoordinatorProject", "project": {"id": "snapshot-boundary", "version": "1"}, - "functions":{"branch":{"runtime":"rhai","source":"functions.rhai","entrypoint":"branch","inputs":{"input":{"type":"null"}},"output":{"enum":["one","two","three"]}}}, + "transforms":{"branch":{"runtime":"rhai","source":"functions.rhai","entrypoint":"branch","inputs":{"input":{"type":"null"}},"output":{"enum":["one","two","three"]}}}, "workflow":{ "input": schema, "deadlineSeconds": 3600, "start": "select", "steps": { - "select": {"type": "choose", "choose": {"type": "function", "function": "branch", "inputs": {"input":{"type":"input"}}}, + "select": {"type": "choose", "choose": {"type": "transform", "transform": "branch", "inputs": {"input":{"type":"input"}}}, "cases": {"one": "first", "two": "second", "three": "third"}}, "first": {"type": "finish", "outcome": "one"}, "second": {"type": "finish", "outcome": "two"}, "third": {"type": "finish", "outcome": "three"} diff --git a/crates/registry-coordinator/tests/wait_for_authoring.rs b/crates/registry-coordinator/tests/wait_for_authoring.rs index 785a4c5164..67928a7ea1 100644 --- a/crates/registry-coordinator/tests/wait_for_authoring.rs +++ b/crates/registry-coordinator/tests/wait_for_authoring.rs @@ -325,7 +325,7 @@ fn a_review_cancel_built_by_a_function_is_refused() { ), ( " input:\n type: fields\n fields:\n request: {type: step, step: submit-review}\n reason: {type: literal, value: \"No decision within fourteen days.\"}\n", - " input: {type: function, function: withdrawal, inputs: {request: {type: step, step: submit-review}}}\n", + " input: {type: transform, transform: withdrawal, inputs: {request: {type: step, step: submit-review}}}\n", ), ], ); diff --git a/crates/registry-discoveryctl/src/build.rs b/crates/registry-discoveryctl/src/build.rs index a0c6320cc5..b528cb7361 100644 --- a/crates/registry-discoveryctl/src/build.rs +++ b/crates/registry-discoveryctl/src/build.rs @@ -14,10 +14,11 @@ use registry_platform_config::{ write_package, DeclaredPosture, PackageError, PackageLimits, Posture, PostureReport, VerifiedPackage, }; +use registry_platform_httputil::select::{select_destination, validate_selected_fetch}; use registry_platform_httputil::{ read_bounded, validate_response_headers, FetchUrlPolicy, PeerPolicy, ResponseHeaderError, }; -use reqwest::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE}; +use reqwest::header::{HeaderValue, ACCEPT, CONTENT_ENCODING, CONTENT_TYPE}; use sha2::{Digest as _, Sha256}; use thiserror::Error; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; @@ -200,17 +201,31 @@ async fn fetch_origins( for approved in project.origins.iter().filter(|origin| origin.enabled) { let url = approved.catalog_url.to_url(); - let validated = policy - .validate_dns_pinned_for_immediate_fetch_with_timeout(&url, dns_timeout) - .await - .map_err(|_| BuildError::Fetch)?; - let response = validated - .immediate_get_with_timeout(fetch_timeout) - .map_err(|_| BuildError::Fetch)? - .header(ACCEPT, registry_discovery_profile::MEDIA_TYPE) - .send() - .await - .map_err(|_| BuildError::Fetch)?; + // Named hosts and HTTPS keep their existing DNS admission policy. + let response = if url.scheme() == "http" + && matches!(url.host_str(), Some("127.0.0.1" | "[::1]")) + { + let selected = select_destination(&url, None, &[]).map_err(|_| BuildError::Fetch)?; + validate_selected_fetch(&selected) + .map_err(|_| BuildError::Fetch)? + .get( + &HeaderValue::from_static(registry_discovery_profile::MEDIA_TYPE), + fetch_timeout, + ) + .await + .map_err(|_| BuildError::Fetch)? + } else { + policy + .validate_dns_pinned_for_immediate_fetch_with_timeout(&url, dns_timeout) + .await + .map_err(|_| BuildError::Fetch)? + .immediate_get_with_timeout(fetch_timeout) + .map_err(|_| BuildError::Fetch)? + .header(ACCEPT, registry_discovery_profile::MEDIA_TYPE) + .send() + .await + .map_err(|_| BuildError::Fetch)? + }; validate_response_headers(response.headers(), peer_policy).map_err( |error| match error { ResponseHeaderError::DevelopmentPeer => BuildError::DevelopmentPeer, diff --git a/crates/registry-documents/src/config.rs b/crates/registry-documents/src/config.rs index 9615637320..defeeba877 100644 --- a/crates/registry-documents/src/config.rs +++ b/crates/registry-documents/src/config.rs @@ -767,13 +767,15 @@ impl RuntimeConfig { network.declared_jwks_fetch_policy(), ), JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { - let document = secrets.resolve(document_ref).map_err(|error| { - RuntimeConfigError::OidcJwksSecret(describe_secret_failure( - &document_field, - document_ref, - &error, - )) - })?; + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| { + RuntimeConfigError::OidcJwksSecret(describe_secret_failure( + &document_field, + document_ref, + &error, + )) + })?; let jwks = parse_static_key_set(&document_field, document.expose_secret())?; JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults()) } diff --git a/crates/registry-documents/src/store.rs b/crates/registry-documents/src/store.rs index d3f8081f7d..338df54c31 100644 --- a/crates/registry-documents/src/store.rs +++ b/crates/registry-documents/src/store.rs @@ -385,13 +385,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs index a5118bdacc..c95751348d 100644 --- a/crates/registry-documentsctl/src/provision.rs +++ b/crates/registry-documentsctl/src/provision.rs @@ -8,7 +8,7 @@ use std::path::Path; use registry_documents::config::{startup_report_with_posture, RuntimeConfig}; use registry_documents_core::DOCUMENTS_RUNTIME_KIND; -use registry_platform_config::describe_secret_failure; +use registry_platform_config::{describe_secret_failure, DatabaseMember, PostureReport}; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, }; @@ -70,17 +70,18 @@ pub(crate) fn load( "Correct secretProviders in the runtime file, then run provision again.", ) })?; - let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), describe_secret_failure(&format!("database.{member}"), reference, &error), - "Check the secret provider and that the secret exists, then run provision again.", + error.suggested_action(), ) }) }; - let url = |member: &str, reference: &str| { + let url = |member: DatabaseMember, reference: &str| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -93,13 +94,16 @@ pub(crate) fn load( ) }) }; - let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; - let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let migration_url = url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?; + let runtime_url = url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?; let ca_pem = config .database .ca_bundle_ref .as_deref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); Ok(ProvisionInput { @@ -108,5 +112,10 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(&config.database), + explicit_settings: config + .posture + .as_ref() + .map(PostureReport::explicit_setting_notices) + .unwrap_or_default(), }) } diff --git a/crates/registry-documentsctl/tests/provision_cli.rs b/crates/registry-documentsctl/tests/provision_cli.rs index 0d93017c62..8fd0345eef 100644 --- a/crates/registry-documentsctl/tests/provision_cli.rs +++ b/crates/registry-documentsctl/tests/provision_cli.rs @@ -200,6 +200,32 @@ fn print_sql_writes_the_script_and_no_password() { } } +#[test] +fn print_sql_notices_the_compose_mount_policy_on_stderr() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let text = std::fs::read_to_string(&runtime).unwrap(); + let stated = text.replacen( + "secretProviders:\n file:\n", + "secretProviders:\n file:\n mountPolicy: compose-native\n", + 1, + ); + assert_ne!(stated, text, "the member is written"); + std::fs::write(&runtime, stated).unwrap(); + + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!( + stderr.contains( + "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy." + ), + "{stderr}" + ); + assert!(!stdout.contains("compose-native"), "{stdout}"); +} + #[test] fn print_sql_as_json_reports_nothing_executed() { let directory = scratch(); diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 95504951db..0f04400cba 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -26,9 +26,10 @@ use registry_platform_config::{ SecretProvidersConfig, SecretReference, DEFAULT_STAND_IN, }; use registry_platform_httputil::client::{ - is_loopback_host, valid_resource_uri, valid_scope_token, MAXIMUM_REQUESTED_SCOPES, - MAXIMUM_REQUESTED_SCOPE_BYTES, MAXIMUM_SCOPE_PARAMETER_BYTES, + valid_resource_uri, valid_scope_token, MAXIMUM_REQUESTED_SCOPES, MAXIMUM_REQUESTED_SCOPE_BYTES, + MAXIMUM_SCOPE_PARAMETER_BYTES, }; +use registry_platform_httputil::select::{select_credential_destination, select_destination}; use registry_platform_yaml::{ shape_union, BoundedU32, BoundedU64, Diagnostic, ExternalId, Invalid, Report, Severity, UniqueList, Url, @@ -708,7 +709,14 @@ pub struct DeliveryDocument { /// endpoint exists. #[serde(default)] pub metrics_listener: Option, - /// The secret providers `tokenClient.privateKeyRef` may name. + /// The secret providers `tokenClient.privateKeyRef` may name. The file provider takes no + /// `mountPolicy`: these keys keep the strict file rule. + // The schema publishes the shared strict block; the reader keeps the + // runtime block so it can refuse `mountPolicy` with a positioned finding. + #[cfg_attr( + feature = "schema", + schemars(with = "registry_platform_config::StrictSecretProvidersConfig") + )] pub secret_providers: SecretProvidersConfig, /// The required durable audit journal for offer attribution and delivery /// outcomes. `stdout` is available for a collector-managed deployment; @@ -1328,7 +1336,7 @@ impl DeliveryDocument { } for (pointer, origin) in self.called_origins() { url_query_or_fragment_findings(pointer, origin, findings); - https_origin_findings(pointer, origin, findings); + https_origin_findings(pointer, origin, OutboundOriginRole::Credential, findings); } for (id, entry) in self.offers.issuers.iter() { let prefix = format!("{OFFER_ISSUERS}/{}", id.as_str()); @@ -1336,7 +1344,12 @@ impl DeliveryDocument { let issuer_path = format!("{prefix}/issuer"); url_query_or_fragment_findings(&issuer_path, &provider.issuer, findings); if !provider.allow_insecure_http { - https_origin_findings(&issuer_path, &provider.issuer, findings); + https_origin_findings( + &issuer_path, + &provider.issuer, + OutboundOriginRole::OfferMetadata, + findings, + ); } let source_path = format!("{prefix}/jwksSource"); match &provider.jwks_source { @@ -1344,7 +1357,12 @@ impl DeliveryDocument { let pointer = format!("{source_path}/uri"); url_query_or_fragment_findings(&pointer, uri, findings); if !provider.allow_insecure_http { - https_origin_findings(&pointer, uri, findings); + https_origin_findings( + &pointer, + uri, + OutboundOriginRole::OfferMetadata, + findings, + ); } } _ => findings.push(Finding::error( @@ -1405,6 +1423,14 @@ impl DeliveryDocument { } fn secret_findings(&self, findings: &mut Vec) { + if self.secret_providers.compose_native_mounts() { + findings.push(Finding::error( + "evidence.oid4vci.secret-providers", + "/secretProviders/file/mountPolicy", + "the wallet delivery service keeps the Evidence Version 1 secret file rule, so it does not accept mountPolicy", + "Remove mountPolicy. Stage each secret file owned by the runtime user with mode 0400 or 0600, or owned by root with no bits outside 0640.", + )); + } if let Err(error) = self.secret_providers.check() { findings.push(match error.kind() { ConfigBlockErrorKind::RelativePath => Finding::error( @@ -1692,21 +1718,31 @@ fn normalized_credential_issuer(written: &str) -> &str { written.trim_end_matches('/') } -/// Require HTTPS for a called origin outside loopback. +enum OutboundOriginRole { + Credential, + OfferMetadata, +} + +/// Require protected transport for a called origin or a strict offer key source. /// The reader refuses URLs without a host or with embedded credentials. -fn https_origin_findings(pointer: &str, origin: &Url, findings: &mut Vec) { - if !origin.is_https() - && !origin - .to_url() - .host() - .as_ref() - .is_some_and(is_loopback_host) - { - let action = if pointer.starts_with(OFFER_ISSUERS) { - "Write an HTTPS or loopback HTTP URL, or use allowInsecureHttp: true in the issuer entry with development for HTTP beyond loopback." - } else { - "Write an HTTPS or loopback HTTP URL." - }; +fn https_origin_findings( + pointer: &str, + origin: &Url, + role: OutboundOriginRole, + findings: &mut Vec, +) { + let url = origin.to_url(); + let (selected, action) = match role { + OutboundOriginRole::Credential => ( + select_credential_destination(&url, None, &[]), + "Write an HTTPS or loopback HTTP URL.", + ), + OutboundOriginRole::OfferMetadata => ( + select_destination(&url, None, &[]), + "Write an HTTPS or loopback HTTP URL, or use allowInsecureHttp: true in the issuer entry with development for HTTP beyond loopback.", + ), + }; + if selected.is_err() { findings.push(Finding::error( HTTPS_REQUIRED, pointer, @@ -2328,10 +2364,34 @@ store: #[test] fn posture_strict_called_origins_allow_loopback_http_only() { - let loopback = VALID.replace("https://evidence.example.org", "http://127.0.0.1:8080"); - assert!(load_from(&loopback).is_ok()); - let private = VALID.replace("https://evidence.example.org", "http://10.0.0.5"); - assert_refused_with(&private, HTTPS_REQUIRED); + for (original, path, suffix) in [ + ("https://evidence.example.org", "/evidence/baseUrl", ""), + ( + "https://mint.example.org/token", + "/tokenClient/tokenEndpoint", + "/token", + ), + ] { + for host in ["127.0.0.1", "[::1]", "localhost"] { + let text = VALID.replace(original, &format!("http://{host}:8080{suffix}")); + assert!(load_from(&text).is_ok(), "{path} at {host}"); + assert!(!check(&text, false) + .diagnostics + .iter() + .any(|d| d.severity == Severity::Error)); + } + for host in ["10.0.0.5", "receiver.localhost"] { + let text = VALID.replace(original, &format!("http://{host}:8080{suffix}")); + let error = load_from(&text).expect_err("non-loopback plaintext is refused"); + let offline = check(&text, false); + for diagnostics in [error.diagnostics(), offline.diagnostics.as_slice()] { + assert_eq!(diagnostics.len(), 1, "{path} at {host}"); + assert_eq!(diagnostics[0].code, HTTPS_REQUIRED); + assert_eq!(diagnostics[0].path, path); + assert!(!diagnostics[0].message.contains(host)); + } + } + } } #[test] diff --git a/crates/registry-evidence-oid4vci/src/main.rs b/crates/registry-evidence-oid4vci/src/main.rs index 5601e618da..23af19a3da 100644 --- a/crates/registry-evidence-oid4vci/src/main.rs +++ b/crates/registry-evidence-oid4vci/src/main.rs @@ -329,13 +329,7 @@ fn check( OutputFormat::Human => { let mut output = std::io::stderr().lock(); for found in &explicit_settings { - writeln!( - output, - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - )?; + writeln!(output, "{}", found.notice())?; } write!(output, "{}", report.render_human())?; } diff --git a/crates/registry-evidence-oid4vci/src/schema.rs b/crates/registry-evidence-oid4vci/src/schema.rs index c38d313e1b..b2c5446c35 100644 --- a/crates/registry-evidence-oid4vci/src/schema.rs +++ b/crates/registry-evidence-oid4vci/src/schema.rs @@ -156,13 +156,20 @@ mod tests { "clientAssertionAudience": "https://mint.example.org" }, "offers": { - "issuer": "https://mint.example.org", - "jwksUri": "https://mint.example.org/.well-known/jwks.json", - "audiences": ["https://wallet.example.org"], - "algorithms": ["EdDSA"], - "allowedClients": ["adopter-front-end"], - "requiredScopes": ["oid4vci:offer"], - "maximumTokenLifetimeSeconds": 900 + "issuers": { + "primary": { + "issuer": "https://mint.example.org", + "jwksSource": { + "type": "uri", + "uri": "https://mint.example.org/.well-known/jwks.json" + }, + "audience": "https://wallet.example.org", + "algorithms": ["EdDSA"], + "allowedClients": ["adopter-front-end"], + "maximumTokenLifetimeSeconds": 900 + } + }, + "requiredScopes": ["oid4vci:offer"] }, "store": { "maximumOffers": 4096, @@ -207,6 +214,11 @@ mod tests { !schema.is_valid(&document) }; assert!(refused(&|document| document["version"] = Value::from(1))); + // The Evidence key rule refuses the Compose mount policy, so the + // published contract does not offer it. + assert!(refused(&|document| { + document["secretProviders"]["file"]["mountPolicy"] = Value::from("compose-native") + })); assert!(refused(&|document| { document["tokenClient"]["privateKeyFile"] = Value::from("client.jwk") })); @@ -218,7 +230,7 @@ mod tests { document["tokenClient"]["privateKeyRef"] = Value::from("/run/secrets/client.jwk") })); assert!(refused(&|document| { - document["offers"]["allowedClients"] = serde_json::json!([]) + document["offers"]["issuers"]["primary"]["allowedClients"] = serde_json::json!([]) })); assert!(refused(&|document| { document["offers"]["requiredScopes"] = Value::from("anything") @@ -230,13 +242,13 @@ mod tests { .remove("requiredScopes"); })); assert!(refused(&|document| { - document["offers"]["audiences"] = serde_json::json!(["a", "a"]) + document["offers"]["issuers"] = serde_json::json!({}) })); assert!(refused(&|document| { document["store"]["maximumOffers"] = Value::from(255) })); assert!(!refused(&|document| { - document["offers"]["allowedClients"] = Value::from("unrestricted") + document["offers"]["issuers"]["primary"]["allowedClients"] = Value::from("unrestricted") })); } diff --git a/crates/registry-evidence-oid4vci/tests/check_command.rs b/crates/registry-evidence-oid4vci/tests/check_command.rs index dc2feaa835..4a90e8985f 100644 --- a/crates/registry-evidence-oid4vci/tests/check_command.rs +++ b/crates/registry-evidence-oid4vci/tests/check_command.rs @@ -319,3 +319,28 @@ fn writable_secret_root_passes_offline_check_and_is_refused_by_serve_and_inspect ); } } + +#[test] +fn compose_native_secret_mounts_are_refused_under_the_version_1_key_rule() { + let text = example().replace( + " root: /run/secrets/evidence-oid4vci\n", + " root: /run/secrets/evidence-oid4vci\n mountPolicy: compose-native\n", + ); + assert_ne!(text, example(), "the member is written"); + let (_root, path) = write(&text); + + let output = check(&path, &["--format", "json"]); + assert_eq!(output.status.code(), Some(1)); + let document = json(&output); + assert!( + document["diagnostics"] + .as_array() + .unwrap() + .iter() + .any( + |diagnostic| diagnostic["code"] == "evidence.oid4vci.secret-providers" + && diagnostic["path"] == "/secretProviders/file/mountPolicy" + ), + "{document}" + ); +} diff --git a/crates/registry-evidence-oid4vp/src/auth.rs b/crates/registry-evidence-oid4vp/src/auth.rs index 8625098d2f..d58f669a2d 100644 --- a/crates/registry-evidence-oid4vp/src/auth.rs +++ b/crates/registry-evidence-oid4vp/src/auth.rs @@ -221,7 +221,7 @@ impl TokenAuthenticator { } JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let document = secrets - .resolve(document_ref) + .resolve_public_document(document_ref) .map_err(|_| AuthSetupError::StaticKeySecret)?; let jwks = parse_static_jwks(document.expose_secret()) .map_err(|error| AuthSetupError::StaticKeySet(error.to_string()))?; diff --git a/crates/registry-evidence-oid4vp/src/config.rs b/crates/registry-evidence-oid4vp/src/config.rs index 1d108f8ee9..fcd7006433 100644 --- a/crates/registry-evidence-oid4vp/src/config.rs +++ b/crates/registry-evidence-oid4vp/src/config.rs @@ -684,7 +684,14 @@ pub struct VerifierDocument { /// endpoint exists. #[serde(default)] pub metrics_listener: Option, - /// The secret providers the `*Ref` members may name. + /// The secret providers the `*Ref` members may name. The file provider takes no + /// `mountPolicy`: these keys keep the strict file rule. + // The schema publishes the shared strict block; the reader keeps the + // runtime block so it can refuse `mountPolicy` with a positioned finding. + #[cfg_attr( + feature = "schema", + schemars(with = "registry_platform_config::StrictSecretProvidersConfig") + )] pub secret_providers: SecretProvidersConfig, /// The required durable audit journal. pub audit: AuditDocument, @@ -1387,6 +1394,14 @@ impl VerifierDocument { } fn secret_findings(&self, findings: &mut Vec) { + if self.secret_providers.compose_native_mounts() { + findings.push(Finding::error( + "evidence.oid4vp.secret-providers", + "/secretProviders/file/mountPolicy", + "the wallet presentation service keeps the Evidence Version 1 secret file rule, so it does not accept mountPolicy", + "Remove mountPolicy. Stage each secret file owned by the runtime user with mode 0400 or 0600, or owned by root with no bits outside 0640.", + )); + } if let Err(error) = self.secret_providers.check() { findings.push(match error.kind() { ConfigBlockErrorKind::RelativePath => Finding::error( diff --git a/crates/registry-evidence-oid4vp/src/main.rs b/crates/registry-evidence-oid4vp/src/main.rs index 0f576013ce..8bae4229bf 100644 --- a/crates/registry-evidence-oid4vp/src/main.rs +++ b/crates/registry-evidence-oid4vp/src/main.rs @@ -293,13 +293,7 @@ fn check( OutputFormat::Human => { let mut output = std::io::stderr().lock(); for found in &explicit_settings { - writeln!( - output, - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - )?; + writeln!(output, "{}", found.notice())?; } write!(output, "{}", report.render_human())?; } diff --git a/crates/registry-evidence-oid4vp/src/schema.rs b/crates/registry-evidence-oid4vp/src/schema.rs index 0e7a29af3d..c53d5cbf00 100644 --- a/crates/registry-evidence-oid4vp/src/schema.rs +++ b/crates/registry-evidence-oid4vp/src/schema.rs @@ -213,6 +213,11 @@ mod tests { !schema.is_valid(&document) }; assert!(refused(&|document| document["version"] = Value::from(1))); + // The Evidence key rule refuses the Compose mount policy, so the + // published contract does not offer it. + assert!(refused(&|document| { + document["secretProviders"]["file"]["mountPolicy"] = Value::from("compose-native") + })); assert!(refused(&|document| document["sessions"] = Value::Null)); assert!(refused( &|document| document["policies"] = serde_json::json!([]) diff --git a/crates/registry-evidence-oid4vp/tests/check_command.rs b/crates/registry-evidence-oid4vp/tests/check_command.rs index 1a2141f4a2..33dbbeadaf 100644 --- a/crates/registry-evidence-oid4vp/tests/check_command.rs +++ b/crates/registry-evidence-oid4vp/tests/check_command.rs @@ -85,7 +85,7 @@ fn the_committed_example_passes_in_both_formats() { assert!(output.stdout.is_empty()); assert_eq!( String::from_utf8(output.stderr).unwrap(), - "Explicit production setting platform.posture.unrestricted-clients at /applicantTokens/issuers/primary/allowedClients. admits a token from every client this issuer signs for.\n0 errors, 0 warnings in 1 file\n" + "Explicit production setting platform.posture.unrestricted-clients at /applicantTokens/issuers/primary/allowedClients. Admits a token from every client this issuer signs for.\n0 errors, 0 warnings in 1 file\n" ); } @@ -204,3 +204,28 @@ fn an_explicitly_empty_claims_list_is_refused() { assert_eq!(output.status.code(), Some(1), "{output:?}"); assert_eq!(json(&output)["ok"], false); } + +#[test] +fn compose_native_secret_mounts_are_refused_under_the_version_1_key_rule() { + let text = example().replace( + " root: /run/secrets/evidence-oid4vp\n", + " root: /run/secrets/evidence-oid4vp\n mountPolicy: compose-native\n", + ); + assert_ne!(text, example(), "the member is written"); + let (_root, path) = write(&text); + + let output = check(&path, &["--format", "json"]); + assert_eq!(output.status.code(), Some(1)); + let document = json(&output); + assert!( + document["diagnostics"] + .as_array() + .unwrap() + .iter() + .any( + |diagnostic| diagnostic["code"] == "evidence.oid4vp.secret-providers" + && diagnostic["path"] == "/secretProviders/file/mountPolicy" + ), + "{document}" + ); +} diff --git a/crates/registry-evidence/src/config.rs b/crates/registry-evidence/src/config.rs index 9f7de935b4..976ce4c2e7 100644 --- a/crates/registry-evidence/src/config.rs +++ b/crates/registry-evidence/src/config.rs @@ -2496,6 +2496,9 @@ pub const RUNTIME_PACKAGE_CODE: &str = "evidence.runtime.invalid-package"; pub const RUNTIME_LISTENER_CODE: &str = "evidence.runtime.invalid-listener"; pub const RUNTIME_METRICS_LISTENER_CODE: &str = "evidence.runtime.invalid-metrics-listener"; pub const RUNTIME_SECRET_PROVIDERS_CODE: &str = "evidence.runtime.invalid-secret-providers"; +/// The remedy when an Evidence runtime states `mountPolicy`: its frozen +/// Version 1 rule never lets other users read a key file. +pub const COMPOSE_NATIVE_REFUSED_ACTION: &str = "Remove mountPolicy. Stage each secret file owned by the runtime user with mode 0400 or 0600, or owned by root with no bits outside 0640."; pub const RUNTIME_SIGNER_CODE: &str = "evidence.runtime.invalid-signer"; pub const RUNTIME_AUDIT_CODE: &str = "evidence.runtime.invalid-audit"; pub const RUNTIME_OUTBOUND_TLS_CODE: &str = "evidence.runtime.invalid-outbound-tls"; @@ -2842,6 +2845,17 @@ impl RuntimeConfig { )); } } + if self.secret_providers.compose_native_mounts() { + findings.push(RuntimeFinding::at_value( + RUNTIME_SECRET_PROVIDERS_CODE, + "/secretProviders/file/mountPolicy", + ConfigError::InvalidField( + "Evidence keeps the Version 1 secret file rule, so it does not accept mountPolicy", + "secretProviders.file.mountPolicy", + ), + COMPOSE_NATIVE_REFUSED_ACTION, + )); + } self.signer .findings(&self.secret_providers, providers_enabled, &mut findings); self.audit.findings(&mut findings); @@ -10926,6 +10940,40 @@ outboundTls: ) } + #[test] + fn a_compose_native_secret_mount_is_refused_under_the_version_1_key_rule() { + let findings = |text: &str| { + RuntimeConfig::decode_yaml_with( + text.as_bytes(), + DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }, + |_| None, + ) + .expect("the shared reader accepts the member") + .config + .findings() + }; + let stated = LOADER_RUNTIME_DOCUMENT.replace( + "file: {root: /run/secrets/registry-evidence}", + "file: {root: /run/secrets/registry-evidence, mountPolicy: compose-native}", + ); + assert_ne!(stated, LOADER_RUNTIME_DOCUMENT, "the member is written"); + let refused = findings(&stated); + assert!( + refused + .iter() + .any(|finding| finding.code == RUNTIME_SECRET_PROVIDERS_CODE + && finding.pointer == "/secretProviders/file/mountPolicy" + && finding.action == COMPOSE_NATIVE_REFUSED_ACTION), + "{refused:?}" + ); + assert!(!findings(LOADER_RUNTIME_DOCUMENT) + .iter() + .any(|finding| finding.pointer == "/secretProviders/file/mountPolicy")); + } + #[test] fn a_runtime_file_with_the_retired_api_version_is_refused_with_the_replacement_named() { let retired = LOADER_RUNTIME_DOCUMENT.replace( diff --git a/crates/registry-evidence/src/main.rs b/crates/registry-evidence/src/main.rs index b990c00060..1c8c0ad079 100644 --- a/crates/registry-evidence/src/main.rs +++ b/crates/registry-evidence/src/main.rs @@ -1133,12 +1133,7 @@ async fn run_check(request: CheckRequest) -> ExitCode { } if !check.is_unavailable() { for found in check.explicit_settings() { - eprintln!( - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - ); + eprintln!("{}", found.notice()); } } eprint!("{}", report.render_human()); diff --git a/crates/registry-evidencectl/Cargo.toml b/crates/registry-evidencectl/Cargo.toml index b4691acb4c..73e65ca45b 100644 --- a/crates/registry-evidencectl/Cargo.toml +++ b/crates/registry-evidencectl/Cargo.toml @@ -42,10 +42,12 @@ registry-cli-reference.workspace = true registry-platform-crypto.workspace = true registry-platform-httpsec = { workspace = true, features = ["server"] } registry-platform-loopback.workspace = true +registry-platform-provision = { workspace = true, features = ["cli"] } registry-platform-yaml.workspace = true registry-rstack-dev.workspace = true registry-thunderid-tooling.workspace = true p256.workspace = true +percent-encoding = "2" # `jwk from-pem` reads a PEM SubjectPublicKeyInfo or PKCS #1 public key. pkcs1.workspace = true pkcs8 = { workspace = true, features = ["pem"] } @@ -66,7 +68,8 @@ schemars = { workspace = true, optional = true } [features] # The generator for the committed schemas of the documents this crate owns. -schema = ["dep:schemars", "registry-evidence-authoring/schema"] +schema = ["dep:schemars", "registry-evidence-authoring/schema", "registry-platform-config/schema"] +postgres-test = [] [[example]] name = "authoring-schema" @@ -77,4 +80,5 @@ registry-adapter-engine.workspace = true registry-evidence.workspace = true registry-evidence-authoring.workspace = true registry-platform-crypto = { workspace = true, features = ["test-support"] } +registry-platform-provision = { workspace = true, features = ["test-support"] } tower.workspace = true diff --git a/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json new file mode 100644 index 0000000000..ee545f8823 --- /dev/null +++ b/crates/registry-evidencectl/schemas/authoring/store-provision.schema.json @@ -0,0 +1,160 @@ +{ + "$defs": { + "DatabaseConfig": { + "additionalProperties": false, + "description": "The PostgreSQL connection a stateful runtime uses. Both URLs are secret\nreferences and may name the same secret.", + "properties": { + "caBundleRef": { + "$ref": "#/$defs/SecretReference", + "description": "Secret reference to a PEM root certificate the connection trusts.\nAbsent, the connection trusts the platform's root certificates." + }, + "migrationUrlRef": { + "$ref": "#/$defs/SecretReference", + "description": "Secret reference to the migration connection URL." + }, + "runtimeUrlRef": { + "$ref": "#/$defs/SecretReference", + "description": "Secret reference to the least-privileged runtime connection URL." + }, + "testOnlyPlaintext": { + "default": false, + "description": "Allow a plaintext connection. Refused outside test builds.", + "type": "boolean" + }, + "transport": { + "$ref": "#/$defs/DatabaseTransport", + "description": "How the connection is protected. Absent means `verified-tls`. A\nplaintext transport must match the database hosts, and cannot be\nwritten beside `testOnlyPlaintext`.", + "x-registry-development-only": [ + "platform.posture.database-private-plaintext" + ] + } + }, + "required": [ + "runtimeUrlRef", + "migrationUrlRef" + ], + "type": "object" + }, + "DatabaseTransport": { + "description": "How a PostgreSQL connection is protected.", + "oneOf": [ + { + "const": "verified-tls", + "description": "TLS with verification. `caBundleRef` is optional.", + "type": "string" + }, + { + "const": "loopback-plaintext", + "description": "No TLS. Every host must be a Unix socket, a numeric loopback address\nor `localhost`.", + "type": "string" + }, + { + "const": "private-network-plaintext", + "description": "No TLS, in development only. Every host must also be loopback, a\nsocket, a private IPv4 address (RFC 1918), an IPv6 unique local\naddress (`fc00::/7`), or a name that resolves only to such addresses.", + "type": "string" + } + ] + }, + "EnvironmentSecretProviderConfig": { + "additionalProperties": false, + "description": "The environment secret provider. It takes no settings.", + "type": "object" + }, + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "Store": { + "enum": [ + "status", + "oid4vci" + ], + "type": "string" + }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/evidence/store-provision/v1alpha1", + "type": "string" + }, + "database": { + "$ref": "#/$defs/DatabaseConfig" + }, + "kind": { + "const": "EvidenceStoreProvisionConfig", + "type": "string" + }, + "secretProviders": { + "$ref": "#/$defs/StrictSecretProvidersConfig" + }, + "store": { + "$ref": "#/$defs/Store", + "description": "The Evidence PostgreSQL store this database is reserved for." + } + }, + "required": [ + "apiVersion", + "kind", + "store", + "database", + "secretProviders" + ], + "title": "Evidence store provisioning config", + "type": "object" +} diff --git a/crates/registry-evidencectl/src/check.rs b/crates/registry-evidencectl/src/check.rs index 0b86b42eef..3343f72b6e 100644 --- a/crates/registry-evidencectl/src/check.rs +++ b/crates/registry-evidencectl/src/check.rs @@ -562,13 +562,7 @@ pub(crate) fn render_human_with_settings( } } for found in explicit_settings { - writeln!( - out, - "Explicit production setting {} at {}. {}.", - found.code, - found.pointer.as_deref().unwrap_or_default(), - found.summary - )?; + writeln!(out, "{}", found.notice())?; } write!(out, "{}", diagnostics.render_human()) } diff --git a/crates/registry-evidencectl/src/doctor.rs b/crates/registry-evidencectl/src/doctor.rs index e3d8ac1f16..53391a11b9 100644 --- a/crates/registry-evidencectl/src/doctor.rs +++ b/crates/registry-evidencectl/src/doctor.rs @@ -302,6 +302,24 @@ fn check_secrets( let mut root_run = CheckRun::new("secret root", project); root_run.read_declaration(); + // Evidence keeps the Version 1 secret file rule and refuses the Compose + // mount policy, so doctor refuses it too. Every other file then gets the + // strict verdict the runtime gives below. + if runtime + .get("secretProviders") + .and_then(|providers| providers.get("file")) + .and_then(|file| file.get("mountPolicy")) + .is_some() + { + root_run.refuse( + runtime_path, + "/secretProviders/file/mountPolicy (evidence.runtime.invalid-secret-providers): \ + Evidence keeps the Version 1 secret file rule, so it does not accept mountPolicy. \ + Remove mountPolicy. Stage each secret file owned by the runtime user with mode \ + 0400 or 0600, or owned by root with no bits outside 0640." + .to_owned(), + ); + } if let Err(error) = registry_platform_config::validate_secret_root(&root) { let diagnostic = error.diagnostic(); root_run.refuse( diff --git a/crates/registry-evidencectl/src/lib.rs b/crates/registry-evidencectl/src/lib.rs index ad4fd9d7f4..93724e8f3f 100644 --- a/crates/registry-evidencectl/src/lib.rs +++ b/crates/registry-evidencectl/src/lib.rs @@ -43,6 +43,7 @@ mod scaffold; mod source_cli; mod source_import; mod source_mock; +mod store_provision; mod suggest; mod target; mod tooling; @@ -90,6 +91,8 @@ enum Command { Types(normalized::TypesArgs), /// Check a normalized project and, when selected, deployment closure, or one tooling file, offline. Check(CheckArgs), + /// Create split PostgreSQL roles and an empty database for a held Evidence store. + Provision(registry_platform_provision::ProvisionArgs), /// Explain the authored inventory and optional target-owned governance. Explain(ExplainArgs), /// Run the project's synthetic Evidence fixtures. @@ -181,7 +184,7 @@ enum CliFormat { ArgGroup::new("checked") .required(true) .multiple(false) - .args(["project", "file"]) + .args(["project", "file", "store_provision_config"]) ))] struct CheckArgs { #[arg( @@ -190,13 +193,19 @@ struct CheckArgs { help = "Declared posture: development or production. Unset means production." )] posture: Option, - /// Editable Evidence project directory. Required unless --file is given. + /// Editable Evidence project directory. Required unless --file or --store-provision-config is given. project: Option, /// Check one tooling file on its own, offline: a client profile, reviewed /// contracts, a ThunderID task connection or session file, a source-import /// baseline or journal, a source resolution file, or a source export manifest. #[arg(long, conflicts_with_all = ["project", "target", "production"])] file: Option, + /// Check a store provisioning file offline without resolving secrets. + #[arg(long, value_name = "FILE", conflicts_with_all = ["target", "production"])] + store_provision_config: Option, + /// Resolve text substitutions in the provisioning file from the environment. + #[arg(long, requires = "store_provision_config")] + environment: bool, /// Explicit deployment target whose governance and runtime structure are checked. #[arg(long)] target: Option, @@ -365,16 +374,22 @@ fn cli_command() -> clap::Command { let command = HUMAN_ONLY_COMMANDS .iter() .fold(Cli::command(), |command, path| narrow_format(command, path)); - command.mut_subcommand("runtime", |subcommand| { - subcommand.arg( - clap::Arg::new("output_format") - .long("format") - .value_name("FORMAT") - .default_value("human") - .hide(true) - .value_parser(clap::builder::EnumValueParser::::new()), - ) - }) + command + .mut_subcommand("provision", |subcommand| { + subcommand.mut_arg("runtime_config", |argument| { + argument.help("Runtime configuration file for Evidence store provisioning") + }) + }) + .mut_subcommand("runtime", |subcommand| { + subcommand.arg( + clap::Arg::new("output_format") + .long("format") + .value_name("FORMAT") + .default_value("human") + .hide(true) + .value_parser(clap::builder::EnumValueParser::::new()), + ) + }) } fn narrow_format(command: clap::Command, path: &[&str]) -> clap::Command { @@ -586,6 +601,7 @@ fn run_entry() -> ExitCode { } let posture_flag = match &cli.command { Command::Check(args) => Some(args.posture.as_deref()), + Command::Provision(args) => Some(args.posture.as_deref()), Command::Package(args) => Some(args.posture.as_deref()), Command::Test(args) => Some(args.posture.as_deref()), Command::Fixtures(fixtures::FixturesCommand::Run(args)) => Some(args.posture.as_deref()), @@ -687,11 +703,24 @@ fn run_entry() -> ExitCode { ) } Command::Types(args) => normalized::generate_types(args, format), + Command::Provision(args) => Ok(store_provision::run(&args, format, posture)), Command::Check(CheckArgs { file: Some(file), deny_warnings, .. }) => Ok(file_check::run(&file, format, deny_warnings)), + Command::Check(CheckArgs { + store_provision_config: Some(file), + deny_warnings, + environment, + .. + }) => Ok(store_provision::check( + &file, + format, + deny_warnings, + environment, + posture, + )), Command::Check(args) => { let artifact = project_of(&args).display().to_string(); safe_command( @@ -1742,6 +1771,7 @@ mod tests { "target explain", "tooling editor", "oid4vci check", + "provision", ]; /// Protocol and artifact output, or a foreground service without a report. diff --git a/crates/registry-evidencectl/src/schema.rs b/crates/registry-evidencectl/src/schema.rs index d3cd7ba773..96bc78018a 100644 --- a/crates/registry-evidencectl/src/schema.rs +++ b/crates/registry-evidencectl/src/schema.rs @@ -14,6 +14,7 @@ use registry_evidence_authoring::schema::publish; use crate::source_import::{ resolution_schema, RESOLUTION_API_VERSION, RESOLUTION_KIND, RESOLUTION_SCHEMA_ID, }; +use crate::store_provision::{self, StoreProvisionDocument}; /// The schema for one local access client under `access/clients/`. pub const ACCESS_CLIENT_SCHEMA_FILE: &str = "access-client.schema.json"; @@ -23,6 +24,8 @@ pub const MOCK_PLAN_SCHEMA_FILE: &str = "mock-plan.schema.json"; /// The schema for one source import resolution file. pub const SOURCE_RESOLUTION_SCHEMA_FILE: &str = "source-resolution.schema.json"; +/// The schema for the operator-only database provisioning input. +pub const STORE_PROVISION_SCHEMA_FILE: &str = "store-provision.schema.json"; /// Every generated schema this crate owns, keyed by the filename it is /// committed under. @@ -59,6 +62,15 @@ pub fn documents() -> Result, serde_json::Error> (RESOLUTION_API_VERSION, RESOLUTION_KIND), )?, ), + ( + STORE_PROVISION_SCHEMA_FILE, + publish( + serde_json::to_value(schemars::schema_for!(StoreProvisionDocument))?, + "Evidence store provisioning config", + store_provision::SCHEMA_ID, + (store_provision::API_VERSION, store_provision::KIND), + )?, + ), ])) } @@ -70,6 +82,7 @@ mod tests { )] use super::{ documents, ACCESS_CLIENT_SCHEMA_FILE, MOCK_PLAN_SCHEMA_FILE, SOURCE_RESOLUTION_SCHEMA_FILE, + STORE_PROVISION_SCHEMA_FILE, }; fn compile(file: &str) -> jsonschema::JSONSchema { @@ -94,6 +107,7 @@ mod tests { ACCESS_CLIENT_SCHEMA_FILE, MOCK_PLAN_SCHEMA_FILE, SOURCE_RESOLUTION_SCHEMA_FILE, + STORE_PROVISION_SCHEMA_FILE, ] ); for (file, generated) in documents().expect("schemas generate") { @@ -107,6 +121,21 @@ mod tests { } } + #[test] + fn store_provision_schema_checks_the_example_and_its_envelope() { + let schema = compile(STORE_PROVISION_SCHEMA_FILE); + let mut example: serde_json::Value = serde_norway::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../products/evidence/examples/formats/store-provision.yaml" + ))) + .expect("the store provision example is YAML"); + assert!(schema.is_valid(&example)); + example["store"] = serde_json::json!("oid4vci"); + assert!(schema.is_valid(&example)); + example["apiVersion"] = serde_json::json!("wrong-version"); + assert!(!schema.is_valid(&example)); + } + #[test] fn an_access_client_with_an_unusable_issuer_is_turned_away() { let schema = compile(ACCESS_CLIENT_SCHEMA_FILE); diff --git a/crates/registry-evidencectl/src/store_provision.rs b/crates/registry-evidencectl/src/store_provision.rs new file mode 100644 index 0000000000..e9981cdd53 --- /dev/null +++ b/crates/registry-evidencectl/src/store_provision.rs @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Operator-only database provisioning for the two held PostgreSQL stores. + +use std::{path::Path, process::ExitCode}; + +use registry_platform_config::{ + describe_secret_failure, DatabaseConfig, DatabaseMember, DatabaseTransport, DeclaredPosture, + RuntimeConfigLoader, RuntimeEnvelope, StrictSecretProvidersConfig, DEFAULT_STAND_IN, +}; +use registry_platform_provision::{ + provision_transport, run_provision, ProductDatabase, ProvisionArgs, ProvisionInput, + SchemaLayout, +}; +use registry_platform_yaml::{Diagnostic, Report, Source}; +use serde::{Deserialize, Deserializer}; +use zeroize::Zeroizing; + +use crate::{report, OutputFormat}; + +pub(crate) const API_VERSION: &str = + "id.registrystack.org/formats/evidence/store-provision/v1alpha1"; +pub(crate) const KIND: &str = "EvidenceStoreProvisionConfig"; +const SPLIT_ROLES_REQUIRED: &str = "evidence.store-provision.split-roles-required"; +#[cfg(feature = "schema")] +pub(crate) const SCHEMA_ID: &str = + "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json"; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "schema", schemars(rename_all = "kebab-case"))] +enum Store { + Status, + Oid4vci, +} + +impl<'de> Deserialize<'de> for Store { + fn deserialize>(deserializer: D) -> Result { + let name = String::deserialize(deserializer)?; + match name.as_str() { + "status" => Ok(Self::Status), + "oid4vci" => Ok(Self::Oid4vci), + _ => Err(serde::de::Error::unknown_variant( + &name, + &["status", "oid4vci"], + )), + } + } +} + +impl Store { + fn product(&self) -> ProductDatabase { + ProductDatabase { + product: match self { + Self::Status => "evidence-status", + Self::Oid4vci => "evidence-oid4vci", + }, + // Both stores create their schema in their separate migration. + layout: SchemaLayout::CreatedByApply, + btree_gist: false, + spatial: None, + } + } +} + +#[derive(Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct StoreProvisionDocument { + #[cfg_attr(feature = "schema", schemars(skip))] + #[serde(rename = "apiVersion")] + _api_version: String, + #[cfg_attr(feature = "schema", schemars(skip))] + #[serde(rename = "kind")] + _kind: String, + /// The Evidence PostgreSQL store this database is reserved for. + store: Store, + database: DatabaseConfig, + secret_providers: StrictSecretProvidersConfig, +} + +fn loader(declared: DeclaredPosture) -> RuntimeConfigLoader { + RuntimeConfigLoader::new( + RuntimeEnvelope { + api_version: API_VERSION, + kind: KIND, + }, + declared, + ) + .require_trusted_ownership() +} + +fn diagnostics(config: &StoreProvisionDocument, defers: impl Fn(&str) -> bool) -> Vec { + let mut findings = Vec::new(); + let mut block = |error: registry_platform_config::ConfigBlockError| { + findings.push(Diagnostic::error( + "evidence.store-provision.configuration", + format!("/{}", error.field().replace('.', "/")), + error.to_string(), + "Correct the named field in the provisioning file.", + )); + }; + if let Err(error) = config.secret_providers.check() { + if !defers(&format!("/{}", error.field().replace('.', "/"))) { + block(error); + } + } + for (field, reference) in config.database.references() { + if !defers(&format!("/{}", field.replace('.', "/"))) { + if let Err(error) = config.secret_providers.check_reference(field, reference) { + block(error); + } + } + } + if config.database.migration_url_ref == config.database.runtime_url_ref + && !defers("/database/migrationUrlRef") + && !defers("/database/runtimeUrlRef") + { + findings.push(Diagnostic::error( + SPLIT_ROLES_REQUIRED, + "/database/runtimeUrlRef", + "the two URL references are identical", + "Use separate references for the migration and runtime login URLs.", + )); + } + if config.database.test_only_plaintext && !defers("/database/testOnlyPlaintext") { + findings.push(Diagnostic::error( + "evidence.store-provision.transport-refused", + "/database/testOnlyPlaintext", + "testOnlyPlaintext is unavailable for store provisioning", + "Use verified TLS or the explicit loopback-plaintext transport.", + )); + } + if !defers("/database/transport") + && provision_transport(&config.database) == DatabaseTransport::PrivateNetworkPlaintext + { + findings.push(Diagnostic::error( + "evidence.store-provision.transport-refused", + "/database/transport", + "store provisioning cannot use private-network-plaintext", + "Use verified TLS or the explicit loopback-plaintext transport.", + )); + } + findings +} + +fn unavailable_path() -> Diagnostic { + Diagnostic::error( + "evidence.store-provision.config-path", + "", + "the provisioning file path cannot be resolved", + "Pass an absolute path to the provisioning file.", + ) +} + +fn decoded_login(url: &str) -> Option { + let url = url::Url::parse(url).ok()?; + // Match the PostgreSQL URL reader's user-info decoding. The provisioner + // validates endpoint overrides and the rest of the URL before doing work. + percent_encoding::percent_decode_str(url.username()) + .decode_utf8() + .ok() + .map(|login| login.into_owned()) +} + +pub(crate) fn check( + path: &Path, + format: OutputFormat, + deny_warnings: bool, + environment: bool, + declared: DeclaredPosture, +) -> ExitCode { + let (found, unavailable) = match std::path::absolute(path) { + Ok(path) => { + let checked = loader(declared).check_offline::( + &path, + environment, + |pointer| match pointer { + "/store" => "status", + "/secretProviders/file/root" => "/deferred", + "/database/transport" => "verified-tls", + "/database/testOnlyPlaintext" => "false", + _ => DEFAULT_STAND_IN, + }, + ); + let extra = checked.loaded.as_ref().map_or_else(Vec::new, |loaded| { + diagnostics(&loaded.config, |pointer| checked.defers(pointer)) + }); + let positioned = extra.into_iter().map(|finding| { + checked.error_at( + KIND, + &finding.code, + &finding.path, + finding.message, + finding.suggested_action, + ) + }); + (checked.report_with(KIND, positioned), checked.unavailable) + } + Err(_) => (Report::new(vec![unavailable_path()]), true), + }; + let exit = if unavailable { + report::OPERATIONAL_FAILURE_EXIT + } else if found.has_errors() || crate::check::refuses_warnings(&found, deny_warnings) { + report::DOMAIN_REFUSAL_EXIT + } else { + report::SUCCESS_EXIT + }; + if exit == report::SUCCESS_EXIT { + match format { + OutputFormat::Json => crate::print_report_with_posture( + &report::success( + "check", + "complete", + serde_json::json!({"diagnostics": found.to_json_value()}), + ), + Some(declared), + ), + OutputFormat::Human => print!("{}", found.render_human()), + } + } else { + crate::write_report_failure("check", exit, &found, format, Some(declared)); + } + ExitCode::from(exit) +} + +fn load(path: &Path, declared: DeclaredPosture) -> Result> { + let absolute = std::path::absolute(path).map_err(|_| vec![unavailable_path()])?; + let loaded = loader(declared) + .load::(&absolute) + .map_err(|error| error.diagnostics().to_vec())?; + let config = loaded.config; + let findings = diagnostics(&config, |_| false); + if !findings.is_empty() { + return Err(findings); + } + let refuse = |code: &str, pointer: &str, message: String, action: &str| { + let mut diagnostic = Diagnostic::error(code, pointer, message, action); + diagnostic.artifact = Some(KIND.to_owned()); + diagnostic.source = Some(Source { + file: path.display().to_string(), + line: None, + column: None, + }); + vec![diagnostic] + }; + let secrets = config + .secret_providers + .resolver(loaded.development.as_ref()) + .map_err(|error| { + refuse( + "evidence.store-provision.secret-provider", + "/secretProviders", + error.to_string(), + error.suggested_action(), + ) + })?; + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); + read.map_err(|error| { + refuse( + "evidence.store-provision.secret-unavailable", + &format!("/database/{member}"), + describe_secret_failure(&format!("database.{member}"), reference, &error), + error.suggested_action(), + ) + }) + }; + let url = |member: DatabaseMember, reference: &str| { + let secret = resolve(member, reference)?; + std::str::from_utf8(secret.expose_secret()) + .map(|text| Zeroizing::new(text.trim().to_owned())) + .map_err(|_| { + refuse( + "evidence.store-provision.url-invalid", + &format!("/database/{member}"), + "the PostgreSQL URL secret is not UTF-8".to_owned(), + "Write a PostgreSQL URL in the secret.", + ) + }) + }; + let input = ProvisionInput { + product: config.store.product(), + migration_url: url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?, + runtime_url: url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?, + ca_pem: config + .database + .ca_bundle_ref + .as_deref() + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) + .transpose()? + .map(|secret| secret.expose_secret().to_vec()), + transport: provision_transport(&config.database), + explicit_settings: Vec::new(), + }; + let logins = decoded_login(&input.migration_url).zip(decoded_login(&input.runtime_url)); + if logins.is_some_and(|(migration, runtime)| migration == runtime) { + return Err(refuse( + SPLIT_ROLES_REQUIRED, + "/database/runtimeUrlRef", + "the two URLs name the same PostgreSQL login".to_owned(), + "Give the migration and runtime URLs distinct PostgreSQL login names.", + )); + } + Ok(input) +} + +pub(crate) fn run( + args: &ProvisionArgs, + format: OutputFormat, + declared: DeclaredPosture, +) -> ExitCode { + let format = match format { + OutputFormat::Human => registry_platform_provision::cli::OutputFormat::Human, + OutputFormat::Json => registry_platform_provision::cli::OutputFormat::Json, + }; + run_provision( + "evidencectl", + registry_platform_buildinfo::DISPLAY_VERSION, + args, + format, + declared, + |path| load(path, declared), + ) +} diff --git a/crates/registry-evidencectl/tests/doctor.rs b/crates/registry-evidencectl/tests/doctor.rs index 9cf4f7dbf5..f03954fb1b 100644 --- a/crates/registry-evidencectl/tests/doctor.rs +++ b/crates/registry-evidencectl/tests/doctor.rs @@ -84,6 +84,37 @@ fn doctor_passes_a_frozen_project_and_leaves_the_public_key_beside_it_alone() { ); } +#[test] +fn doctor_refuses_the_compose_mount_policy_as_the_runtime_does() { + let workspace = tempfile::tempdir().expect("tempdir"); + let project = workspace.path().join("project"); + provision(&project); + provision_bearer_token(&project); + set_mode(&project.join("secrets"), 0o750); + let runtime = project.join("runtime.yaml"); + let text = fs::read_to_string(&runtime).expect("runtime fixture"); + let stated = text.replace( + " root: secrets\n", + " root: secrets\n mountPolicy: compose-native\n", + ); + assert_ne!(stated, text, "the member is written"); + fs::write(&runtime, stated).expect("runtime fixture"); + + freeze(&project); + let output = doctor(&project, &[]); + unfreeze(&project); + + let stdout = stdout_of(&output); + assert!( + !output.status.success(), + "doctor passed a mount policy the runtime refuses:\n{stdout}" + ); + assert!( + stdout.contains("/secretProviders/file/mountPolicy"), + "{stdout}" + ); +} + #[test] fn doctor_names_every_artifact_whose_mode_the_runtime_refuses() { let workspace = tempfile::tempdir().expect("tempdir"); diff --git a/crates/registry-evidencectl/tests/file_check.rs b/crates/registry-evidencectl/tests/file_check.rs index 7d9f6bfc71..46165a0c79 100644 --- a/crates/registry-evidencectl/tests/file_check.rs +++ b/crates/registry-evidencectl/tests/file_check.rs @@ -393,7 +393,7 @@ fn check_help_says_the_project_is_required_unless_a_file_is_given() { .expect("run evidencectl"); let help = String::from_utf8_lossy(&output.stdout); assert!( - help.contains("Required unless --file is given"), + help.contains("Required unless --file or --store-provision-config is given"), "check --help must say when PROJECT is required: {help}" ); } diff --git a/crates/registry-evidencectl/tests/store_provision.rs b/crates/registry-evidencectl/tests/store_provision.rs new file mode 100644 index 0000000000..2efeaea35c --- /dev/null +++ b/crates/registry-evidencectl/tests/store_provision.rs @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::path::Path; +use std::process::{Command, Output}; + +fn config(directory: &Path, store: &str) -> std::path::PathBuf { + let path = directory.join("store-provision.yaml"); + std::fs::write( + &path, + format!( + "\ +apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 +kind: EvidenceStoreProvisionConfig +store: {store} +database: + migrationUrlRef: secret:env/EVIDENCE_TEST_STORE_MIGRATION + runtimeUrlRef: secret:env/EVIDENCE_TEST_STORE_RUNTIME +secretProviders: + environment: {{}} +" + ), + ) + .expect("write operator configuration"); + path +} + +fn evidencectl() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_evidencectl")); + command + .env_remove("REGISTRY_STACK_POSTURE") + .env_remove("EVIDENCE_TEST_STORE_MIGRATION") + .env_remove("EVIDENCE_TEST_STORE_RUNTIME"); + command +} + +fn check(path: &Path) -> Output { + evidencectl() + .args(["--format", "json", "check", "--store-provision-config"]) + .arg(path) + .output() + .expect("run offline check") +} + +fn plan(path: &Path, migration_role: &str, runtime_role: &str) -> Output { + let endpoint = + |role: &str| format!("postgresql://{role}:synthetic-canary@db.example.test/store"); + evidencectl() + .args(["provision", "--print-sql", "--runtime-config"]) + .arg(path) + .env("EVIDENCE_TEST_STORE_MIGRATION", endpoint(migration_role)) + .env("EVIDENCE_TEST_STORE_RUNTIME", endpoint(runtime_role)) + .output() + .expect("plan provisioning") +} + +#[test] +fn both_store_documents_check_without_resolving_secrets() { + let directory = tempfile::tempdir().expect("private test directory"); + for store in ["status", "oid4vci"] { + let output = check(&config(directory.path(), store)); + assert!( + output.status.success(), + "{store} check: {:?}", + output.status + ); + let report: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["status"], "complete"); + } +} + +#[test] +fn an_unknown_store_is_refused_offline() { + let directory = tempfile::tempdir().expect("private test directory"); + let output = check(&config(directory.path(), "unrecognised")); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["path"], "/store"); +} + +#[test] +fn store_name_requires_a_string() { + let directory = tempfile::tempdir().expect("private test directory"); + for store in ["true", "3", "2.5"] { + let output = check(&config(directory.path(), store)); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["path"], "/store"); + assert_eq!(report["diagnostics"][0]["code"], "config.expected-string"); + } +} + +#[test] +fn provisioning_check_resolves_authored_text_only_when_requested() { + let directory = tempfile::tempdir().expect("private test directory"); + let path = config(directory.path(), "status"); + let document = std::fs::read_to_string(&path).expect("read test configuration"); + std::fs::write(&path, document.replace( + "database:\n", + "database:\n transport: \"${EVIDENCE_TEST_TRANSPORT:?synthetic-private-diagnostic}\"\n", + )).expect("write a deferred transport setting"); + assert!(check(&path).status.success()); + + let inspect = |transport: Option<&str>| { + let mut command = evidencectl(); + command + .args([ + "--format", + "json", + "check", + "--environment", + "--store-provision-config", + ]) + .arg(&path) + .env_remove("EVIDENCE_TEST_TRANSPORT"); + if let Some(transport) = transport { + command.env("EVIDENCE_TEST_TRANSPORT", transport); + } + command.output().expect("run provisioning check") + }; + assert!(inspect(Some("verified-tls")).status.success()); + let refused = inspect(None); + assert_eq!(refused.status.code(), Some(1)); + assert!(!String::from_utf8_lossy(&refused.stdout).contains("synthetic-private-diagnostic")); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["code"], "config.substitution"); + assert_eq!(report["diagnostics"][0]["path"], "/database/transport"); +} + +#[test] +fn a_shared_url_reference_is_refused_without_resolving_it() { + let directory = tempfile::tempdir().expect("private test directory"); + let path = config(directory.path(), "status"); + let document = std::fs::read_to_string(&path).expect("read test configuration"); + std::fs::write( + &path, + document.replace( + "EVIDENCE_TEST_STORE_RUNTIME", + "EVIDENCE_TEST_STORE_MIGRATION", + ), + ) + .expect("write shared reference"); + let output = check(&path); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("check report"); + assert_eq!(report["diagnostics"][0]["path"], "/database/runtimeUrlRef"); + assert_eq!( + report["diagnostics"][0]["code"], + "evidence.store-provision.split-roles-required" + ); +} + +#[test] +fn provisioning_plans_split_roles_and_leaves_migration_separate() { + let directory = tempfile::tempdir().expect("private test directory"); + for store in ["status", "oid4vci"] { + let output = plan(&config(directory.path(), store), "migration", "runtime"); + assert!(output.status.success(), "{store} plan: {:?}", output.status); + let sql = std::str::from_utf8(&output.stdout).expect("SQL text"); + assert!(sql.contains("CREATE ROLE \"migration\"")); + assert!(sql.contains("CREATE ROLE \"runtime\"")); + assert!(sql.contains("GRANT CREATE ON DATABASE \"store\" TO \"migration\"")); + assert!(!sql.contains("CREATE TABLE")); + assert!(!sql.contains("synthetic-canary")); + assert!(!sql.contains("SCRAM-SHA-256")); + } +} + +#[test] +fn a_shared_login_is_refused_even_when_one_url_encodes_it() { + let directory = tempfile::tempdir().expect("private test directory"); + let output = plan(&config(directory.path(), "status"), "same", "%73ame"); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let refusal = std::str::from_utf8(&output.stderr).expect("refusal text"); + assert!(refusal.contains("evidence.store-provision.split-roles-required")); + assert!(!refusal.contains("synthetic-canary")); +} + +/// Use the shared verified-TLS fixture. Both variables must point to a +/// disposable server, as in the other products' provisioning tests. +#[cfg(feature = "postgres-test")] +#[tokio::test] +async fn both_stores_provision_idempotently_without_migrating() { + use registry_platform_provision::test_support::{connect_verified, provision_test_env}; + + let (admin_url, ca) = provision_test_env(); + let admin = connect_verified(&admin_url, &ca, None).await; + let base = registry_platform_provision::admin_config(&admin_url, Some(&ca)) + .expect("parse the disposable TLS endpoint"); + let directory = tempfile::tempdir().expect("private test directory"); + for (store, schema) in [ + ("status", "evidence_status"), + ("oid4vci", "evidence_oid4vci"), + ] { + let suffix: u64 = rand::random(); + let database = format!("evidence_store_{suffix:x}"); + let migration = format!("evidence_mig_{suffix:x}"); + let runtime = format!("evidence_run_{suffix:x}"); + let url = |role: &str| { + format!( + "postgresql://{role}:synthetic-canary@{}:{}/{database}?sslmode=verify-full", + base.host(), + base.port() + ) + }; + let migration_url = url(&migration); + let runtime_url = url(&runtime); + let config_path = config(directory.path(), store); + let document = std::fs::read_to_string(&config_path).expect("read test configuration"); + std::fs::write( + &config_path, + document.replace( + "database:\n", + "database:\n caBundleRef: secret:env/EVIDENCE_TEST_STORE_CA\n", + ), + ) + .expect("add the disposable CA reference"); + for _ in 0..2 { + let output = evidencectl() + .args([ + "--format", + "json", + "provision", + "--admin-url-env", + "EVIDENCE_TEST_STORE_ADMIN", + "--runtime-config", + ]) + .arg(&config_path) + .env("EVIDENCE_TEST_STORE_MIGRATION", &migration_url) + .env("EVIDENCE_TEST_STORE_RUNTIME", &runtime_url) + .env( + "EVIDENCE_TEST_STORE_CA", + std::str::from_utf8(&ca).expect("fixture PEM"), + ) + .env("EVIDENCE_TEST_STORE_ADMIN", &admin_url) + .output() + .expect("invoke the provision command"); + assert!( + output.status.success(), + "{store} provision: {:?}", + output.status + ); + let report: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("provision report"); + assert_eq!(report["roleMode"], "split"); + assert!(!String::from_utf8_lossy(&output.stdout).contains("synthetic-canary")); + } + let runtime_client = connect_verified(&runtime_url, &ca, None).await; + let migration_client = connect_verified(&migration_url, &ca, None).await; + let privilege = "SELECT has_database_privilege(current_database(), 'CREATE')"; + assert!(!runtime_client + .query_one(privilege, &[]) + .await + .unwrap() + .get::<_, bool>(0)); + assert!(migration_client + .query_one(privilege, &[]) + .await + .unwrap() + .get::<_, bool>(0)); + assert!(migration_client + .query_one("SELECT to_regnamespace($1) IS NULL", &[&schema]) + .await + .unwrap() + .get::<_, bool>(0)); + // The separate migration can create the store schema under its own role. + migration_client + .batch_execute(&format!("BEGIN; CREATE SCHEMA {schema}; ROLLBACK")) + .await + .expect("migration role can create the store schema"); + drop(runtime_client); + drop(migration_client); + admin + .batch_execute(&format!("DROP DATABASE {database} WITH (FORCE)")) + .await + .expect("clean up owned disposable database"); + admin + .batch_execute(&format!("DROP ROLE {migration}, {runtime}")) + .await + .expect("clean up owned disposable roles"); + } +} diff --git a/crates/registry-language-server/src/products/catalog_coordinator.rs b/crates/registry-language-server/src/products/catalog_coordinator.rs index 72e07ea93f..44ab88af5a 100644 --- a/crates/registry-language-server/src/products/catalog_coordinator.rs +++ b/crates/registry-language-server/src/products/catalog_coordinator.rs @@ -6,7 +6,7 @@ use super::spec::{DocumentRules, FileRule, NameRule as N}; const DECLARATIONS: &[N] = &[ N::global("project/id", "Coordinator workflow"), N::global("types/$key", "Coordinator type"), - N::global("functions/$key", "Coordinator Function"), + N::global("transforms/$key", "Coordinator Transform"), N::global("contracts/$key", "Coordinator contract import"), N::global("operations/$key", "Coordinator Operation"), N::global("workflow/steps/$key", "Coordinator Step"), @@ -31,13 +31,13 @@ const REFERENCES: &[N] = &[ ), N::global( "operations/*/completions/*/interpret", - "Coordinator Function", + "Coordinator Transform", ), - N::global("operations/*/interpret", "Coordinator Function"), + N::global("operations/*/interpret", "Coordinator Transform"), // Mapping inputs and fields hold References, so literal JSON payloads are never walked. N { - only_when: Some(("type", "function")), - ..N::global("workflow/steps/*/input/function", "Coordinator Function") + only_when: Some(("type", "transform")), + ..N::global("workflow/steps/*/input/transform", "Coordinator Transform") }, N { only_when: Some(("type", "step")), @@ -52,8 +52,8 @@ const REFERENCES: &[N] = &[ ..N::global("workflow/steps/*/input/fields/*/step", "Coordinator Step") }, N { - only_when: Some(("type", "function")), - ..N::global("workflow/steps/*/choose/function", "Coordinator Function") + only_when: Some(("type", "transform")), + ..N::global("workflow/steps/*/choose/transform", "Coordinator Transform") }, N { only_when: Some(("type", "step")), @@ -68,10 +68,10 @@ const REFERENCES: &[N] = &[ ..N::global("workflow/steps/*/choose/fields/*/step", "Coordinator Step") }, N { - only_when: Some(("type", "function")), + only_when: Some(("type", "transform")), ..N::global( - "workflow/steps/*/waitUntil/function", - "Coordinator Function", + "workflow/steps/*/waitUntil/transform", + "Coordinator Transform", ) }, N { @@ -93,8 +93,8 @@ const REFERENCES: &[N] = &[ ) }, N { - only_when: Some(("type", "function")), - ..N::global("workflow/steps/*/output/function", "Coordinator Function") + only_when: Some(("type", "transform")), + ..N::global("workflow/steps/*/output/transform", "Coordinator Transform") }, N { only_when: Some(("type", "step")), @@ -109,10 +109,10 @@ const REFERENCES: &[N] = &[ ..N::global("workflow/steps/*/output/fields/*/step", "Coordinator Step") }, N { - only_when: Some(("type", "function")), + only_when: Some(("type", "transform")), ..N::global( - "workflow/eventTriggers/*/input/function", - "Coordinator Function", + "workflow/eventTriggers/*/input/transform", + "Coordinator Transform", ) }, N { @@ -142,35 +142,38 @@ const REFERENCES: &[N] = &[ "types/*/completionOutput/operation", "Coordinator Operation", ), - N::global("functions/*/inputs/*/typeRef", "Coordinator type"), + N::global("transforms/*/inputs/*/typeRef", "Coordinator type"), N::global( - "functions/*/inputs/*/operationInput", + "transforms/*/inputs/*/operationInput", "Coordinator Operation", ), N::global( - "functions/*/inputs/*/operationOutput", + "transforms/*/inputs/*/operationOutput", "Coordinator Operation", ), N::global( - "functions/*/inputs/*/operationRefusal", + "transforms/*/inputs/*/operationRefusal", "Coordinator Operation", ), N::global( - "functions/*/inputs/*/completionOutput/operation", + "transforms/*/inputs/*/completionOutput/operation", "Coordinator Operation", ), - N::global("functions/*/output/typeRef", "Coordinator type"), - N::global("functions/*/output/operationInput", "Coordinator Operation"), + N::global("transforms/*/output/typeRef", "Coordinator type"), N::global( - "functions/*/output/operationOutput", + "transforms/*/output/operationInput", "Coordinator Operation", ), N::global( - "functions/*/output/operationRefusal", + "transforms/*/output/operationOutput", "Coordinator Operation", ), N::global( - "functions/*/output/completionOutput/operation", + "transforms/*/output/operationRefusal", + "Coordinator Operation", + ), + N::global( + "transforms/*/output/completionOutput/operation", "Coordinator Operation", ), N::global("operations/*/responseSchema/typeRef", "Coordinator type"), @@ -252,7 +255,7 @@ pub(super) const DOCUMENTS: &[DocumentRules] = &[ references: REFERENCES, // Assets remain navigation targets; no Rhai or generated contract bytes are indexed. files: &[ - FileRule::root("functions/*/source", false), + FileRule::root("transforms/*/source", false), FileRule::root("contracts/*/source", false), ], }, diff --git a/crates/registry-language-server/tests/coordinator_navigation.rs b/crates/registry-language-server/tests/coordinator_navigation.rs index c4d256e462..1562a85e0e 100644 --- a/crates/registry-language-server/tests/coordinator_navigation.rs +++ b/crates/registry-language-server/tests/coordinator_navigation.rs @@ -19,8 +19,8 @@ types: <|type|>request: {type: object} contracts: <|contract|>registry: {type: breg, source: <|contract-file|>generated/registry.json} -functions: - <|function|>make-request: +transforms: + <|transform|>make-request: runtime: rhai source: <|function-file|>functions.rhai entrypoint: make_request @@ -41,8 +41,8 @@ workflow: dataSchema: urn:example:remote-event:v1 event: {typeRef: <|event-type-use|>request} input: - type: function - function: <|event-function-use|>make-request + type: transform + transform: <|event-function-use|>make-request inputs: {request: {type: input}} review: outcomes: @@ -53,8 +53,8 @@ workflow: type: call operation: <|operation-use|>read-record input: - type: function - function: <|function-use|>make-request + type: transform + transform: <|function-use|>make-request inputs: {request: {type: input}} next: <|next-use|>complete <|finish|>complete: @@ -66,7 +66,7 @@ workflow: record: {type: step, step: <|step-use|>read} literal: type: literal - value: {type: function, function: not-a-local-function, step: not-a-local-step, typeRef: not-a-local-type} + value: {type: transform, transform: not-a-local-function, step: not-a-local-step, typeRef: not-a-local-type} outcomes: <|outcome|>handled: {operationOutput: <|output-operation-use|>read-record} "#; @@ -100,8 +100,8 @@ fn coordinator_native_review_and_event_edges_resolve_without_claiming_external_n ("operation-use", "operation", "read-record"), ("output-operation-use", "operation", "read-record"), ("contract-use", "contract", "registry"), - ("function-use", "function", "make-request"), - ("event-function-use", "function", "make-request"), + ("function-use", "transform", "make-request"), + ("event-function-use", "transform", "make-request"), ("start-use", "step", "read"), ("next-use", "finish", "complete"), ("step-use", "step", "read"), @@ -262,7 +262,7 @@ async fn coordinator_discovery_unsaved_diagnostics_and_watched_assets_use_the_re ); let changed = source - .replace("function: make-request", "function: unknown-function") + .replace("transform: make-request", "transform: unknown-function") .replace("operation: read-record", "operation: unknown-operation") .replace("start: read", "start: unknown-step") .replace("typeRef: request", "typeRef: unknown-type") diff --git a/crates/registry-mcp-edge/src/config.rs b/crates/registry-mcp-edge/src/config.rs index 2d10e938ac..81d25fa1bd 100644 --- a/crates/registry-mcp-edge/src/config.rs +++ b/crates/registry-mcp-edge/src/config.rs @@ -583,13 +583,14 @@ impl ResourceServerConfig { } JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { let field = format!("{base}.jwksSource.documentRef"); - let secret = secrets.resolve(document_ref).map_err(|error| { - IssuerBuildError::Secret { - field: field.clone(), - reference: document_ref.clone(), - error, - } - })?; + let secret = + secrets + .resolve_public_document(document_ref) + .map_err(|error| IssuerBuildError::Secret { + field: field.clone(), + reference: document_ref.clone(), + error, + })?; let keys = parse_static_jwks(secret.expose_secret()).map_err(|error| { IssuerBuildError::StaticKeySet { field: field.clone(), diff --git a/crates/registry-mcp/src/config.rs b/crates/registry-mcp/src/config.rs index 253a836f06..ad0e8e3f6e 100644 --- a/crates/registry-mcp/src/config.rs +++ b/crates/registry-mcp/src/config.rs @@ -260,8 +260,28 @@ impl RuntimeConfig { environment: bool, declared: DeclaredPosture, ) -> (Report, bool) { + let (report, unavailable, _) = Self::check_with_settings(path, environment, declared); + (report, unavailable) + } + + /// [`Self::check_status_with_posture`], with the explicit production + /// settings the file states, which `check` reports beside its diagnostics. + pub fn check_with_settings( + path: &Path, + environment: bool, + declared: DeclaredPosture, + ) -> ( + Report, + bool, + Vec, + ) { let (checked, report) = read_runtime(path, environment, declared); - (report, checked.unavailable) + let settings = checked + .loaded + .as_ref() + .map(|loaded| loaded.posture.explicit_settings().to_vec()) + .unwrap_or_default(); + (report, checked.unavailable, settings) } pub fn validate( &self, diff --git a/crates/registry-mcp/src/main.rs b/crates/registry-mcp/src/main.rs index 5e09f9bf07..afa41e6b61 100644 --- a/crates/registry-mcp/src/main.rs +++ b/crates/registry-mcp/src/main.rs @@ -111,36 +111,43 @@ async fn main() -> ExitCode { if let Command::Check(arguments) = cli.command { let given = &runtime_config; - let (report, unavailable) = match registry_breg_mcp::check::absolute_runtime_path(given) { - Some(path) => { - let (mut report, unavailable) = RuntimeConfig::check_status_with_posture( - &path, - arguments.environment, - declared, - ); - registry_breg_mcp::check::restore_diagnostic_path( - report.diagnostics_mut(), - &path, - given, - ); - (report, unavailable) - } - None => { - use registry_platform_yaml::{Diagnostic, Report, Source}; - let mut diagnostic = Diagnostic::error( - "platform.runtime-config.unavailable", - "", - "the runtime file path could not be made absolute", - "Name the runtime file by an absolute path, then run the check again.", - ); - diagnostic.source = Some(Source { - file: given.display().to_string(), - line: None, - column: None, - }); - (Report::new(vec![diagnostic]), true) - } - }; + let (report, unavailable, settings) = + match registry_breg_mcp::check::absolute_runtime_path(given) { + Some(path) => { + let (mut report, unavailable, settings) = + RuntimeConfig::check_with_settings(&path, arguments.environment, declared); + registry_breg_mcp::check::restore_diagnostic_path( + report.diagnostics_mut(), + &path, + given, + ); + (report, unavailable, settings) + } + None => { + use registry_platform_yaml::{Diagnostic, Report, Source}; + let mut diagnostic = Diagnostic::error( + "platform.runtime-config.unavailable", + "", + "the runtime file path could not be made absolute", + "Name the runtime file by an absolute path, then run the check again.", + ); + diagnostic.source = Some(Source { + file: given.display().to_string(), + line: None, + column: None, + }); + (Report::new(vec![diagnostic]), true, Vec::new()) + } + }; + // Each explicit production setting the file states, as every check + // reports it: a fact for review, not a diagnostic. + let file = given.display().to_string(); + let explicit: Vec<_> = settings + .iter() + .map(|found| { + registry_platform_config::ExplicitSettingLine::from_found(found, Some(&file)) + }) + .collect(); let failed = unavailable || report.has_errors() || (arguments.deny_warnings @@ -154,9 +161,14 @@ async fn main() -> ExitCode { }; eprintln!("{headline}\n{}", report.render_human()); } - Format::Human => print!("{}", report.render_human()), + Format::Human => { + for found in &settings { + eprintln!("{}", found.notice()); + } + print!("{}", report.render_human()); + } Format::Json => match serde_json::to_string_pretty( - &serde_json::json!({"ok":!failed,"command":"check","status":if unavailable {"operational-failure"} else if failed {"domain-refusal"} else {"complete"},"apiVersion":"id.registrystack.org/formats/platform/mcp-ctl-report/v1alpha1","kind":"PlatformMcpCtlReport","version":env!("CARGO_PKG_VERSION"),"filesChecked":1,"errors":report.error_count(),"warnings":report.warning_count(),"diagnostics":report.to_json_value(),"posture":{"value":declared.posture.as_str(),"source":declared.source.as_str()}}), + &serde_json::json!({"ok":!failed,"command":"check","status":if unavailable {"operational-failure"} else if failed {"domain-refusal"} else {"complete"},"apiVersion":"id.registrystack.org/formats/platform/mcp-ctl-report/v1alpha1","kind":"PlatformMcpCtlReport","version":env!("CARGO_PKG_VERSION"),"filesChecked":1,"errors":report.error_count(),"warnings":report.warning_count(),"diagnostics":report.to_json_value(),"posture":{"value":declared.posture.as_str(),"source":declared.source.as_str()},"explicitProductionSettings":explicit}), ) { Ok(json) => println!("{json}"), Err(_) => { diff --git a/crates/registry-mcp/tests/cli.rs b/crates/registry-mcp/tests/cli.rs index 906af94f68..4a1b9e7223 100644 --- a/crates/registry-mcp/tests/cli.rs +++ b/crates/registry-mcp/tests/cli.rs @@ -251,6 +251,32 @@ fn the_shipped_example_passes_a_production_check() { assert_eq!(report["diagnostics"], serde_json::json!([]), "{report}"); } +#[test] +fn check_reports_the_explicit_production_settings_the_file_states() { + let directory = private_fixture_directory().unwrap(); + let plain = std::fs::read_to_string(example()).unwrap(); + let path = stage_runtime(directory.path().join("plain.yaml"), plain.as_bytes()); + let (exit, report) = check_json(&path, &[]); + assert_eq!(exit, Some(0), "{report}"); + assert_eq!(report["explicitProductionSettings"], serde_json::json!([])); + + let stated = plain.replace( + "secretProviders:\n environment: {}\n", + "secretProviders:\n environment: {}\n file:\n root: /run/registry-mcp/secrets\n mountPolicy: compose-native\n", + ); + assert_ne!(stated, plain, "the member is written"); + let path = stage_runtime(directory.path().join("stated.yaml"), stated.as_bytes()); + let (exit, report) = check_json(&path, &[]); + assert_eq!(exit, Some(0), "{report}"); + let settings = report["explicitProductionSettings"].as_array().unwrap(); + assert!( + settings.iter().any(|setting| setting["code"] + == "platform.posture.compose-native-secret-mount" + && setting["pointer"] == "/secretProviders/file/mountPolicy"), + "{report}" + ); +} + #[test] fn the_shipped_example_separates_the_public_resource_from_the_listener() { use registry_mcp::config::{ProviderConfig, RuntimeConfig}; diff --git a/crates/registry-messaging/src/config.rs b/crates/registry-messaging/src/config.rs index 203cd5ea30..4db247638f 100644 --- a/crates/registry-messaging/src/config.rs +++ b/crates/registry-messaging/src/config.rs @@ -1250,12 +1250,12 @@ impl RuntimeConfig { } OidcJwksSource::Static { document_ref } | OidcJwksSource::TestIssuer { document_ref } => { - let document = secrets.resolve(document_ref).map_err(|error| { - RuntimeConfigError::OidcJwksSecret { + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| RuntimeConfigError::OidcJwksSecret { issuer: id.to_owned(), message: describe_secret_failure(&document_field, document_ref, &error), - } - })?; + })?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { match error { // The document is the operator's own file, so its text names the @@ -2370,6 +2370,15 @@ pub(crate) mod tests { /// key source from it. #[cfg(unix)] async fn static_key_source(document: &str) -> Result<(), RuntimeConfigError> { + static_key_source_with_mode(document, 0o600).await + } + + /// [`static_key_source`] with the key set file at `mode`. + #[cfg(unix)] + async fn static_key_source_with_mode( + document: &str, + mode: u32, + ) -> Result<(), RuntimeConfigError> { use std::os::unix::fs::PermissionsExt as _; let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); @@ -2378,7 +2387,7 @@ pub(crate) mod tests { std::fs::set_permissions(&secrets, std::fs::Permissions::from_mode(0o700)).unwrap(); let file = secrets.join("issuer-jwks"); std::fs::write(&file, document).unwrap(); - std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(mode)).unwrap(); let mut runtime = runtime_value(root.path()); runtime["authentication"]["oidc"]["issuers"]["main"]["jwksSource"] = json!({"type": "static", "documentRef": "secret:file/issuer-jwks"}); @@ -2403,6 +2412,17 @@ pub(crate) mod tests { key } + /// A key set is a public document: a world-readable file loads, where a + /// secret at the same mode is refused. + #[cfg(unix)] + #[tokio::test] + async fn a_world_readable_static_key_set_loads_as_a_public_document() { + let document = json!({"keys": [static_key(json!({}))]}); + static_key_source_with_mode(&document.to_string(), 0o644) + .await + .expect("a world-readable key set loads"); + } + #[cfg(unix)] #[tokio::test] async fn a_static_key_set_with_members_it_does_not_know_loads() { diff --git a/crates/registry-messaging/src/http_provider/settings.rs b/crates/registry-messaging/src/http_provider/settings.rs index 6a5ddeb319..1b8acd421b 100644 --- a/crates/registry-messaging/src/http_provider/settings.rs +++ b/crates/registry-messaging/src/http_provider/settings.rs @@ -29,6 +29,9 @@ use registry_platform_httputil::destination::{ is_script_visible_response_header_name, is_script_writable_request_header_name, MAX_DESTINATION_OPERATION_TIMEOUT, MAX_DESTINATION_PRIVATE_CIDRS, }; +use registry_platform_httputil::select::{ + select_destination, DestinationSelectionError, TransportClass, +}; use registry_platform_yaml::{ ApiVersion, Decoded, EnvelopeRule, Expect, FormatSpec, Invalid, Reader, RemovedKey, Report, UniqueList, @@ -1287,23 +1290,16 @@ fn split_base_url( "must not carry credentials, a query, or a fragment", )); } - let development = match parsed.scheme() { - "https" => false, - "http" => { - let loopback = parsed - .host_str() - .and_then(registry_platform_httputil::loopback::loopback_host) - .is_some(); - if !loopback { - return Err(invalid( - field, - "http is allowed only to a loopback host; use https", - )); + let selected = select_destination(&parsed, None, &[]).map_err(|error| { + let message = match error { + DestinationSelectionError::PrivateNetworkNotDeclared => { + "http is allowed only to a loopback host; use https" } - true - } - _ => return Err(invalid(field, "must use https, or http to a loopback host")), - }; + _ => "must use https, or http to a loopback host", + }; + invalid(field, message) + })?; + let development = selected.transport() == TransportClass::LoopbackPlaintext; // The URL parser resolves dot segments and their escapes, so the // configured text is checked too: the path sent is the path written. let path = parsed.path().to_owned(); @@ -1414,6 +1410,27 @@ fn token_form_body( mod tests { use super::*; + #[test] + fn provider_and_token_paths_keep_the_configured_https_origin() { + let expected_origin = "https://provider.example.test:8443/".to_owned(); + let (origin, path, development) = + split_base_url("baseUrl", "https://provider.example.test:8443/v1/", true).unwrap(); + assert_eq!( + (origin, path, development), + (expected_origin.clone(), "/v1/".to_owned(), false) + ); + let (origin, path, development) = split_base_url( + "authentication.tokenEndpoint", + "https://provider.example.test:8443/issuer/token", + false, + ) + .unwrap(); + assert_eq!( + (origin, path, development), + (expected_origin, "/issuer/token".to_owned(), false) + ); + } + #[test] fn plain_http_is_allowed_only_to_a_loopback_host() { for base_url in [ diff --git a/crates/registry-messaging/src/providers.rs b/crates/registry-messaging/src/providers.rs index 6cb3a06c4a..f7db2e9287 100644 --- a/crates/registry-messaging/src/providers.rs +++ b/crates/registry-messaging/src/providers.rs @@ -91,9 +91,18 @@ pub fn activate_providers( .to_owned(), ) })?; - Some(resolve(secrets, "bundleRef", &profile.bundle_ref).map_err( - |reason| refused(format!("tlsTrustProfiles.{name}: {reason}")), - )?) + Some( + secrets + .resolve_public_document(&profile.bundle_ref) + .map_err(|error| { + let reason = describe_secret_failure( + "bundleRef", + &profile.bundle_ref, + &error, + ); + refused(format!("tlsTrustProfiles.{name}: {reason}")) + })?, + ) } }; let provider = Arc::new( diff --git a/crates/registry-messaging/src/smtp/settings.rs b/crates/registry-messaging/src/smtp/settings.rs index ee5ad1ce32..1203b3da2c 100644 --- a/crates/registry-messaging/src/smtp/settings.rs +++ b/crates/registry-messaging/src/smtp/settings.rs @@ -310,9 +310,15 @@ impl SmtpProviderSettings { fn tls_parameters(&self, secrets: &SecretResolver) -> Result { let mut builder = TlsParameters::builder(self.host.clone()); if let Some(reference) = &self.ca_bundle_ref { - let pem = secrets.resolve(reference).map_err(|error| { - SmtpSettingsError::Secret(describe_secret_failure("caBundleRef", reference, &error)) - })?; + let pem = secrets + .resolve_public_document(reference) + .map_err(|error| { + SmtpSettingsError::Secret(describe_secret_failure( + "caBundleRef", + reference, + &error, + )) + })?; let certificates = CertificateDer::pem_slice_iter(pem.expose_secret()) .collect::, _>>() .map_err(|_| SmtpSettingsError::InvalidTrustedRootCertificate)?; diff --git a/crates/registry-messaging/src/store.rs b/crates/registry-messaging/src/store.rs index a242049777..502cf4b469 100644 --- a/crates/registry-messaging/src/store.rs +++ b/crates/registry-messaging/src/store.rs @@ -460,13 +460,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index 713486fa54..6d243afba5 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -2476,13 +2476,7 @@ fn render_check( )?; } for setting in settings { - writeln!( - stdout, - "Explicit production setting {} at {}. {}.", - setting.code, - setting.pointer.as_deref().unwrap_or_default(), - setting.summary - )?; + writeln!(stdout, "{}", setting.notice())?; } Ok(()) } @@ -2817,6 +2811,48 @@ audit: ); } + #[test] + fn the_compose_mount_policy_is_listed_by_check_and_recorded_for_startup() { + let (root, path) = project(""); + let text = std::fs::read_to_string(&path).unwrap(); + let providers = "secretProviders:\n environment: {}\n"; + assert!(text.contains(providers), "{text}"); + let secrets = root.path().canonicalize().unwrap().join("secrets"); + std::fs::write( + &path, + text.replace( + providers, + &format!( + "{providers} file:\n root: {}\n mountPolicy: compose-native\n", + secrets.display() + ), + ), + ) + .unwrap(); + let (exit, report) = check_json(&path); + assert_eq!(exit, ExitCode::SUCCESS, "{report}"); + assert!( + report["explicitProductionSettings"] + .as_array() + .unwrap() + .iter() + .any( + |line| line["code"] == "platform.posture.compose-native-secret-mount" + && line["pointer"] == "/secretProviders/file/mountPolicy" + ), + "{report}" + ); + // Startup logs every setting the loaded posture records. + let config = RuntimeConfig::load(&path, registry_messaging::config::DEFAULT_POSTURE) + .expect("the runtime file loads"); + assert!(config + .posture_report() + .explicit_setting_notices() + .iter() + .any(|notice| notice + .contains("compose-native-secret-mount at /secretProviders/file/mountPolicy"))); + } + #[test] fn a_check_lists_the_explicit_production_settings_the_runtime_states() { let (_root, path) = project(""); diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs index 8388648e78..a488c5867d 100644 --- a/crates/registry-messagingctl/src/provision.rs +++ b/crates/registry-messagingctl/src/provision.rs @@ -8,7 +8,7 @@ use std::path::Path; use registry_messaging::config::{startup_report, RuntimeConfig}; use registry_messaging_core::MESSAGING_RUNTIME_KIND; -use registry_platform_config::describe_secret_failure; +use registry_platform_config::{describe_secret_failure, DatabaseMember}; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, }; @@ -74,17 +74,18 @@ pub(crate) fn load( "Correct secretProviders in the runtime file, then run provision again.", ) })?; - let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), describe_secret_failure(&format!("database.{member}"), reference, &error), - "Check the secret provider and that the secret exists, then run provision again.", + error.suggested_action(), ) }) }; - let url = |member: &str, reference: &str| { + let url = |member: DatabaseMember, reference: &str| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -97,13 +98,16 @@ pub(crate) fn load( ) }) }; - let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; - let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let migration_url = url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?; + let runtime_url = url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?; let ca_pem = config .database .ca_bundle_ref .as_deref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); Ok(ProvisionInput { @@ -112,5 +116,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(&config.database), + explicit_settings: config.posture_report().explicit_setting_notices(), }) } diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index 60e448a720..df6f80f1af 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -191,6 +191,45 @@ fn print_sql_writes_the_script_and_no_password() { } } +#[test] +fn a_world_readable_ca_bundle_loads_and_the_mount_policy_is_noticed() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + // A CA bundle is a public document: a mode 0644 file loads, where a + // secret at that mode is refused. + let ca = directory.path().join("secrets").join("database-ca.pem"); + std::fs::write( + &ca, + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n", + ) + .unwrap(); + std::fs::set_permissions(&ca, std::fs::Permissions::from_mode(0o644)).unwrap(); + let text = std::fs::read_to_string(&runtime).unwrap(); + let stated = text + .replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca.pem\n", + ) + .replace( + "secretProviders:\n file:\n", + "secretProviders:\n file:\n mountPolicy: compose-native\n", + ); + assert_eq!(stated.matches("caBundleRef").count(), 1, "{stated}"); + assert!(stated.contains("mountPolicy"), "{stated}"); + std::fs::write(&runtime, stated).unwrap(); + + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert_eq!(output.status.code(), Some(0), "{stdout}{stderr}"); + assert!( + stderr.contains( + "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy." + ), + "{stderr}" + ); +} + #[test] fn print_sql_as_json_reports_nothing_executed() { let directory = scratch(); @@ -320,6 +359,34 @@ fn a_missing_runtime_url_secret_is_refused_at_its_member() { assert_eq!(diagnostic["path"], "/database/runtimeUrlRef", "{report:#}"); } +#[test] +fn a_ca_bundle_that_is_not_text_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let ca = directory.path().join("secrets").join("database-ca.pem"); + std::fs::write(&ca, [0xff, 0xfe, 0xfd]).unwrap(); + std::fs::set_permissions(&ca, std::fs::Permissions::from_mode(0o644)).unwrap(); + let text = std::fs::read_to_string(&runtime).unwrap(); + let stated = text.replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca.pem\n", + ); + assert_eq!(stated.matches("caBundleRef").count(), 1, "{stated}"); + std::fs::write(&runtime, stated).unwrap(); + let (code, report) = refusal(&runtime); + assert_eq!(code, Some(1), "{report:#}"); + let diagnostic = first_diagnostic(&report); + assert_eq!(diagnostic["code"], "config.refused", "{report:#}"); + assert_eq!(diagnostic["path"], "/database/caBundleRef", "{report:#}"); + assert!( + diagnostic["message"] + .as_str() + .unwrap() + .contains("not UTF-8 text"), + "{report:#}" + ); +} + #[test] fn a_migration_url_secret_that_is_not_text_is_refused_at_its_member() { let directory = scratch(); diff --git a/crates/registry-platform-config/README.md b/crates/registry-platform-config/README.md index 5ba2ff1409..d7bdb252a5 100644 --- a/crates/registry-platform-config/README.md +++ b/crates/registry-platform-config/README.md @@ -12,7 +12,8 @@ apply the same provider allowlist, regular-file checks, size bounds, redacted diagnostics, and zeroization. The consumer validates its key format and length; the resolver does not decode, trim, or reinterpret file contents. -A secret file is read through one rule. The name may be a relative link that +A secret file is read through one rule, with two explicit widenings described +below. The name may be a relative link that stays below `secretProviders.file.root` (downward steps only, at most 8 links, no `..`, no absolute target). The file it reaches must be a regular file with one hard link and no write access for others, and either owned by the runtime @@ -25,6 +26,17 @@ and `SecretError::suggested_action()` gives the fix for any failure. `SecretResolver::inspect_reference` runs the same checks without reading the bytes. +The file provider's `mountPolicy: compose-native` also accepts a root-owned, +single-link file at mode exactly 0444, the Docker Compose secret mount shape. +It is an explicit production setting: startup, `check` and the `provision` +tools report it. A public document, such as a static JWKS or a CA bundle, is +read with `resolve_public_document`, which keeps the walk, owner, link and +write checks but lets group and others read the file. Its refusals are +`SecretError::UnsafePublicDocument`, worded for a public document, and it +refuses a file holding a PEM private key block +(`SecretError::PrivateKeyInPublicDocument`). `inspect_public_document` checks +one without reading it. + ## Loader `RuntimeConfigLoader` reads one runtime configuration file named by an @@ -111,9 +123,16 @@ accepted reference through the explicitly enabled environment or file provider. - `SecretProvidersConfig`: `file.root` enables `secret:file/name`, and `environment: {}` enables `secret:env/NAME`. At least one must be declared, - and a reference to an undeclared provider is refused. + and a reference to an undeclared provider is refused. `file.mountPolicy` + is the Compose mount setting above, and `compose_native_mounts()` lets a + product whose contract keeps the strict rule refuse it. +- `StrictSecretProvidersConfig`: the same providers without `mountPolicy`, for + operator-local files read outside any runtime, such as saved CLI + connections and task connections. - `DatabaseConfig`: `runtimeUrlRef`, `migrationUrlRef`, and an optional - `caBundleRef`. + `caBundleRef`. `DatabaseMember` names each of them and reads it with the + rule it takes: the CA bundle as a public document that must be UTF-8 text, + each URL as a secret. - `DestinationTransport`: `verified-tls`, `loopback-plaintext` or `private-network-plaintext`. Only the last is an explicit production setting. - `PrivateRanges`: the `allowedPrivateCidrs` list of `PrivateRange` values from diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 74ea24fbda..9444678671 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -20,7 +20,8 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::{ DestinationTransport, DevelopmentClass, DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, ExplicitClass, ExplicitProductionSetting, Gated, PrivateRanges, - SecretError, SecretProvider, SecretReference, SecretResolver, Stated, MAX_SECRET_BYTES, + ProtectedSecret, SecretError, SecretProvider, SecretReference, SecretResolver, Stated, + MAX_SECRET_BYTES, }; /// The schema pattern of a field that must name an enabled secret provider. @@ -138,9 +139,52 @@ pub struct FileSecretProviderConfig { /// the runtime user with mode 0400 or 0600, or owned by root with no /// access beyond group read (0440 or 0640) when the runtime is not root. /// A process that declared development loads a file with looser read or - /// mode bits and logs a warning. + /// mode bits and logs a warning. A public document, such as a static JWKS + /// or a CA bundle, may also be readable by group and others. #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] pub root: PathBuf, + /// `compose-native` also accepts a root-owned regular file with one hard + /// link and mode exactly 0444, the shape of a Docker Compose secret mount. + /// Every user in the container can read such a file. Startup and `check` + /// report this explicit production setting. Without it, only the file + /// shapes `root` describes are accepted. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "Stated"))] + mount_policy: Option>, +} + +impl FileSecretProviderConfig { + /// The standard file provider, with the strict production permission policy. + #[must_use] + pub fn new(root: PathBuf) -> Self { + Self { + root, + mount_policy: None, + } + } +} + +static COMPOSE_NATIVE_SECRET_MOUNT: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.compose-native-secret-mount", + key: "mountPolicy", + summary: "The file secret provider accepts root-owned, mode 0444 Compose mounts", +}; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "kebab-case")] +enum SecretMountPolicy { + ComposeNative, +} + +impl ExplicitClass for SecretMountPolicy { + const SETTINGS: &'static [&'static ExplicitProductionSetting] = &[&COMPOSE_NATIVE_SECRET_MOUNT]; + + fn explicit_setting(&self) -> Option<&'static ExplicitProductionSetting> { + match self { + Self::ComposeNative => Some(&COMPOSE_NATIVE_SECRET_MOUNT), + } + } } /// The environment secret provider. It takes no settings. @@ -205,6 +249,18 @@ impl SecretProvidersConfig { providers } + /// Whether the file provider states `mountPolicy: compose-native`. A + /// product whose contract keeps the strict file rule refuses the block + /// when this is true. + #[must_use] + pub fn compose_native_mounts(&self) -> bool { + self.file.as_ref().is_some_and(|file| { + file.mount_policy + .as_ref() + .is_some_and(|policy| *policy.get() == SecretMountPolicy::ComposeNative) + }) + } + /// A resolver for exactly the providers this block enables. When the /// process holds a [`DevelopmentWitness`], the file provider relaxes the /// read and mode-bit checks to a warning. @@ -218,7 +274,91 @@ impl SecretProvidersConfig { .as_ref() .map_or_else(|| Path::new(""), |file| file.root.as_path()), ) - .map(|resolver| resolver.in_development(witness)) + .map(|resolver| { + let resolver = resolver.in_development(witness); + if self.compose_native_mounts() { + resolver.with_compose_native_mounts() + } else { + resolver + } + }) + } +} + +/// The secret providers without the Compose mount policy, so the strict file +/// rule always applies. An operator-local file read outside any runtime, such +/// as a saved CLI connection or a task connection, uses it because nothing +/// reports an explicit production setting for that file. A runtime whose keys +/// keep the strict rule publishes it as the shape of its `secretProviders`. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(extend("anyOf" = [ + {"required": ["file"], "properties": {"file": {"$ref": "#/$defs/StrictFileSecretProviderConfig"}}}, + {"required": ["environment"], "properties": {"environment": {"$ref": "#/$defs/EnvironmentSecretProviderConfig"}}} + ])) +)] +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StrictSecretProvidersConfig { + /// Enables `secret:file/name` references, read from files under `root`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "StrictFileSecretProviderConfig"))] + pub file: Option, + /// Enables `secret:env/NAME` references, read from the process + /// environment. Declared as an empty mapping: `environment: {}`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(with = "EnvironmentSecretProviderConfig"))] + pub environment: Option, +} + +/// The file secret provider without the Compose mount policy. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StrictFileSecretProviderConfig { + /// Absolute directory holding one file per secret. A name may be a + /// relative link that stays below this directory, through at most 8 links. + /// The file it reaches must be a regular file with one hard link, owned by + /// the user running the process with mode 0400 or 0600, or owned by root + /// with no access beyond group read (0440 or 0640) when that user is not + /// root. A process that declared development loads a file with looser read + /// or mode bits and logs a warning. A public document, such as a static + /// JWKS or a CA bundle, may also be readable by group and others. + #[cfg_attr(feature = "schema", schemars(extend("pattern" = "^/")))] + pub root: PathBuf, +} + +impl StrictSecretProvidersConfig { + /// The same providers as a runtime block with no `mountPolicy`, which is + /// how every check and the resolver read them. + #[must_use] + pub fn as_runtime_block(&self) -> SecretProvidersConfig { + SecretProvidersConfig { + file: self + .file + .as_ref() + .map(|file| FileSecretProviderConfig::new(file.root.clone())), + environment: self.environment.clone(), + } + } + + /// See [`SecretProvidersConfig::check`]. + pub fn check(&self) -> Result<(), ConfigBlockError> { + self.as_runtime_block().check() + } + + /// See [`SecretProvidersConfig::check_reference`]. + pub fn check_reference(&self, field: &str, raw: &str) -> Result<(), ConfigBlockError> { + self.as_runtime_block().check_reference(field, raw) + } + + /// A resolver with the strict file rule. See [`SecretProvidersConfig::resolver`]. + pub fn resolver( + &self, + witness: Option<&DevelopmentWitness>, + ) -> Result { + self.as_runtime_block().resolver(witness) } } @@ -247,6 +387,20 @@ pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretErro check.code(), check.suggested_action() ), + SecretError::UnsafePublicDocument(check) => format!( + "{} ({}). {}", + check.public_message(), + check.code(), + check.public_suggested_action() + ), + SecretError::PrivateKeyInPublicDocument => format!( + "the public document holds a PEM private key block. {}", + error.suggested_action() + ), + SecretError::PublicDocumentNotText => format!( + "the public document is not UTF-8 text. {}", + error.suggested_action() + ), SecretError::Read => "the secret could not be read".to_owned(), SecretError::InvalidValue => format!( "the secret value must be non-empty text of at most {MAX_SECRET_BYTES} bytes \ @@ -284,6 +438,69 @@ pub struct DatabaseConfig { pub transport: Option>, } +/// One secret reference of a database block, and how a tool reads it: the CA +/// bundle is a public document, and each URL is a secret. A provisioning tool +/// names the member it reads, so the read follows the member and a renamed key +/// cannot fall back to the wrong rule. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DatabaseMember { + RuntimeUrl, + MigrationUrl, + CaBundle, +} + +impl DatabaseMember { + /// The member's key in the database block. + #[must_use] + pub fn key(self) -> &'static str { + match self { + Self::RuntimeUrl => "runtimeUrlRef", + Self::MigrationUrl => "migrationUrlRef", + Self::CaBundle => "caBundleRef", + } + } + + /// Read the member's reference with the rule the member takes. A CA + /// bundle is a public document read as text, so bytes that are not UTF-8 + /// are [`SecretError::PublicDocumentNotText`]. Its certificates are + /// parsed where the connection is configured, not here. + pub fn read( + self, + resolver: &SecretResolver, + reference: &str, + ) -> Result { + match self { + Self::CaBundle => utf8_text(resolver.resolve_public_document(reference)?), + Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve(reference), + } + } + + /// [`Self::read`] for a parsed reference. + pub fn read_reference( + self, + resolver: &SecretResolver, + reference: &SecretReference, + ) -> Result { + match self { + Self::CaBundle => utf8_text(resolver.resolve_public_document_reference(reference)?), + Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve_reference(reference), + } + } +} + +fn utf8_text(document: ProtectedSecret) -> Result { + if std::str::from_utf8(document.expose_secret()).is_err() { + return Err(SecretError::PublicDocumentNotText); + } + Ok(document) +} + +impl fmt::Display for DatabaseMember { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.key()) + } +} + impl fmt::Debug for DatabaseConfig { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 328904befa..472d72c968 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -78,6 +78,130 @@ fn the_resolver_enables_exactly_the_declared_providers() { )); } +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_reads_as_a_public_document_and_a_url_as_a_secret() { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir().expect("tempdir"); + let canonical = std::fs::canonicalize(root.path()).expect("canonical root"); + let shared = canonical.join("shared"); + std::fs::write(&shared, b"-----BEGIN CERTIFICATE-----\n").expect("write file"); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o644)).expect("set 0644"); + let resolver = SecretProvidersConfig { + file: Some(FileSecretProviderConfig::new(canonical)), + environment: None, + } + .resolver(None) + .expect("production resolver"); + + assert_eq!(DatabaseMember::CaBundle.key(), "caBundleRef"); + assert_eq!(DatabaseMember::MigrationUrl.to_string(), "migrationUrlRef"); + assert!(DatabaseMember::CaBundle + .read(&resolver, "secret:file/shared") + .is_ok()); + let reference = SecretReference::parse("secret:file/shared").unwrap(); + assert!(DatabaseMember::CaBundle + .read_reference(&resolver, &reference) + .is_ok()); + for member in [DatabaseMember::RuntimeUrl, DatabaseMember::MigrationUrl] { + assert_eq!( + member.read(&resolver, "secret:file/shared").unwrap_err(), + SecretError::UnsafeFile(crate::SecretFileCheck::WorldReadable) + ); + assert_eq!( + member.read_reference(&resolver, &reference).unwrap_err(), + SecretError::UnsafeFile(crate::SecretFileCheck::WorldReadable) + ); + } +} + +/// A resolver over a fresh root holding each `(name, bytes)` as a 0644 file, +/// the mode a public document may have whatever the process umask. +#[cfg(unix)] +fn public_documents(files: &[(&str, &[u8])]) -> (tempfile::TempDir, SecretResolver) { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir().expect("tempdir"); + let canonical = std::fs::canonicalize(root.path()).expect("canonical root"); + for (name, bytes) in files { + let path = canonical.join(name); + std::fs::write(&path, bytes).expect("write file"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).expect("0644"); + } + let resolver = SecretProvidersConfig { + file: Some(FileSecretProviderConfig::new(canonical)), + environment: None, + } + .resolver(None) + .expect("production resolver"); + (root, resolver) +} + +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_that_is_not_text_is_refused_as_not_text() { + let (_root, resolver) = public_documents(&[("binary", &[0xff, 0xfe, 0xfd])]); + let reference = SecretReference::parse("secret:file/binary").unwrap(); + assert_eq!( + DatabaseMember::CaBundle + .read(&resolver, "secret:file/binary") + .unwrap_err(), + SecretError::PublicDocumentNotText + ); + assert_eq!( + DatabaseMember::CaBundle + .read_reference(&resolver, &reference) + .unwrap_err(), + SecretError::PublicDocumentNotText + ); + let described = describe_secret_failure( + "database.caBundleRef", + "secret:file/binary", + &SecretError::PublicDocumentNotText, + ); + assert!(described.contains("not UTF-8 text"), "{described}"); +} + +#[cfg(unix)] +#[test] +fn a_database_ca_bundle_accepts_every_text_shape_of_pem() { + let certificate = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + let bom = [b"\xEF\xBB\xBF".as_slice(), certificate.as_bytes()].concat(); + let crlf = certificate.replace('\n', "\r\n"); + let several = format!("issuer comment\n{certificate}{certificate} \n"); + let (_root, resolver) = public_documents(&[ + ("bom", &bom), + ("crlf", crlf.as_bytes()), + ("several", several.as_bytes()), + ]); + for name in ["bom", "crlf", "several"] { + assert!( + DatabaseMember::CaBundle + .read(&resolver, &format!("secret:file/{name}")) + .is_ok(), + "{name}" + ); + } +} + +#[cfg(unix)] +#[test] +fn a_private_key_is_refused_before_the_text_rule() { + let key = [ + &[0xff, 0xfe][..], + b"\n-----BEGIN PRIVATE KEY-----\nMII\n-----END PRIVATE KEY-----\n", + ] + .concat(); + let (_root, resolver) = public_documents(&[("key", &key)]); + assert_eq!( + DatabaseMember::CaBundle + .read(&resolver, "secret:file/key") + .unwrap_err(), + SecretError::PrivateKeyInPublicDocument + ); +} + #[cfg(unix)] #[test] fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_development_witness() { @@ -91,7 +215,7 @@ fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_develop .expect("set 0644"); let config = SecretProvidersConfig { - file: Some(FileSecretProviderConfig { root: canonical }), + file: Some(FileSecretProviderConfig::new(canonical)), environment: None, }; @@ -128,6 +252,70 @@ fn secret_providers_resolver_relaxes_secret_file_permissions_only_with_a_develop assert_eq!(secret.expose_secret(), b"shared-secret-canary"); } +#[test] +fn compose_native_mount_is_an_explicit_production_setting_at_its_member() { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Runtime { + secret_providers: SecretProvidersConfig, + } + + let loader = crate::RuntimeConfigLoader::new( + crate::RuntimeEnvelope { + api_version: "registry.registrystack.org/example/v1alpha1", + kind: "ExampleRuntimeConfig", + }, + crate::DeclaredPosture { + posture: crate::Posture::Production, + source: crate::PostureSource::Flag, + }, + ); + let strict = "apiVersion: registry.registrystack.org/example/v1alpha1\nkind: ExampleRuntimeConfig\nsecretProviders:\n file:\n root: /run/secrets\n"; + let omitted = loader.parse_str::(strict, |_| None).unwrap(); + assert!(omitted.posture.explicit_settings().is_empty()); + assert!(!omitted + .config + .secret_providers + .resolver(None) + .unwrap() + .admits_compose_native_mounts()); + + let explicit = format!("{strict} mountPolicy: compose-native\n"); + let loaded = loader.parse_str::(&explicit, |_| None).unwrap(); + assert!(loaded.development.is_none()); + loaded.config.secret_providers.check().unwrap(); + // The member, and only the member, switches the resolver to the Compose rule. + assert!(loaded + .config + .secret_providers + .resolver(None) + .unwrap() + .admits_compose_native_mounts()); + let [notice] = loaded.posture.explicit_settings() else { + panic!("one explicit setting is recorded"); + }; + assert_eq!( + notice.setting.code, + "platform.posture.compose-native-secret-mount" + ); + assert_eq!( + notice.pointer.as_deref(), + Some("/secretProviders/file/mountPolicy") + ); + assert!(notice.position.is_some()); + assert!(loaded + .posture + .ready_member() + .get("explicitProductionSettings") + .is_none()); + assert!(loader + .parse_str::( + &explicit.replace("compose-native", "allow-world-readable"), + |_| None + ) + .is_err()); +} + #[test] fn database_debug_redacts_every_reference() { let database: DatabaseConfig = read_block( diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index e2fc8a6ddd..a2704968ff 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -38,13 +38,14 @@ pub use blocks::{ is_sha256_label, plaintext_host_addresses, published_http_issuer_setting, resolve_database_host, url_hook_destinations, AdmittedClients, AttachmentVerifierConfig, AttemptTimeoutMilliseconds, AuditKeyConfig, AuditKeyCustody, CheckedHost, ConfigBlockError, - ConfigBlockErrorKind, DatabaseConfig, DatabaseHost, DatabaseTransport, DatabaseTransportError, - EnvironmentSecretProviderConfig, FileSecretProviderConfig, HostResolver, InsecureHttp, - JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, - ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, - PackageClients, PackageClientsError, PackageConfig, PackageDigestMismatch, PermittedTransport, - PrivateListenerConfig, SecretProvidersConfig, TaskGrantStatusConfig, TlsTermination, - UrlHookDestinationConfig, DEFAULT_ATTEMPT_TIMEOUT_MILLISECONDS, + ConfigBlockErrorKind, DatabaseConfig, DatabaseHost, DatabaseMember, DatabaseTransport, + DatabaseTransportError, EnvironmentSecretProviderConfig, FileSecretProviderConfig, + HostResolver, InsecureHttp, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, + MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, + OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, + PackageDigestMismatch, PermittedTransport, PrivateListenerConfig, SecretProvidersConfig, + StrictFileSecretProviderConfig, StrictSecretProvidersConfig, TaskGrantStatusConfig, + TlsTermination, UrlHookDestinationConfig, DEFAULT_ATTEMPT_TIMEOUT_MILLISECONDS, DEFAULT_HOOK_ATTEMPT_TIMEOUT_MILLISECONDS, DEFAULT_HOOK_MAXIMUM_ATTEMPTS, DEFAULT_TASK_GRANT_STATUS_PATH, DEFAULT_TASK_GRANT_STATUS_SCOPE, MAX_ASSERTION_ISSUERS_PER_CLIENT, MAX_ASSERTION_ISSUER_BYTES, MAX_ASSERTION_ISSUER_CLIENTS, @@ -82,11 +83,12 @@ pub use package::{ }; pub use posture::{ collect_development_settings, collect_posture_settings, declared, declared_from, - declared_from_with_production_alias, declared_with_production_alias, has_denied_warnings, - CollectedSettings, DeclaredPosture, DevelopmentClass, DevelopmentOnlyRefused, - DevelopmentSetting, DevelopmentWitness, ExplicitClass, ExplicitProductionSetting, - FoundExplicitSetting, FoundSetting, Gated, Posture, PostureError, PostureReport, PostureSource, - SettingOrigin, Stated, DEVELOPMENT, POSTURE_ENV, + declared_from_with_production_alias, declared_with_production_alias, explicit_setting_notice, + has_denied_warnings, CollectedSettings, DeclaredPosture, DevelopmentClass, + DevelopmentOnlyRefused, DevelopmentSetting, DevelopmentWitness, ExplicitClass, + ExplicitProductionSetting, ExplicitSettingLine, FoundExplicitSetting, FoundSetting, Gated, + Posture, PostureError, PostureReport, PostureSource, SettingOrigin, Stated, DEVELOPMENT, + POSTURE_ENV, }; pub use secrets::{ validate_secret_root, ProtectedSecret, SecretError, SecretFileCheck, SecretProvider, diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index 22065ef648..9b5ab0dcd3 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -442,6 +442,89 @@ pub struct ExplicitProductionSetting { pub summary: &'static str, } +/// One explicit production setting an operator stated, as a `check` report +/// lists it: a setting valid in every posture that relaxes something and is +/// worth a reviewer's attention. It is a list of facts, not a diagnostic, so +/// `--deny-warnings` is unaffected. The summary is value-free. +/// +/// `file` names the document `pointer` refers to, such as the runtime file or +/// the package, and is left out when absent. `pointer`, `line` and `column` +/// are left out when unknown. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ExplicitSettingLine { + pub code: String, + pub file: Option, + pub pointer: Option, + pub line: Option, + pub column: Option, + pub summary: String, +} + +impl ExplicitSettingLine { + /// The line a `check` report lists for `found`. `file` names the document + /// the pointer refers to: the runtime file, or the package for a setting + /// found there. + #[must_use] + pub fn from_found(found: &FoundExplicitSetting, file: Option<&str>) -> Self { + Self { + code: found.setting.code.to_owned(), + file: file.map(ToOwned::to_owned), + pointer: found.pointer.clone(), + line: found.position.map(|position| position.line), + column: found.position.map(|position| position.column), + summary: found.setting.summary.to_owned(), + } + } + + /// The one line a command prints for this setting: see + /// [`explicit_setting_notice`]. + #[must_use] + pub fn notice(&self) -> String { + explicit_setting_notice( + &self.code, + self.pointer.as_deref().unwrap_or_default(), + &self.summary, + ) + } +} + +impl Serialize for ExplicitSettingLine { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeMap as _; + + let mut map = serializer.serialize_map(None)?; + map.serialize_entry("code", &self.code)?; + if let Some(file) = &self.file { + map.serialize_entry("file", file)?; + } + if let Some(pointer) = &self.pointer { + map.serialize_entry("pointer", pointer)?; + } + if let Some(line) = self.line { + map.serialize_entry("line", &line)?; + } + if let Some(column) = self.column { + map.serialize_entry("column", &column)?; + } + map.serialize_entry("summary", &self.summary)?; + map.end() + } +} + +/// The one line every command prints for an explicit production setting: +/// the code, where it is stated and what it relaxes. The summary starts a +/// sentence here, so its first letter is capitalised whatever its authored +/// case. +#[must_use] +pub fn explicit_setting_notice(code: &str, location: &str, summary: &str) -> String { + let mut rest = summary.chars(); + let summary: String = rest + .next() + .map(|first| first.to_uppercase().chain(rest).collect()) + .unwrap_or_default(); + format!("Explicit production setting {code} at {location}. {summary}.") +} + /// An [`ExplicitProductionSetting`] found in a process's configuration. #[derive(Clone, Debug)] pub struct FoundExplicitSetting { @@ -451,6 +534,19 @@ pub struct FoundExplicitSetting { pub origin: SettingOrigin, } +impl FoundExplicitSetting { + /// The one line a command prints for this setting, as the check commands + /// print it: see [`explicit_setting_notice`]. + #[must_use] + pub fn notice(&self) -> String { + explicit_setting_notice( + self.setting.code, + self.pointer.as_deref().unwrap_or_default(), + self.setting.summary, + ) + } +} + /// What one decode found: the development-only settings a [`Gated`] recorded /// and the explicit production settings a [`Stated`] recorded. #[derive(Clone, Debug, Default)] @@ -559,6 +655,15 @@ impl PostureReport { &self.explicit } + /// [`FoundExplicitSetting::notice`] for each explicit production setting. + #[must_use] + pub fn explicit_setting_notices(&self) -> Vec { + self.explicit + .iter() + .map(FoundExplicitSetting::notice) + .collect() + } + /// The one decision. Production refuses every recorded setting and /// development accepts and lists them, under the same codes. #[must_use] diff --git a/crates/registry-platform-config/src/posture_tests.rs b/crates/registry-platform-config/src/posture_tests.rs index 8f9e097012..61139e852e 100644 --- a/crates/registry-platform-config/src/posture_tests.rs +++ b/crates/registry-platform-config/src/posture_tests.rs @@ -790,3 +790,22 @@ fn deny_warnings_refuses_only_unaccepted_warnings_outside_posture() { assert!(!has_denied_warnings(&[platform, product, accepted])); assert!(has_denied_warnings(&[ordinary])); } + +#[test] +fn a_notice_starts_its_summary_as_a_sentence() { + static LOWERCASE: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.example", + key: "example", + summary: "admits an example. Other values stay refused", + }; + let found = FoundExplicitSetting { + setting: &LOWERCASE, + pointer: Some("/example".to_owned()), + position: None, + origin: SettingOrigin::RuntimeFile, + }; + assert_eq!( + found.notice(), + "Explicit production setting platform.posture.example at /example. Admits an example. Other values stay refused." + ); +} diff --git a/crates/registry-platform-config/src/schema.rs b/crates/registry-platform-config/src/schema.rs index d5bdddbe88..2bd0eb004a 100644 --- a/crates/registry-platform-config/src/schema.rs +++ b/crates/registry-platform-config/src/schema.rs @@ -6,7 +6,7 @@ use crate::blocks::{ AttachmentVerifierConfig, AuditKeyConfig, DatabaseConfig, JwksSource, ListenerConfig, MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, PackageConfig, PrivateListenerConfig, SecretProvidersConfig, - TaskGrantStatusConfig, UrlHookDestinationConfig, + StrictSecretProvidersConfig, TaskGrantStatusConfig, UrlHookDestinationConfig, }; use crate::caller_issuers::{ AccessProfileClients, AllowedClients, CallerIssuerCore, CallerIssuers, ClientList, @@ -22,6 +22,7 @@ pub const SHARED_BLOCKS_SCHEMA_FILE: &str = "runtime-config-blocks.schema.json"; #[allow(dead_code)] struct SharedBlocks { secret_providers: SecretProvidersConfig, + strict_secret_providers: StrictSecretProvidersConfig, database: DatabaseConfig, jwks_source: JwksSource, package: PackageConfig, diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index b259994bea..08a3475e4d 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -193,6 +193,17 @@ pub enum SecretError { Unavailable, #[error("the referenced secret file is unsafe")] UnsafeFile(SecretFileCheck), + /// A public document's file failed a check. The check is the one a + /// secret file fails, worded for a document anyone may read. + #[error("the referenced public document file is unsafe")] + UnsafePublicDocument(SecretFileCheck), + /// A public document holds a PEM private key block. + #[error("the referenced public document holds a private key")] + PrivateKeyInPublicDocument, + /// A public document read as text, such as a CA bundle of PEM + /// certificates, holds bytes that are not UTF-8. + #[error("the referenced public document is not UTF-8 text")] + PublicDocumentNotText, #[error("the referenced secret could not be read")] Read, #[error("the referenced secret value is invalid")] @@ -218,6 +229,13 @@ impl SecretError { "Create the secret under the configured provider, or correct the name." } Self::UnsafeFile(check) => check.suggested_action(), + Self::UnsafePublicDocument(check) => check.public_suggested_action(), + Self::PrivateKeyInPublicDocument => { + "Put only certificates or public keys in the document, and keep the private key in its own secret file." + } + Self::PublicDocumentNotText => { + "Store the document as UTF-8 text, such as PEM certificates." + } Self::Read => "Check that the secret can be read by the runtime user.", Self::InvalidValue => { "Store a non-empty value of at most 64 KiB, without NUL bytes unless the secret is a binary key." @@ -326,6 +344,51 @@ impl SecretFileCheck { } } + /// [`Self::message`] for a public document such as a JWKS or a CA bundle. + #[must_use] + pub const fn public_message(self) -> &'static str { + match self { + Self::LinkLeavesRoot => { + "the public document is reached through a link that leaves secretProviders.file.root" + } + Self::TooManyLinks => "the public document is reached through more than 8 links", + Self::CannotOpen => "the runtime user cannot open the public document", + Self::NotRegular => "the public document is not a regular file", + Self::HardLinked => "the public document has more than one hard link", + Self::Owner => "the public document is owned by neither the runtime user nor root", + Self::WorldWritable => { + "users outside the file's owner and group can write the public document" + } + Self::WorldReadable | Self::GroupAccess => "the public document's group can write or execute it", + Self::ModeBits => { + "the public document has an execute, setuid, setgid or sticky bit, or its owner cannot read it" + } + } + } + + /// [`Self::suggested_action`] for a public document: anyone may read it, + /// so only who can change it matters. + #[must_use] + pub const fn public_suggested_action(self) -> &'static str { + match self { + Self::LinkLeavesRoot + | Self::TooManyLinks + | Self::NotRegular + | Self::HardLinked => self.suggested_action(), + Self::CannotOpen => { + "Let the runtime user read the file, for example mode 0644, or 0444 owned by root." + } + Self::Owner => "Give the file to the runtime user or to root.", + Self::WorldWritable => "Remove write access for others (chmod o-w).", + Self::WorldReadable | Self::GroupAccess => { + "Remove group write and execute (chmod g-wx)." + } + Self::ModeBits => { + "Clear the execute, setuid, setgid and sticky bits, and let the owner read the file, for example mode 0644." + } + } + } + /// Whether a development process loads the file with a warning instead of /// refusing it. Production refuses every check. #[must_use] @@ -393,12 +456,25 @@ impl fmt::Debug for ProtectedSecret { /// The production rule accepts a file owned by the runtime user with mode 0400 /// or 0600, and a root-owned file with no bit outside 0640 when the runtime is /// not root. [`Self::in_development`] relaxes the read and mode-bit checks to a -/// warning for a process that declared development. +/// warning for a process that declared development. The file provider's +/// explicit `mountPolicy: compose-native` setting also accepts a root-owned, +/// single-link regular file with mode exactly 0444. A public document read +/// through [`Self::resolve_public_document`] skips only the group and world +/// read checks. #[derive(Debug)] pub struct SecretResolver { providers: BTreeSet, file_root: PathBuf, + file_access: FileAccess, +} + +#[derive(Clone, Copy, Debug, Default)] +struct FileAccess { development: bool, + compose_native: bool, + /// A public document such as a JWKS or a CA bundle: anyone may read it, + /// so only who can change it is checked. + public_document: bool, } impl SecretResolver { @@ -411,7 +487,7 @@ impl SecretResolver { Self { providers: BTreeSet::new(), file_root: PathBuf::new(), - development: false, + file_access: FileAccess::default(), } } @@ -430,22 +506,48 @@ impl SecretResolver { Ok(Self { providers, file_root, - development: false, + file_access: FileAccess::default(), }) } /// Apply the development rule when the process holds the witness. Without - /// it the resolver keeps the production rule, so a production path cannot - /// relax the rule by mistake. + /// it the resolver keeps the configured production rule. #[must_use] pub fn in_development(mut self, witness: Option<&DevelopmentWitness>) -> Self { - self.development = witness.is_some(); + self.file_access.development = witness.is_some(); + self + } + + pub(crate) fn with_compose_native_mounts(mut self) -> Self { + self.file_access.compose_native = true; self } + /// Whether this resolver admits root-owned mode 0444 Compose mounts, so a + /// test can prove which configurations switch the rule on. + #[cfg(test)] + pub(crate) fn admits_compose_native_mounts(&self) -> bool { + self.file_access.compose_native + } + /// Run every check a read runs, without retaining the bytes. A check tool /// uses this to give the verdict the runtime would give. pub fn inspect_reference(&self, reference: &SecretReference) -> Result<(), SecretError> { + self.inspect_with(reference, self.file_access) + } + + /// [`Self::inspect_reference`] for a public document, with the rule + /// [`Self::resolve_public_document_reference`] applies. + pub fn inspect_public_document(&self, reference: &SecretReference) -> Result<(), SecretError> { + self.inspect_with(reference, self.public_access()) + .map_err(public_document_error) + } + + fn inspect_with( + &self, + reference: &SecretReference, + access: FileAccess, + ) -> Result<(), SecretError> { if !self.providers.contains(&reference.provider()) { return Err(SecretError::ProviderDisabled); } @@ -454,11 +556,50 @@ impl SecretResolver { .map(|_| ()) .ok_or(SecretError::Unavailable), SecretProvider::File => { - open_secret_file(&self.file_root, reference.name(), self.development).map(|_| ()) + open_secret_file(&self.file_root, reference.name(), access).map(|_| ()) } } } + /// Resolve a public document, such as a static JWKS or a PEM CA bundle, + /// named by a `secret:env/NAME` or `secret:file/name` reference. + /// + /// Public documents are not secrets: a file may be readable by group and + /// others, so a root-owned mode 0444 Compose mount loads with no setting. + /// Every other file check still applies: a single-link regular file owned + /// by root or the runtime user, with no group or world write and no + /// execute or special bit, reached by the root-confined walk. The caller + /// still parses and checks the document itself. + pub fn resolve_public_document(&self, reference: &str) -> Result { + let reference = SecretReference::parse(reference)?; + self.resolve_public_document_reference(&reference) + } + + /// [`Self::resolve_public_document`] for an already parsed reference. + pub fn resolve_public_document_reference( + &self, + reference: &SecretReference, + ) -> Result { + let document = validate_secret( + self.read_with(reference, self.public_access()) + .map_err(public_document_error)? + .0, + )?; + // A public document may be readable by everyone, so a private key + // staged in it by mistake is refused rather than loaded. + if holds_pem_private_key(document.expose_secret()) { + return Err(SecretError::PrivateKeyInPublicDocument); + } + Ok(document) + } + + fn public_access(&self) -> FileAccess { + FileAccess { + public_document: true, + ..self.file_access + } + } + /// Resolve one exact `secret:env/NAME` or `secret:file/name` reference. pub fn resolve(&self, reference: &str) -> Result { let reference = SecretReference::parse(reference)?; @@ -482,6 +623,14 @@ impl SecretResolver { pub fn resolve_binary_reference( &self, reference: &SecretReference, + ) -> Result { + self.read_with(reference, self.file_access) + } + + fn read_with( + &self, + reference: &SecretReference, + access: FileAccess, ) -> Result { if !self.providers.contains(&reference.provider()) { return Err(SecretError::ProviderDisabled); @@ -489,9 +638,7 @@ impl SecretResolver { let bytes = match reference.provider() { SecretProvider::Environment => read_environment(reference.name())?, - SecretProvider::File => { - read_secret_file(&self.file_root, reference.name(), self.development)? - } + SecretProvider::File => read_secret_file(&self.file_root, reference.name(), access)?, }; validate_binary_secret(bytes) } @@ -519,9 +666,9 @@ pub const MAX_SECRET_LINKS: usize = 8; fn read_secret_file( root: &Path, name: &str, - development: bool, + access: FileAccess, ) -> Result>, SecretError> { - read_bounded(open_secret_file(root, name, development)?) + read_bounded(open_secret_file(root, name, access)?) } /// What the rule looks at in an opened file. @@ -549,7 +696,7 @@ enum FileKind { fn judge( facts: Facts, euid: u32, - development: bool, + access: FileAccess, ) -> Result, SecretFileCheck> { use SecretFileCheck::{ GroupAccess, HardLinked, ModeBits, NotRegular, Owner, WorldReadable, WorldWritable, @@ -567,28 +714,56 @@ fn judge( if facts.mode & 0o002 != 0 { return Err(WorldWritable); } + if access.compose_native && facts.uid == 0 && facts.mode == 0o444 { + return Ok(Vec::new()); + } let own = facts.uid == euid; let mut failed = Vec::new(); - if facts.mode & 0o005 != 0 { - failed.push(WorldReadable); - } - let group_bits = if own { 0o070 } else { 0o030 }; - if facts.mode & group_bits != 0 { - failed.push(GroupAccess); - } - if facts.mode & 0o7100 != 0 || (own && facts.mode & 0o400 == 0) { - failed.push(ModeBits); + if access.public_document { + if facts.mode & 0o030 != 0 { + failed.push(GroupAccess); + } + if facts.mode & 0o7101 != 0 || (own && facts.mode & 0o400 == 0) { + failed.push(ModeBits); + } + } else { + if facts.mode & 0o005 != 0 { + failed.push(WorldReadable); + } + let group_bits = if own { 0o070 } else { 0o030 }; + if facts.mode & group_bits != 0 { + failed.push(GroupAccess); + } + if facts.mode & 0o7100 != 0 || (own && facts.mode & 0o400 == 0) { + failed.push(ModeBits); + } } - match (development, failed.first()) { + match (access.development, failed.first()) { (false, Some(check)) => Err(*check), _ => Ok(failed), } } +/// A file refusal from a public-document read names the public document. +fn public_document_error(error: SecretError) -> SecretError { + match error { + SecretError::UnsafeFile(check) => SecretError::UnsafePublicDocument(check), + other => other, + } +} + +/// Whether `bytes` hold an armored private key block of any kind: PKCS #8 +/// (encrypted or not), RSA, EC, DSA, OpenSSH or OpenPGP. +fn holds_pem_private_key(bytes: &[u8]) -> bool { + [&b"PRIVATE KEY-----"[..], &b"PRIVATE KEY BLOCK-----"[..]] + .iter() + .any(|label| bytes.windows(label.len()).any(|window| window == *label)) +} + /// Walk `name` from the root by openat steps, following only relative /// downward links, then judge the descriptor that will be read. #[cfg(unix)] -fn open_secret_file(root: &Path, name: &str, development: bool) -> Result { +fn open_secret_file(root: &Path, name: &str, access: FileAccess) -> Result { use rustix::{ fs::{Mode, OFlags}, io::Errno, @@ -652,12 +827,12 @@ fn open_secret_file(root: &Path, name: &str, development: bool) -> Result Result<(), SecretError> { +fn judge_file(file: &File, access: FileAccess) -> Result<(), SecretError> { use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _}; let metadata = file.metadata().map_err(|_| SecretError::Read)?; @@ -679,7 +854,7 @@ fn judge_file(file: &File, development: bool) -> Result<(), SecretError> { mode: metadata.permissions().mode() & 0o7777, nlink: metadata.nlink(), }; - match judge(facts, rustix::process::geteuid().as_raw(), development) { + match judge(facts, rustix::process::geteuid().as_raw(), access) { Err(check) => Err(SecretError::UnsafeFile(check)), Ok(warnings) => { for check in warnings { @@ -701,13 +876,13 @@ fn judge_file(file: &File, development: bool) -> Result<(), SecretError> { fn read_secret_file( root: &Path, name: &str, - development: bool, + access: FileAccess, ) -> Result>, SecretError> { - read_bounded(open_secret_file(root, name, development)?) + read_bounded(open_secret_file(root, name, access)?) } #[cfg(not(unix))] -fn open_secret_file(root: &Path, name: &str, _development: bool) -> Result { +fn open_secret_file(root: &Path, name: &str, _access: FileAccess) -> Result { let path = root.join(name); let metadata = std::fs::symlink_metadata(&path).map_err(|_| SecretError::Unavailable)?; if metadata.file_type().is_symlink() || !metadata.is_file() { diff --git a/crates/registry-platform-config/src/secrets_tests.rs b/crates/registry-platform-config/src/secrets_tests.rs index a09e5f8a0c..478956289b 100644 --- a/crates/registry-platform-config/src/secrets_tests.rs +++ b/crates/registry-platform-config/src/secrets_tests.rs @@ -88,18 +88,100 @@ fn the_decision_table_gives_one_answer_per_owner_mode_and_posture() { for (row, euid, uid, mode, kind, nlink, production, development) in rows { let f = facts(*kind, *uid, *mode, *nlink); assert_eq!( - observed(judge(f, *euid, false)), + observed(judge(f, *euid, FileAccess::default())), *production, "{row} in production" ); assert_eq!( - observed(judge(f, *euid, true)), + observed(judge( + f, + *euid, + FileAccess { + development: true, + ..FileAccess::default() + } + )), *development, "{row} in development" ); } } +#[test] +fn compose_native_adds_only_root_owned_single_link_mode_0444() { + use FileKind::{Directory, Regular}; + use Outcome::{Load, Refuse}; + const APP: u32 = 10001; + let access = FileAccess { + compose_native: true, + ..FileAccess::default() + }; + for (uid, mode, kind, nlink, expected) in [ + (0, 0o444, Regular, 1, Load), + (0, 0o440, Regular, 1, Load), + (APP, 0o400, Regular, 1, Load), + (APP, 0o444, Regular, 1, Refuse(WorldReadable)), + (10002, 0o444, Regular, 1, Refuse(Owner)), + (0, 0o644, Regular, 1, Refuse(WorldReadable)), + (0, 0o464, Regular, 1, Refuse(WorldReadable)), + (0, 0o446, Regular, 1, Refuse(WorldWritable)), + (0, 0o444, Regular, 2, Refuse(HardLinked)), + (0, 0o444, Directory, 1, Refuse(NotRegular)), + ] { + assert_eq!( + observed(judge(facts(kind, uid, mode, nlink), APP, access)), + expected + ); + } +} + +#[test] +fn a_public_document_drops_only_the_read_checks() { + use FileKind::{Directory, Regular}; + use Outcome::{Load, Refuse, Warn}; + const APP: u32 = 10001; + let production = FileAccess { + public_document: true, + ..FileAccess::default() + }; + let development = FileAccess { + development: true, + ..production + }; + #[rustfmt::skip] + let rows: &[(&str, u32, u32, FileKind, u64, Outcome, Outcome)] = &[ + ("compose JWKS", 0, 0o444, Regular, 1, Load, Load), + ("root 0644", 0, 0o644, Regular, 1, Load, Load), + ("root 0640", 0, 0o640, Regular, 1, Load, Load), + ("own 0444", APP, 0o444, Regular, 1, Load, Load), + ("own 0644", APP, 0o644, Regular, 1, Load, Load), + ("own 0400", APP, 0o400, Regular, 1, Load, Load), + ("group write", 0, 0o464, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("own group w", APP, 0o664, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("group exec", 0, 0o454, Regular, 1, Refuse(GroupAccess), Warn(&[GroupAccess])), + ("world exec", 0, 0o445, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("owner exec", APP, 0o544, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("setuid", 0, 0o4444, Regular, 1, Refuse(ModeBits), Warn(&[ModeBits])), + ("world write", 0, 0o446, Regular, 1, Refuse(WorldWritable), Refuse(WorldWritable)), + ("other owner", 10002, 0o444, Regular, 1, Refuse(Owner), Refuse(Owner)), + ("hard linked", 0, 0o444, Regular, 2, Refuse(HardLinked), Refuse(HardLinked)), + ("directory", 0, 0o555, Directory, 1, Refuse(NotRegular), Refuse(NotRegular)), + ]; + for (row, uid, mode, kind, nlink, in_production, in_development) in rows { + let f = facts(*kind, *uid, *mode, *nlink); + assert_eq!( + observed(judge(f, APP, production)), + *in_production, + "{row} in production" + ); + assert_eq!( + observed(judge(f, APP, development)), + *in_development, + "{row} in development" + ); + } +} + #[test] fn every_check_has_a_unique_code_a_value_free_message_and_a_full_stop_fix() { let all = [ @@ -216,6 +298,139 @@ mod filesystem { .map(|secret| secret.expose_secret().to_vec()) } + fn load_public(resolver: &SecretResolver, name: &str) -> Result, SecretError> { + resolver + .resolve_public_document(&format!("secret:file/{name}")) + .map(|document| document.expose_secret().to_vec()) + } + + #[test] + fn a_world_readable_public_document_loads_without_any_secret_setting() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "jwks.json", 0o444); + write(root.path(), "ca.pem", 0o644); + let resolver = resolver(root.path()); + assert_eq!( + load_public(&resolver, "jwks.json").expect("loads"), + b"file-canary" + ); + assert_eq!( + load_public(&resolver, "ca.pem").expect("loads"), + b"file-canary" + ); + let reference = SecretReference::parse("secret:file/jwks.json").expect("reference"); + resolver + .inspect_public_document(&reference) + .expect("the check gives the same verdict"); + assert_eq!( + load(&resolver, "jwks.json"), + Err(SecretError::UnsafeFile(WorldReadable)), + "a secret read keeps the strict rule" + ); + assert_eq!( + resolver.inspect_reference(&reference), + Err(SecretError::UnsafeFile(WorldReadable)) + ); + } + + #[test] + fn a_writable_or_escaping_public_document_is_refused() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "group-writable.json", 0o664); + write(root.path(), "world-writable.json", 0o666); + let outside = tempfile::tempdir().expect("outside"); + write(outside.path(), "jwks.json", 0o444); + symlink(outside.path().join("jwks.json"), root.path().join("escape")).expect("link"); + let resolver = resolver(root.path()); + assert_eq!( + load_public(&resolver, "group-writable.json"), + Err(SecretError::UnsafePublicDocument(GroupAccess)) + ); + assert_eq!( + load_public(&resolver, "world-writable.json"), + Err(SecretError::UnsafePublicDocument(WorldWritable)) + ); + // An absolute link is refused by the check that refuses it for a + // secret, worded for a public document. + match (load_public(&resolver, "escape"), load(&resolver, "escape")) { + ( + Err(SecretError::UnsafePublicDocument(public)), + Err(SecretError::UnsafeFile(secret)), + ) => assert_eq!(public, secret), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_public_document_refusal_gives_public_document_advice() { + let root = tempfile::tempdir().expect("root"); + write(root.path(), "group-writable.json", 0o664); + let error = load_public(&resolver(root.path()), "group-writable.json").unwrap_err(); + let SecretError::UnsafePublicDocument(check) = error else { + panic!("{error:?}"); + }; + for text in [ + check.public_message(), + check.public_suggested_action(), + error.suggested_action(), + ] { + assert!(!text.contains("secret file"), "{text}"); + assert!(!text.contains("0400 or 0600"), "{text}"); + } + let described = crate::describe_secret_failure("jwksSource.documentRef", "", &error); + assert!(described.contains("public document"), "{described}"); + assert!(!described.contains("0400 or 0600"), "{described}"); + } + + #[test] + fn a_public_document_holding_a_private_key_is_refused() { + let root = tempfile::tempdir().expect("root"); + for (name, block) in [ + ("pkcs8.pem", "PRIVATE KEY"), + ("rsa.pem", "RSA PRIVATE KEY"), + ("ec.pem", "EC PRIVATE KEY"), + ("encrypted.pem", "ENCRYPTED PRIVATE KEY"), + ("openssh.pem", "OPENSSH PRIVATE KEY"), + ("dsa.pem", "DSA PRIVATE KEY"), + ("pgp.asc", "PGP PRIVATE KEY BLOCK"), + ] { + let path = root.path().join(name); + fs::write( + &path, + format!( + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n\ + -----BEGIN {block}-----\nMIIE\n-----END {block}-----\n" + ), + ) + .expect("write"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("mode"); + } + let resolver = resolver(root.path()); + for name in [ + "pkcs8.pem", + "rsa.pem", + "ec.pem", + "encrypted.pem", + "openssh.pem", + "dsa.pem", + "pgp.asc", + ] { + assert_eq!( + load_public(&resolver, name), + Err(SecretError::PrivateKeyInPublicDocument), + "{name}" + ); + } + let bundle = root.path().join("ca.pem"); + fs::write( + &bundle, + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n", + ) + .expect("write"); + fs::set_permissions(&bundle, fs::Permissions::from_mode(0o644)).expect("mode"); + assert!(load_public(&resolver, "ca.pem").is_ok()); + } + #[test] fn a_relative_link_inside_the_root_loads_the_file_it_names() { let root = tempfile::tempdir().expect("root"); diff --git a/crates/registry-platform-config/src/service_compiler.rs b/crates/registry-platform-config/src/service_compiler.rs index 7c396dc900..384346f968 100644 --- a/crates/registry-platform-config/src/service_compiler.rs +++ b/crates/registry-platform-config/src/service_compiler.rs @@ -88,18 +88,23 @@ struct ManifestReference { #[serde(deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema), schemars(extend("minProperties" = 1)))] struct ProductReferences { + adapter: Option, breg: Option, casework: Option, coordinator: Option, + discovery: Option, + documents: Option, evidence: Option, messaging: Option, + render: Option, + scheduling: Option, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct NamedProjects { - /// Projects keyed by service product ID. BReg IDs form the generated client member names. + /// Projects keyed by project ID. In a service, BReg IDs form the generated client member names. #[cfg_attr( feature = "schema", schemars(schema_with = "local_index::", extend("minProperties" = 1)) @@ -111,7 +116,7 @@ struct NamedProjects { #[serde(deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] struct ProjectReference { - /// Directory containing the product's native project file, relative to this service file. + /// Directory containing the product's native project file, relative to the file that declares it. path: PathBuf, } @@ -130,6 +135,12 @@ pub fn service_schema() -> schemars::Schema { schemars::schema_for!(ServiceFile) } +/// The product inventory mapping shared by `service.yaml` and `dev.yaml`. +#[cfg(feature = "schema")] +pub fn product_inventory_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + generator.subschema_for::() +} + #[cfg(feature = "schema")] fn roles_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { let mut roles = local_index::(generator); @@ -287,7 +298,14 @@ pub fn plan(file: &Path, options: Options<'_>) -> Result { let settings = Reader::new(path.display().to_string()) .with_hook(&mut AuthoredExpressions) .read(&read(&path)?, &Expect::one(&DEV_FORMAT))?; - let projection = project_dev(root, &settings, &products, doc)?; + let projection = if settings.span_of("/products").is_none() { + project_dev(root, &settings, &products, doc)? + } else if products.is_empty() { + let entries = dev_inventory(root, &settings)?; + project_dev(root, &settings, &entries, &settings)? + } else { + return Err(two_inventories(&settings, doc)); + }; (Some(root.to_owned()), Some(projection.native)) } None => (None, None), @@ -315,14 +333,16 @@ struct ServiceDocument { } fn read_service(file: &Path, workspace: Option<&Path>) -> Result { - let file = file.canonicalize().map_err(|_| unreadable(file))?; + // Refusals name the path as written, never where a link resolves. + let authored = file; + let file = file.canonicalize().map_err(|_| unreadable(authored))?; let directory = file.parent().ok_or_else(|| unreadable(&file))?; let workspace = match workspace { Some(root) => root.canonicalize().map_err(|_| unreadable(root))?, None => directory.to_owned(), }; if !file.starts_with(&workspace) || !workspace.is_dir() { - return Err(unreadable(&file)); + return Err(unreadable(authored)); } let decoded = Reader::new(file.display().to_string()) .with_hook(&mut AuthoredExpressions) @@ -340,13 +360,42 @@ fn read_service(file: &Path, workspace: Option<&Path>) -> Result Result<(Document, Vec), Report> { - let ServiceDocument { +/// The one product inventory of a development directory: the `products` of +/// its `dev.yaml`, or else those of a sibling `service.yaml`. Returns the +/// document that declares the inventory and its entries. +fn development_inventory( + root: &Path, + settings: &Document, +) -> Result<(Document, Vec), Report> { + let service_file = root.join("service.yaml"); + let service = service_file + .exists() + .then(|| read_service(&service_file, Some(root))) + .transpose()?; + if settings.span_of("/products").is_some() { + if let Some(service) = service + .as_ref() + .filter(|service| service.decoded.value.products.is_some()) + { + return Err(two_inventories(settings, &service.decoded.document)); + } + return Ok((settings.clone(), dev_inventory(root, settings)?)); + } + let Some(ServiceDocument { file, workspace, decoded, .. - } = read_service(&root.join("service.yaml"), Some(root))?; + }) = service + else { + return Err(problem( + settings, + "rstack.service.projects", + "/products", + "The development plan needs product projects.", + "Declare the native products to start under products in dev.yaml.", + )); + }; let directory = file .parent() .expect("a readable service file has a directory"); @@ -356,23 +405,66 @@ fn development_inventory(root: &Path) -> Result<(Document, Vec), Report "rstack.service.projects", "/products", "The development plan needs product projects.", - "Declare the native products to start in service.yaml.", + "Declare the native products to start in dev.yaml or service.yaml.", ) })?; let entries = products(references, &decoded.document, directory, &workspace)?; Ok((decoded.document, entries)) } +/// The products declared in development settings, resolved against their +/// directory. +fn dev_inventory(root: &Path, settings: &Document) -> Result, Report> { + if settings + .to_json_value() + .pointer("/products") + .is_some_and(Value::is_array) + { + return Err(problem( + settings, + "rstack.dev.products-list", + "/products", + "The development products are a mapping of product kinds, not a list.", + "Write each product as products..projects..path for breg, coordinator and evidence, or products..path for every other kind, and move its audience to audiences..", + )); + } + let workspace = root.canonicalize().map_err(|_| unreadable(root))?; + let references = settings.decode_at::("/products")?; + products(references, settings, &workspace, &workspace) +} + +fn two_inventories(settings: &Document, service: &Document) -> Report { + let mut report = problem( + settings, + "rstack.service.dev-products", + "/products", + "The service file already declares the development products.", + "Declare the products in one file: remove them from these development settings, or from service.yaml.", + ); + if let Some(diagnostic) = report.diagnostics_mut().first_mut() { + service.add_related_value(diagnostic, "/products", "the service file's products"); + } + report +} + +fn read_settings(root: &Path) -> Result { + let file = root.join("dev.yaml"); + Reader::new(file.display().to_string()) + .with_hook(&mut AuthoredExpressions) + .read(&read(&file)?, &Expect::one(&DEV_FORMAT)) +} + /// The native component kinds the launcher needs to select a development host. pub fn development_product_kinds(root: &Path) -> Result, Report> { - let (_, entries) = development_inventory(root)?; + let (_, entries) = development_inventory(root, &read_settings(root)?)?; Ok(entries.into_iter().map(|entry| entry.product).collect()) } -/// Apply the service beside dev.yaml while leaving native dev validation to its runner. +/// 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 { - let (service, entries) = development_inventory(root)?; - project_dev(root, settings, &entries, &service) + let (inventory, entries) = development_inventory(root, settings)?; + project_dev(root, settings, &entries, &inventory) } fn products( @@ -424,8 +516,13 @@ fn products( } } for (kind, manifest, reference) in [ + ("adapter", "project.yaml", references.adapter), ("casework", "casework.yaml", references.casework), + ("discovery", "origins.yaml", references.discovery), + ("documents", "documents.yaml", references.documents), ("messaging", "messaging.yaml", references.messaging), + ("render", "render.yaml", references.render), + ("scheduling", "scheduling.yaml", references.scheduling), ] { if let Some(reference) = reference { let source = format!("/products/{kind}/path"); @@ -577,7 +674,7 @@ pub struct DevelopmentPlan { } pub struct DevelopmentSources { - service: Document, + inventory: Document, products: Vec, } @@ -587,10 +684,10 @@ struct ProductSource { } impl DevelopmentSources { - /// Locate a native plan field in one of the two authored documents. + /// Locate a native plan field in the settings or the inventory document. pub fn locate<'a>(&'a self, settings: &'a Document, path: &'a str) -> (&'a Document, &'a str) { if path == "/products" { - return (&self.service, path); + return (&self.inventory, path); } if let Some(rest) = path.strip_prefix("/products/") { let (index, field) = rest.split_once('/').unwrap_or((rest, "")); @@ -602,7 +699,7 @@ impl DevelopmentSources { return if field == "audience" { (settings, &source.audience) } else { - (&self.service, &source.project) + (&self.inventory, &source.project) }; } } @@ -614,24 +711,15 @@ fn project_dev( root: &Path, doc: &Document, products: &[Product], - service: &Document, + inventory: &Document, ) -> Result { if products.is_empty() { return Err(problem( - service, + inventory, "rstack.service.projects", "/products", "The development plan needs product projects.", - "Declare the native products to start in service.yaml.", - )); - } - if doc.span_of("/products").is_some() { - return Err(problem( - doc, - "rstack.service.dev-products", - "/products", - "The service file supplies the development products.", - "Remove products from the development settings and give each service product an audience.", + "Declare the native products to start in dev.yaml or service.yaml.", )); } let mut audiences = doc.decode_at::>("/audiences")?; @@ -641,7 +729,7 @@ fn project_dev( for product in products { if !kinds.insert(product.product) { return Err(problem( - service, + inventory, "rstack.service.dev-product", &product.source, "The development runner accepts one project per product kind.", @@ -650,7 +738,7 @@ fn project_dev( } let relative = product.project.strip_prefix(root).map_err(|_| { problem( - service, + inventory, "rstack.service.dev-root", &product.source, "The development runner requires project paths inside the development directory.", @@ -667,8 +755,8 @@ fn project_dev( doc, "rstack.service.dev-audience", "/audiences", - "A service product needs a development audience.", - "Set audiences for all declared service product IDs.", + "A development product needs an audience.", + "Set audiences for all declared product IDs.", )); }; native_products @@ -683,8 +771,8 @@ fn project_dev( doc, "rstack.service.dev-audience", &format!("/audiences/{}", extra.as_str()), - "A development audience names an unknown service product.", - "Remove the audience or add its product to the service file.", + "A development audience names an unknown product.", + "Remove the audience or add its product to the inventory.", )); } let mut dev = doc.to_json_value(); @@ -696,7 +784,7 @@ fn project_dev( Ok(DevelopmentPlan { native: dev, sources: DevelopmentSources { - service: service.clone(), + inventory: inventory.clone(), products: sources, }, }) @@ -805,3 +893,6 @@ fn problem(doc: &Document, code: &str, pointer: &str, message: &str, next: &str) }); doc.report_with([diagnostic]) } + +#[cfg(test)] +mod tests; diff --git a/crates/registry-platform-config/src/service_compiler/tests.rs b/crates/registry-platform-config/src/service_compiler/tests.rs new file mode 100644 index 0000000000..904b9d6ade --- /dev/null +++ b/crates/registry-platform-config/src/service_compiler/tests.rs @@ -0,0 +1,215 @@ +use super::*; + +const DEV_HEADER: &str = "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: https://issuer.example.test +journeyFile: dev-journeys.yaml +"; + +const SERVICE_HEADER: &str = + "apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1\nkind: RStackService\n"; + +const DEV_INVENTORY: &str = "products: + breg: + projects: + breg: {path: registry} + casework: {path: casework} +audiences: + breg: urn:example:registry + casework: urn:example:casework +"; + +struct Directory { + _directory: tempfile::TempDir, + root: PathBuf, +} + +impl Directory { + fn new(dev: &str) -> Self { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + for (project, manifest) in [("registry", "registry.yaml"), ("casework", "casework.yaml")] { + fs::create_dir(root.join(project)).unwrap(); + fs::write(root.join(project).join(manifest), "").unwrap(); + } + fs::write(root.join("dev.yaml"), format!("{DEV_HEADER}{dev}")).unwrap(); + Self { + _directory: directory, + root, + } + } + + fn service(self, body: &str) -> Self { + fs::write( + self.root.join("service.yaml"), + format!("{SERVICE_HEADER}{body}"), + ) + .unwrap(); + self + } + + fn settings(&self) -> Document { + let file = self.root.join("dev.yaml"); + Reader::new(file.display().to_string()) + .read(&fs::read(&file).unwrap(), &Expect::one(&DEV_FORMAT)) + .unwrap() + } + + fn plan(&self) -> Result { + development_plan(&self.root, &self.settings()) + } +} + +fn refusal(report: Report) -> Diagnostic { + let [diagnostic] = report.diagnostics() else { + panic!("expected exactly one diagnostic: {report}"); + }; + diagnostic.clone() +} + +fn source_file(diagnostic: &Diagnostic) -> String { + let file = &diagnostic + .source + .as_ref() + .expect("a located diagnostic") + .file; + Path::new(file) + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() +} + +#[test] +fn a_dev_owned_inventory_projects_native_products_without_a_service_file() { + let directory = Directory::new(DEV_INVENTORY); + let plan = directory.plan().expect("the dev inventory projects"); + assert_eq!( + plan.native["products"], + json!([ + {"product": "breg", "project": "registry", "audience": "urn:example:registry"}, + {"product": "casework", "project": "casework", "audience": "urn:example:casework"}, + ]) + ); + assert!(plan.native.get("audiences").is_none()); + assert_eq!( + development_product_kinds(&directory.root).unwrap(), + ["breg", "casework"] + ); +} + +#[test] +fn a_roles_only_service_file_leaves_the_inventory_with_dev() { + let directory = Directory::new(DEV_INVENTORY) + .service("roles:\n clerk:\n actorKind: service\n accessProfiles: {breg: [clerk]}\n"); + let plan = directory.plan().expect("the dev inventory projects"); + assert_eq!(plan.native["products"][0]["product"], "breg"); +} + +#[test] +fn a_sibling_service_inventory_still_supplies_the_products() { + let directory = Directory::new("audiences: {records: urn:example:registry}\n") + .service("products:\n breg:\n projects:\n records: {path: registry}\n"); + let plan = directory.plan().expect("the service inventory projects"); + assert_eq!( + plan.native["products"], + json!([{"product": "breg", "project": "registry", "audience": "urn:example:registry"}]) + ); + assert_eq!( + development_product_kinds(&directory.root).unwrap(), + ["breg"] + ); +} + +#[test] +fn two_inventories_in_one_directory_are_refused_at_the_dev_products() { + let directory = Directory::new(DEV_INVENTORY) + .service("products:\n breg:\n projects:\n breg: {path: registry}\n"); + let diagnostic = refusal(directory.plan().err().expect("two inventories")); + assert_eq!(diagnostic.code, "rstack.service.dev-products"); + assert_eq!(diagnostic.path, "/products"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); + let [related] = diagnostic.related.as_slice() else { + panic!("expected the service inventory as the related location"); + }; + assert!(related.file.ends_with("service.yaml"), "{}", related.file); + assert_eq!(related.path, "/products"); + assert_eq!(related.line, Some(4)); + assert!(development_product_kinds(&directory.root).is_err()); +} + +#[test] +fn the_retired_product_list_is_refused_with_the_mapping_named() { + let directory = Directory::new( + "products:\n - {product: breg, project: registry, audience: urn:example:registry}\naudiences: {breg: urn:example:registry}\n", + ); + let diagnostic = refusal(directory.plan().err().expect("the list is retired")); + assert_eq!(diagnostic.code, "rstack.dev.products-list"); + assert_eq!(diagnostic.path, "/products"); + assert_eq!( + diagnostic.suggested_action, + "Write each product as products..projects..path for breg, coordinator and evidence, or products..path for every other kind, and move its audience to audiences.." + ); + let source = diagnostic.source.as_ref().expect("a located diagnostic"); + assert_eq!((source.line, source.column), (Some(6), Some(3))); + assert_eq!(source_file(&diagnostic), "dev.yaml"); +} + +#[test] +fn a_directory_without_an_inventory_names_dev_yaml() { + let directory = Directory::new("audiences: {breg: urn:example:registry}\n"); + let diagnostic = refusal(directory.plan().err().expect("no inventory")); + assert_eq!(diagnostic.code, "rstack.service.projects"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); +} + +#[test] +fn dev_inventory_refusals_point_into_dev_yaml() { + let directory = Directory::new(&DEV_INVENTORY.replace("{path: registry}", "{path: missing}")); + let diagnostic = refusal(directory.plan().err().expect("missing project")); + assert_eq!(diagnostic.path, "/products/breg/projects/breg/path"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); + + let directory = + Directory::new(&DEV_INVENTORY.replace(" casework: urn:example:casework\n", "")); + let diagnostic = refusal(directory.plan().err().expect("missing audience")); + assert_eq!(diagnostic.code, "rstack.service.dev-audience"); + assert_eq!(diagnostic.path, "/audiences"); + assert_eq!(source_file(&diagnostic), "dev.yaml"); +} + +#[test] +fn an_explicit_dev_config_uses_its_own_inventory_beside_a_roles_only_service() { + let directory = Directory::new(DEV_INVENTORY) + .service("roles:\n clerk:\n actorKind: service\n accessProfiles: {breg: [clerk]}\n"); + let dev = directory.root.join("dev.yaml"); + let plan = plan( + &directory.root.join("service.yaml"), + Options { + workspace_root: None, + dev_config: Some(&dev), + checked_routes: None, + route_selections: &[], + for_client: false, + }, + ) + .expect("the roles-only service plans with the dev inventory"); + assert_eq!( + plan.dev_plan.expect("a dev projection")["products"][1], + json!({"product": "casework", "project": "casework", "audience": "urn:example:casework"}) + ); +} + +#[test] +fn single_project_runner_products_take_a_path() { + let directory = Directory::new( + "products:\n scheduling: {path: scheduling}\naudiences: {scheduling: urn:example:scheduling}\n", + ); + fs::create_dir(directory.root.join("scheduling")).unwrap(); + fs::write(directory.root.join("scheduling/scheduling.yaml"), "").unwrap(); + let plan = directory.plan().expect("a scheduling project"); + assert_eq!( + plan.native["products"], + json!([{"product": "scheduling", "project": "scheduling", "audience": "urn:example:scheduling"}]) + ); +} diff --git a/crates/registry-platform-objectstore/src/s3.rs b/crates/registry-platform-objectstore/src/s3.rs index 15ae9aea63..26f8d28534 100644 --- a/crates/registry-platform-objectstore/src/s3.rs +++ b/crates/registry-platform-objectstore/src/s3.rs @@ -218,8 +218,13 @@ impl S3Settings { .connect_timeout(connect_timeout(self.timeout)) .destination(&self.destination); if let Some(reference) = &self.ca_bundle_ref { - builder = - builder.trusted_root_certificates(resolve(reference)?.expose_secret().to_vec()); + builder = builder.trusted_root_certificates( + resolver + .resolve_public_document_reference(reference) + .map_err(|_| ObjectStoreError::Secret)? + .expose_secret() + .to_vec(), + ); } let scope = hex::encode(Sha256::digest(scope_input.as_bytes())); let binding_digest = binding_digest(namespace, &self.bucket_url, &self.region, &scope)?; diff --git a/crates/registry-platform-oidc/src/task_grant/config.rs b/crates/registry-platform-oidc/src/task_grant/config.rs index bb0501ca76..f172f2c9d7 100644 --- a/crates/registry-platform-oidc/src/task_grant/config.rs +++ b/crates/registry-platform-oidc/src/task_grant/config.rs @@ -145,7 +145,7 @@ impl TaskGrantStatusRegistry { let ca = config .ca_bundle_ref .as_ref() - .map(|reference| secrets.resolve_reference(reference)) + .map(|reference| secrets.resolve_public_document_reference(reference)) .transpose() .map_err(|_| TaskGrantError::Configuration)?; let mut token = PrivateKeyJwtConfig::new( diff --git a/crates/registry-platform-postgres/README.md b/crates/registry-platform-postgres/README.md index adcd9380b2..0d3f150df9 100644 --- a/crates/registry-platform-postgres/README.md +++ b/crates/registry-platform-postgres/README.md @@ -4,5 +4,6 @@ - `postgres_connection` checks every host and `hostaddr` of a parsed connection string under the runtime's `database.transport`. Under a plaintext transport it returns a configuration that dials only the numeric addresses each host was checked as, so the driver never resolves a name again. Under `verified-tls` the configuration is returned unchanged. - `loopback_postgres_connection` does the same under `loopback-plaintext`, for a constructor that holds no runtime database block. -- Both take the host resolver as an argument. A runtime passes `registry_platform_config::resolve_database_host`; tests pass a fixed answer. +- `private_development_postgres_connection` pins only private and loopback addresses for the development runner's explicitly selected administrator transport. Product runtimes use `postgres_connection` with the loaded database block and its posture witness. +- Each entry point takes a host resolver. A runtime passes `registry_platform_config::resolve_database_host`. Tests pass a fixed answer. - A keyword host written as an IP address in brackets, such as `host=[::1]`, is dropped from the list, as the driver itself fails that entry. When no other host is left, the connection is refused with `platform.database.bracketed-host`. diff --git a/crates/registry-platform-postgres/src/lib.rs b/crates/registry-platform-postgres/src/lib.rs index 367f003c59..8ed2cc157f 100644 --- a/crates/registry-platform-postgres/src/lib.rs +++ b/crates/registry-platform-postgres/src/lib.rs @@ -52,11 +52,30 @@ pub fn loopback_postgres_connection( postgres: Config, resolve: &HostResolver, ) -> Result { - let permitted = check_database_hosts( - DatabaseTransport::LoopbackPlaintext, - &database_hosts(&postgres), + connection_for_transport(postgres, DatabaseTransport::LoopbackPlaintext, resolve) +} + +/// Pin a PostgreSQL administrator configuration for an explicitly selected +/// private development attachment. Only the development runner uses this +/// entry point. Product runtimes use [`postgres_connection`] with a loaded +/// database block and its posture witness. +pub fn private_development_postgres_connection( + postgres: Config, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> Result { + connection_for_transport( + postgres, + DatabaseTransport::PrivateNetworkPlaintext, resolve, - )?; + ) +} + +fn connection_for_transport( + postgres: Config, + transport: DatabaseTransport, + resolve: &dyn Fn(&str) -> std::io::Result>, +) -> Result { + let permitted = check_database_hosts(transport, &database_hosts(&postgres), resolve)?; pinned(&permitted, postgres) } diff --git a/crates/registry-platform-provision/src/cli.rs b/crates/registry-platform-provision/src/cli.rs index 22e4402b94..15e3e3e959 100644 --- a/crates/registry-platform-provision/src/cli.rs +++ b/crates/registry-platform-provision/src/cli.rs @@ -95,6 +95,10 @@ pub struct ProvisionInput { pub ca_pem: Option>, /// How the runtime connects to PostgreSQL, from `database.transport`. pub transport: DatabaseTransport, + /// One notice per explicit production setting the runtime file states, + /// from [`registry_platform_config::FoundExplicitSetting::notice`]. The + /// runner writes each to stderr, as the runtime logs it at startup. + pub explicit_settings: Vec, } /// Result class of a run, as in every other verb's report. @@ -796,6 +800,13 @@ fn run_with( return output.refusal(&report); } }; + // The notice is the only report of an explicit setting for this run, so + // a notice that cannot reach stderr is an operational failure. + for notice in &input.explicit_settings { + if writeln!(output.stderr, "{notice}").is_err() { + return output.write_failed(false); + } + } report.product = Some(input.product.product.to_owned()); let dotted_section = section.replace('/', "."); let (Some(migration), Some(runtime)) = ( @@ -1160,6 +1171,7 @@ mod tests { runtime_url: Zeroizing::new(runtime.to_owned()), ca_pem: None, transport: DatabaseTransport::VerifiedTls, + explicit_settings: Vec::new(), } } @@ -1394,6 +1406,56 @@ mod tests { // ---- print mode ---- + #[test] + fn the_runtime_file_explicit_settings_are_printed_on_stderr() { + let notice = "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy. The file secret provider accepts root-owned, mode 0444 Compose mounts."; + for arguments in [ + &["--print-sql"][..], + &["--print-sql", "--format", "json"][..], + ] { + let mut input = split_input(); + input.explicit_settings = vec![notice.to_owned()]; + let run = execute_run(arguments, None, Ok(input), &must_not_run); + assert_eq!(run.exit, 0, "{}", run.all_output()); + assert!(run.stderr.contains(notice), "{arguments:?}: {}", run.stderr); + assert!(!run.stdout.contains(notice), "{arguments:?}"); + } + } + + #[test] + fn an_explicit_setting_notice_that_cannot_be_written_is_an_operational_failure() { + struct Closed; + impl Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut input = split_input(); + input.explicit_settings = vec!["Explicit production setting".to_owned()]; + let args = parse(&["--print-sql", "--runtime-config", "runtime.yaml"]).expect("arguments"); + let mut stdout = Vec::new(); + let exit = run_with( + "casectl", + "database", + "1.2.3-test", + &args, + OutputFormat::Human, + registry_cli_report::declared_from(None, None).unwrap(), + |_| Ok(input), + &must_not_run, + &mut stdout, + &mut Closed, + ); + assert_eq!(exit, 3); + assert!( + stdout.is_empty(), + "the script must not follow a lost notice" + ); + } + #[test] fn print_mode_writes_only_the_script_to_stdout() { let run = execute_run(&["--print-sql"], None, Ok(split_input()), &must_not_run); @@ -2683,6 +2745,7 @@ mod tests { runtime_url: input.runtime_url.clone(), ca_pem: None, transport: DatabaseTransport::LoopbackPlaintext, + explicit_settings: Vec::new(), }), &created_everything, declared, @@ -2941,6 +3004,7 @@ mod postgres_tests { )), ca_pem: Some(ca.clone()), transport: DatabaseTransport::VerifiedTls, + explicit_settings: Vec::new(), }; let _cleanup = Cleanup { admin: admin_config(&admin_url, Some(&ca)).expect("administrator config"), diff --git a/crates/registry-render/src/auth.rs b/crates/registry-render/src/auth.rs index dc275abfa9..576c3fc5eb 100644 --- a/crates/registry-render/src/auth.rs +++ b/crates/registry-render/src/auth.rs @@ -71,9 +71,24 @@ async fn entry_verifier( } registry_platform_config::JwksSource::Static { document_ref } | registry_platform_config::JwksSource::TestIssuer { document_ref } => { - let bytes = crate::runtime::resolve_secret(runtime, witness, document_ref)?; + // A provider that cannot be built is named as such, as every other + // reference this runtime resolves names it. + let resolver = runtime + .secret_providers + .resolver(witness) + .map_err(|error| { + RenderProblem::new( + ProblemKind::RuntimeInvalid, + format!("secretProviders: {error}"), + ) + })?; + let document = resolver + .resolve_public_document(document_ref) + .map_err(|error| { + RenderProblem::new(ProblemKind::RuntimeInvalid, format!("{error}")) + })?; let keys = - registry_platform_oidc::parse_static_jwks(&bytes).map_err(|error| match error { + registry_platform_oidc::parse_static_jwks(document.expose_secret()).map_err(|error| match error { OidcError::StaticKeySet(refused) => RenderProblem::new( ProblemKind::RuntimeInvalid, format!( diff --git a/crates/registry-render/src/check.rs b/crates/registry-render/src/check.rs index e8dfdf83ff..9f575b6808 100644 --- a/crates/registry-render/src/check.rs +++ b/crates/registry-render/src/check.rs @@ -295,10 +295,12 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn .iter() .map(|setting| { format!( - "Explicit production setting {} at {}. {}.\n", - setting.code, - setting.pointer.as_deref().unwrap_or(""), - setting.summary + "{}\n", + registry_platform_config::explicit_setting_notice( + setting.code, + setting.pointer.as_deref().unwrap_or(""), + setting.summary, + ) ) }) .collect::() diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index d6cc696eb8..371a6814fe 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -2221,6 +2221,19 @@ pub fn resolve_protected_secret( .resolve(reference) } +/// Resolve a public document, such as a static JWKS or a PEM CA bundle, under +/// the providers the runtime declares. Group and other may read the file. +pub fn resolve_public_document( + runtime: &RenderRuntime, + witness: Option<&DevelopmentWitness>, + reference: &str, +) -> Result { + runtime + .secret_providers + .resolver(witness)? + .resolve_public_document(reference) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-render/src/seal.rs b/crates/registry-render/src/seal.rs index 0d0a120481..f02ff67847 100644 --- a/crates/registry-render/src/seal.rs +++ b/crates/registry-render/src/seal.rs @@ -1199,8 +1199,8 @@ impl TimestampAuthority { let Some(reference) = authority.ca_bundle_ref.as_deref() else { return Self::new(seal_id, authority, None, peer_policy); }; - let bundle = crate::runtime::resolve_protected_secret(runtime, witness, reference) - .map_err(|error| { + let bundle = crate::runtime::resolve_public_document(runtime, witness, reference).map_err( + |error| { refusal( seal_id, "timestampAuthority/caBundleRef", @@ -1212,7 +1212,8 @@ impl TimestampAuthority { "Provide the timestamp authority's PEM CA bundle under the secret provider \ the reference names.", ) - })?; + }, + )?; Self::new( seal_id, authority, diff --git a/crates/registry-rstack-dev/Cargo.toml b/crates/registry-rstack-dev/Cargo.toml index 24f678cc21..abeddad28b 100644 --- a/crates/registry-rstack-dev/Cargo.toml +++ b/crates/registry-rstack-dev/Cargo.toml @@ -35,12 +35,15 @@ axum.workspace = true base64.workspace = true clap.workspace = true getrandom.workspace = true +jsonschema.workspace = true postgres-protocol.workspace = true 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-crypto.workspace = true +registry-platform-hooks = { workspace = true, features = ["receiver"] } registry-platform-httputil.workspace = true registry-platform-postgres.workspace = true registry-platform-provision.workspace = true @@ -63,6 +66,3 @@ tokio-postgres-rustls.workspace = true url.workspace = true uuid = { workspace = true, features = ["serde"] } zeroize.workspace = true - -[dev-dependencies] -jsonschema.workspace = true diff --git a/crates/registry-rstack-dev/src/bindings.rs b/crates/registry-rstack-dev/src/bindings.rs index 84edefcc8a..3a2bef870a 100644 --- a/crates/registry-rstack-dev/src/bindings.rs +++ b/crates/registry-rstack-dev/src/bindings.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -//! Run-local bindings between BReg and Casework. +//! Run-local bindings between the products of one development run: BReg and +//! Casework, and the Coordinator's Casework review producer and BReg client. //! -//! The token endpoint exists only for one development run. It accepts the two +//! The token endpoint exists only for one development run. It accepts the //! machine identities the plan explicitly binds, verifies their private-key //! JWT assertions, and mints the same bounded product token a named test person //! would receive. Keys, tokens, and assertion identifiers never enter reports @@ -60,7 +61,7 @@ const TOKEN_LIFETIME_SECONDS: u64 = 300; const TOKEN_SERVER_SHUTDOWN_GRACE: Duration = Duration::from_secs(2); const CLOCK_LEEWAY_SECONDS: u64 = 5; -/// Run-local connections between BReg and Casework. Configuring either one requires both products. +/// Run-local connections between products. The BReg and Casework bindings require both products; the Coordinator review producer requires Coordinator and Casework. #[derive(Default, Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -71,6 +72,51 @@ pub(super) struct Bindings { /// Connects Casework to BReg as a context provider. Casework authenticates to BReg as a machine identity. #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) casework_context_provider: Option, + /// Connects the Coordinator to Casework as one trusted review producer. The Coordinator authenticates to Casework as a machine identity, and Casework wakes its waiting run through a completion hook. Development runs only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) coordinator_review_producer: Option, + /// Gives one Coordinator BReg connection a machine identity on the run's token endpoint, with exactly one test person's BReg grant. BReg's own access profile and Action rules decide every call. Development runs only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) coordinator_breg_client: Option, +} + +/// One Coordinator `breg` connection the run authenticates as one test +/// person. The person's BReg grant is the only source of the connection's +/// profile and scopes; nothing in dev.yaml adds to them. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct CoordinatorBregClient { + /// The Coordinator `runtime.yaml` connection of type `breg`, without task authority. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) connection: String, + /// Name of the test person, in `people`, whose BReg grant the Coordinator uses. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) identity: String, +} + +/// The Coordinator's Casework review producer connection that the run binds +/// to Casework. Casework trusts exactly the producer the connection names, for +/// the run issuer, only when its pinned issuer, profile and subject match the +/// guards; nothing here widens what Casework trusts. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct CoordinatorReviewProducer { + /// The Coordinator `runtime.yaml` connection of type `casework-review-producer`. Its `producer` names the Casework trusted producer. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) connection: String, + /// The Casework trusted producer in `casework.yaml`. It must be the producer the connection names. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) producer: String, + /// Name of the test person, in `people`, whose Casework grant the Coordinator uses to authenticate. Its profile and subject are the producer's. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) identity: String, + /// The completion `destinationId` the producer names in `casework.yaml`. The run binds it to the Coordinator's completion endpoint with a per-run key. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub(super) completion_destination: String, + /// The exact source guards for binding this producer to the synthetic run issuer. It has no initiator guard. + pub(super) run_issuer_binding: ProducerIssuerBinding, } /// A BReg review authority that the run connects to Casework. @@ -104,6 +150,15 @@ pub(super) struct RunIssuerBinding { #[serde(default, skip_serializing_if = "Option::is_none")] pub initiator: Option, } +/// The run issuer guards of a binding that rebinds a producer only, never an +/// initiator. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ProducerIssuerBinding { + pub producer: RunProducer, +} + #[derive(Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -149,9 +204,16 @@ impl Bindings { self.breg_review_authority .as_ref() .is_some_and(|binding| binding.run_issuer_binding.is_some()) + || self.coordinator_review_producer.is_some() } pub(super) fn validate(&self, plan: &Plan) -> plan::SemanticResult<()> { + if let Some(binding) = &self.coordinator_review_producer { + validate_coordinator_review_producer(plan, binding)?; + } + if let Some(binding) = &self.coordinator_breg_client { + validate_coordinator_breg_client(plan, binding)?; + } if self.breg_review_authority.is_none() && self.casework_context_provider.is_none() { return Ok(()); } @@ -207,6 +269,115 @@ impl Bindings { } } +const COORDINATOR_BREG_CLIENT: &str = "/bindings/coordinatorBregClient"; + +fn validate_coordinator_breg_client( + plan: &Plan, + binding: &CoordinatorBregClient, +) -> plan::SemanticResult<()> { + plan::require( + product_position(plan, Product::Coordinator).is_some() + && product_position(plan, Product::Breg).is_some(), + "/bindings", + "The Coordinator BReg client binding requires the Coordinator and BReg products.", + "Add both products to products, or remove bindings.coordinatorBregClient.", + )?; + plan::require( + plan::identifier(&binding.connection), + &format!("{COORDINATOR_BREG_CLIENT}/connection"), + "The value must be a local identifier.", + "Set it to a lowercase local identifier of at most 64 characters.", + )?; + require_machine_person( + plan, + &binding.identity, + Product::Breg, + &format!("{COORDINATOR_BREG_CLIENT}/identity"), + )?; + // BReg attributes every Coordinator call to this person, so no other + // binding or preview actor may act as it. + let shared = [ + plan.bindings + .breg_review_authority + .as_ref() + .map(|other| other.identity.as_str()), + plan.bindings + .casework_context_provider + .as_ref() + .map(|other| other.identity.as_str()), + plan.bindings + .coordinator_review_producer + .as_ref() + .map(|other| other.identity.as_str()), + ] + .into_iter() + .flatten() + .chain( + plan.preview + .iter() + .flat_map(|preview| preview.actor_names()), + ) + .any(|other| other == binding.identity); + plan::require( + !shared, + &format!("{COORDINATOR_BREG_CLIENT}/identity"), + "The Coordinator's BReg identity must be a dedicated machine person that no other binding or preview actor uses.", + "Declare a separate test person for the Coordinator's BReg grant.", + )?; + // The run-local token endpoint signs with the run's key, which BReg + // trusts only through the run's own key set. + plan::require( + plan.jwks_uri().is_none(), + COORDINATOR_BREG_CLIENT, + "The Coordinator BReg client binding needs the run's own key set, so it cannot use externalJwksUri.", + "Remove externalJwksUri, or remove bindings.coordinatorBregClient.", + ) +} + +const COORDINATOR_PRODUCER: &str = "/bindings/coordinatorReviewProducer"; + +fn validate_coordinator_review_producer( + plan: &Plan, + binding: &CoordinatorReviewProducer, +) -> plan::SemanticResult<()> { + plan::require( + product_position(plan, Product::Coordinator).is_some() + && product_position(plan, Product::Casework).is_some(), + "/bindings", + "The Coordinator review producer binding requires the Coordinator and Casework products.", + "Add both products to products, or remove bindings.coordinatorReviewProducer.", + )?; + // Two machine identities never act as one Casework producer. + plan::require( + plan.bindings + .breg_review_authority + .as_ref() + .is_none_or(|other| other.producer != binding.producer), + &format!("{COORDINATOR_PRODUCER}/producer"), + "The BReg review authority binding already binds this Casework producer.", + "Bind a separate trusted producer for the Coordinator.", + )?; + for (member, value) in [ + ("connection", &binding.connection), + ("producer", &binding.producer), + ("completionDestination", &binding.completion_destination), + ] { + plan::require( + plan::identifier(value), + &format!("{COORDINATOR_PRODUCER}/{member}"), + "The value must be a local identifier.", + "Set it to a lowercase local identifier of at most 64 characters.", + )?; + } + require_machine_person( + plan, + &binding.identity, + Product::Casework, + &format!("{COORDINATOR_PRODUCER}/identity"), + ) + .map(|_| ()) +} + fn product_position(plan: &Plan, product: Product) -> Option { plan.products .iter() @@ -415,6 +586,14 @@ struct TokenServer { } const BREG_REVIEW_CLIENT: &str = "breg-review-client"; +const COORDINATOR_REVIEW_CLIENT: &str = "coordinator-review-client"; +const COORDINATOR_BREG_CLIENT_FILE: &str = "coordinator-breg-client"; +/// The run file holding the HMAC key Casework signs a Coordinator review +/// completion with and the Coordinator verifies it with. +pub(super) const COORDINATOR_COMPLETION_KEY: &str = "coordinator-review-completion-key"; +/// The Coordinator's review completion route, as `registry-review-protocol` +/// declares it. rstack dev depends on no product protocol crate. +pub(super) const REVIEW_COMPLETIONS_PATH: &str = "/v1/review-completions"; const CASEWORK_CONTEXT_CLIENT: &str = "casework-context-client"; #[derive(Default)] @@ -435,15 +614,33 @@ impl RuntimeBindings { origins: &BTreeMap, ) -> Result { let bindings = &input.plan.bindings; - if bindings.breg_review_authority.is_none() && bindings.casework_context_provider.is_none() + if bindings.breg_review_authority.is_none() + && bindings.casework_context_provider.is_none() + && bindings.coordinator_review_producer.is_none() + && bindings.coordinator_breg_client.is_none() { return Ok(Self::default()); } bindings.validate(&input.plan)?; ensure!( - origins.contains_key(&Product::Breg) && origins.contains_key(&Product::Casework), + bindings.coordinator_breg_client.is_none() + || (origins.contains_key(&Product::Coordinator) + && origins.contains_key(&Product::Breg)), + "the Coordinator BReg client binding requires reserved Coordinator and BReg origins" + ); + ensure!( + (bindings.breg_review_authority.is_none() + && bindings.casework_context_provider.is_none()) + || (origins.contains_key(&Product::Breg) + && origins.contains_key(&Product::Casework)), "run-local bindings require reserved BReg and Casework origins" ); + ensure!( + bindings.coordinator_review_producer.is_none() + || (origins.contains_key(&Product::Coordinator) + && origins.contains_key(&Product::Casework)), + "the Coordinator review producer binding requires reserved Coordinator and Casework origins" + ); let mut clients = Vec::new(); if let Some(binding) = &bindings.breg_review_authority { @@ -466,6 +663,32 @@ impl RuntimeBindings { &mut clients, )?; } + if let Some(binding) = &bindings.coordinator_review_producer { + prepare_binding( + root, + &input, + &binding.identity, + Product::Casework, + COORDINATOR_REVIEW_CLIENT, + &mut clients, + )?; + // Casework signs each completion with this key and the + // Coordinator verifies it: exact random bytes, owner-only, per run. + let mut key = Zeroizing::new([0_u8; 32]); + getrandom::fill(key.as_mut()) + .map_err(|_| anyhow::anyhow!("cannot generate the review completion key"))?; + write_private(&root.join(COORDINATOR_COMPLETION_KEY), key.as_ref())?; + } + if let Some(binding) = &bindings.coordinator_breg_client { + prepare_binding( + root, + &input, + &binding.identity, + Product::Breg, + COORDINATOR_BREG_CLIENT_FILE, + &mut clients, + )?; + } let server = start_token_server(input.clone(), issuer.clone(), clients)?; Ok(Self { server: Some(server), @@ -529,6 +752,12 @@ fn render( }); } Product::Casework => { + if let Some(binding) = plan.bindings.coordinator_review_producer.as_ref() { + config["destinations"]["hooks"][binding.completion_destination.as_str()] = json!({ + "url": format!("{}{REVIEW_COMPLETIONS_PATH}", origins[&Product::Coordinator]), + "hmacSha256KeyRef": format!("secret:file/{COORDINATOR_COMPLETION_KEY}"), + }); + } let Some(binding) = plan.bindings.casework_context_provider.as_ref() else { return; }; @@ -548,6 +777,69 @@ fn render( "clientAssertionKeyRef": client_assertion_key_ref, }); } + Product::Coordinator => { + if let Some(binding) = plan.bindings.coordinator_breg_client.as_ref() { + if let Some(connection) = config["connections"] + .get_mut(binding.connection.as_str()) + .and_then(Value::as_object_mut) + { + // The grant alone supplies the profile and scopes, and the + // authorization is replaced whole, so no authored member + // such as task authority survives. + let person = &plan.people[&binding.identity]; + let grant = &person.grants[&Product::Breg]; + let (_, signing_key_ref) = client_refs(COORDINATOR_BREG_CLIENT_FILE); + connection.insert("baseUrl".into(), json!(origins[&Product::Breg])); + connection.insert("profile".into(), json!(grant.profile)); + connection.insert( + "authorization".into(), + json!({ + "tokenEndpoint": token_endpoint, + "clientAssertionAudience": issuer, + "clientId": person.client, + "signingKeyRef": signing_key_ref, + "resource": plan.product(Product::Breg).audience, + "scopes": grant.scopes, + }), + ); + } + } + let Some(binding) = plan.bindings.coordinator_review_producer.as_ref() else { + return; + }; + let Some(connection) = config["connections"] + .get_mut(binding.connection.as_str()) + .and_then(Value::as_object_mut) + else { + return; + }; + let person = &plan.people[&binding.identity]; + let grant = &person.grants[&Product::Casework]; + let (_, signing_key_ref) = client_refs(COORDINATOR_REVIEW_CLIENT); + connection.insert("baseUrl".into(), json!(origins[&Product::Casework])); + connection.insert("profile".into(), json!(grant.profile)); + connection.insert( + "authorization".into(), + json!({ + "tokenEndpoint": token_endpoint, + "clientAssertionAudience": issuer, + "clientId": person.client, + "signingKeyRef": signing_key_ref, + "resource": plan.product(Product::Casework).audience, + "scopes": grant.scopes, + }), + ); + if let Some(completion) = connection + .get_mut("completion") + .and_then(Value::as_object_mut) + { + completion.remove("previousHmacSha256KeyRef"); + completion.insert( + "hmacSha256KeyRef".into(), + json!(format!("secret:file/{COORDINATOR_COMPLETION_KEY}")), + ); + } + } // Evidence has no bindings: a caller reaches it with a test token. // Messaging has no bindings: a caller reaches it with a test token. _ => {} @@ -584,6 +876,7 @@ pub(super) fn render_for_check(plan: &Plan, product: Product, config: &mut Value let origins = BTreeMap::from([ (Product::Breg, CHECK_ORIGIN.to_owned()), (Product::Casework, CHECK_ORIGIN.to_owned()), + (Product::Coordinator, CHECK_ORIGIN.to_owned()), ]); render( plan, @@ -1464,6 +1757,7 @@ mod tests { issuer: "https://identity.example.test/realms/dev".to_owned(), external_jwks_uri: None, external_breg: None, + external_scheduling: None, products: vec![ ProductPlan { product: Product::Breg, @@ -1515,6 +1809,8 @@ mod tests { identity: "context-reader".to_owned(), action: "reviewed-change".to_owned(), }), + coordinator_review_producer: None, + coordinator_breg_client: None, }, journey_file: PathBuf::from("dev-journeys.yaml"), schema_test_people: BTreeMap::new(), @@ -2980,4 +3276,579 @@ mod tests { "{error}" ); } + + /// Casework and the Coordinator, with the Coordinator's `review` + /// connection bound as the `coordinator` producer. + fn coordinator_plan() -> Plan { + let mut value = plan(); + value.products = vec![ + ProductPlan { + product: Product::Casework, + project: PathBuf::from("casework"), + audience: "urn:dev:casework".to_owned(), + }, + ProductPlan { + product: Product::Coordinator, + project: PathBuf::from("coordinator"), + audience: "urn:dev:coordinator".to_owned(), + }, + ]; + value.people = BTreeMap::from([( + "coordinator-producer".to_owned(), + TestPerson { + subject: "coordinator-producer".to_owned(), + display_name: None, + client: "coordinator-review-client".to_owned(), + grants: BTreeMap::from([( + Product::Casework, + grant("coordinator-producer", "casework:review"), + )]), + }, + )]); + value.bindings = serde_json::from_value(json!({"coordinatorReviewProducer": { + "connection": "review", "producer": "coordinator", "identity": "coordinator-producer", + "completionDestination": "coordinator-wake", + "runIssuerBinding": {"producer": { + "expectedIssuer": "https://identity.example.test/producer", + "expectedProfile": "coordinator-producer", + "expectedSubject": "coordinator-producer" + }} + }})) + .unwrap(); + value + } + + fn coordinator_origins() -> BTreeMap { + BTreeMap::from([ + (Product::Casework, "http://127.0.0.1:31002".to_owned()), + (Product::Coordinator, "http://127.0.0.1:31003".to_owned()), + ]) + } + + #[test] + fn a_coordinator_review_producer_needs_its_products_identity_and_a_closed_guard() { + let value = coordinator_plan(); + value.bindings.validate(&value).unwrap(); + // The bound Coordinator and Casework pair may use the run issuer. + assert!(value.paired_run_binding()); + let refused = |change: fn(&mut Plan)| { + let mut value = coordinator_plan(); + change(&mut value); + value.bindings.validate(&value).unwrap_err().to_string() + }; + let error = refused(|plan| { + plan.products + .retain(|entry| entry.product != Product::Coordinator) + }); + assert!(error.contains("/bindings"), "{error}"); + let error = refused(|plan| { + plan.people + .get_mut("coordinator-producer") + .unwrap() + .grants + .clear(); + }); + assert!( + error.contains("/bindings/coordinatorReviewProducer/identity"), + "{error}" + ); + // The schema has no initiator member for this binding. + let widened = serde_json::from_value::(json!({"coordinatorReviewProducer": { + "connection": "review", "producer": "coordinator", "identity": "coordinator-producer", + "completionDestination": "coordinator-wake", + "runIssuerBinding": { + "producer": { + "expectedIssuer": "https://identity.example.test/producer", + "expectedProfile": "coordinator-producer", + "expectedSubject": "coordinator-producer" + }, + "initiator": {"expectedIssuer": "https://identity.example.test/people", "trust": "run-test-people"} + } + }})); + assert!(widened.is_err()); + } + + #[test] + fn the_coordinator_review_producer_renders_both_sides_with_one_run_key() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let run = Arc::new(input(coordinator_plan())); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = + RuntimeBindings::prepare(root.path(), run.clone(), issuer, &coordinator_origins()) + .unwrap(); + let endpoint = runtime.server.as_ref().unwrap().endpoint.clone(); + + let mut casework = json!({}); + runtime.configure(Product::Casework, &mut casework); + assert_eq!( + casework["destinations"]["hooks"]["coordinator-wake"], + json!({ + "url": "http://127.0.0.1:31003/v1/review-completions", + "hmacSha256KeyRef": "secret:file/coordinator-review-completion-key" + }) + ); + + let mut coordinator = json!({"connections": { + "review": { + "type": "casework-review-producer", "baseUrl": "http://127.0.0.1:1", + "profile": "coordinator-producer", "producer": "coordinator", + "authorization": {"tokenEndpoint": "http://127.0.0.1:1/token", "clientId": "authored"}, + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }, + "other": {"type": "breg", "baseUrl": "http://127.0.0.1:2"} + }}); + runtime.configure(Product::Coordinator, &mut coordinator); + assert_eq!( + coordinator["connections"]["review"], + json!({ + "type": "casework-review-producer", "baseUrl": "http://127.0.0.1:31002", + "profile": "coordinator-producer", "producer": "coordinator", + "authorization": { + "tokenEndpoint": endpoint, + "clientAssertionAudience": run.plan.issuer, + "clientId": "coordinator-review-client", + "signingKeyRef": "secret:file/coordinator-review-client-key", + "resource": "urn:dev:casework", + "scopes": ["casework:review"] + }, + "completion": { + "recipientBinding": "coordinator-v1", + "hmacSha256KeyRef": "secret:file/coordinator-review-completion-key" + } + }) + ); + assert_eq!( + coordinator["connections"]["other"], + json!({"type": "breg", "baseUrl": "http://127.0.0.1:2"}) + ); + + // One owner-only key of exact random bytes signs and verifies the wake-up. + let key = root.path().join("coordinator-review-completion-key"); + assert_eq!(std::fs::read(&key).unwrap().len(), 32); + assert_eq!( + std::fs::metadata(&key).unwrap().permissions().mode() & 0o777, + 0o600 + ); + + // Without the binding, nothing is rendered for either side. + let mut plain = coordinator_plan(); + plain.bindings = Bindings::default(); + let unbound = RuntimeBindings::prepare( + root.path(), + Arc::new(input(plain)), + Arc::new(Issuer::create(root.path()).unwrap()), + &coordinator_origins(), + ) + .unwrap(); + let mut untouched = json!({"connections": {"review": {"baseUrl": "http://127.0.0.1:1"}}}); + unbound.configure(Product::Coordinator, &mut untouched); + assert_eq!( + untouched, + json!({"connections": {"review": {"baseUrl": "http://127.0.0.1:1"}}}) + ); + } + + #[test] + fn the_coordinator_obtains_a_producer_token_from_the_run_token_server() { + use base64::Engine as _; + let root = tempfile::tempdir().unwrap(); + let mut run = input(coordinator_plan()); + // Casework names the subject claim for each profile it serves. + run.casework_principals + .insert("coordinator-producer".to_owned(), "sub".to_owned()); + let input = Arc::new(run); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = + RuntimeBindings::prepare(root.path(), input.clone(), issuer, &coordinator_origins()) + .unwrap(); + let mut coordinator = json!({"connections": {"review": { + "type": "casework-review-producer", "producer": "coordinator", + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }}}); + runtime.configure(Product::Coordinator, &mut coordinator); + let authorization = &coordinator["connections"]["review"]["authorization"]; + let encoded = Zeroizing::new( + std::fs::read(root.path().join("coordinator-review-client-key")).unwrap(), + ); + let key = PrivateJwk::parse(std::str::from_utf8(&encoded).unwrap()).unwrap(); + // The client the Coordinator builds from its rendered authorization. + let provider = PrivateKeyJwt::new( + PrivateKeyJwtConfig::new( + authorization["tokenEndpoint"] + .as_str() + .unwrap() + .parse() + .unwrap(), + authorization["clientId"].as_str().unwrap(), + key, + ) + .with_audience(authorization["clientAssertionAudience"].as_str().unwrap()) + .with_resource(authorization["resource"].as_str().unwrap()) + .with_scopes(vec!["casework:review".to_owned()]), + ) + .unwrap(); + let token = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(provider.bearer_token()) + .expect("the Coordinator obtains a producer token"); + let header = token.authorization_header_value(); + let compact = header.to_str().unwrap().trim_start_matches("Bearer "); + let claims: Value = serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(compact.split('.').nth(1).unwrap()) + .unwrap(), + ) + .unwrap(); + assert_eq!(claims["sub"], "coordinator-producer"); + assert_eq!(claims["aud"], "urn:dev:casework"); + assert_eq!(claims["iss"], input.plan.issuer); + } + + #[test] + fn one_casework_producer_is_bound_by_at_most_one_binding() { + let mut value = coordinator_plan(); + value.products.push(ProductPlan { + product: Product::Breg, + project: PathBuf::from("registry"), + audience: "urn:dev:breg".to_owned(), + }); + value.bindings.breg_review_authority = Some(BregReviewAuthority { + id: "casework".to_owned(), + producer: "coordinator".to_owned(), + identity: "coordinator-producer".to_owned(), + run_issuer_binding: None, + }); + let error = value.bindings.validate(&value).unwrap_err().to_string(); + assert!( + error.contains("/bindings/coordinatorReviewProducer/producer"), + "{error}" + ); + } + + #[test] + fn each_start_writes_a_fresh_completion_key_that_nothing_else_carries() { + let read = || { + let root = tempfile::tempdir().unwrap(); + let runtime = RuntimeBindings::prepare( + root.path(), + Arc::new(input(coordinator_plan())), + Arc::new(Issuer::create(root.path()).unwrap()), + &coordinator_origins(), + ) + .unwrap(); + let mut casework = json!({}); + runtime.configure(Product::Casework, &mut casework); + let mut coordinator = json!({"connections": {"review": { + "type": "casework-review-producer", "producer": "coordinator", + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }}}); + runtime.configure(Product::Coordinator, &mut coordinator); + let key = std::fs::read(root.path().join(COORDINATOR_COMPLETION_KEY)).unwrap(); + // Only the key file holds the key: no other run file and no rendered + // configuration carries its bytes in any common encoding. + use base64::Engine as _; + let encodings = [ + key.iter() + .map(|byte| format!("{byte:02x}")) + .collect::(), + base64::engine::general_purpose::STANDARD.encode(&key), + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&key), + ]; + for rendered in [casework.to_string(), coordinator.to_string()] { + for encoded in &encodings { + assert!(!rendered.contains(encoded.as_str())); + } + } + for entry in std::fs::read_dir(root.path()).unwrap() { + let path = entry.unwrap().path(); + if path.file_name().unwrap() == COORDINATOR_COMPLETION_KEY || !path.is_file() { + continue; + } + let bytes = std::fs::read(&path).unwrap(); + assert!( + !bytes + .windows(key.len()) + .any(|window| window == key.as_slice()), + "{}", + path.display() + ); + let text = String::from_utf8_lossy(&bytes); + for encoded in &encodings { + assert!(!text.contains(encoded.as_str()), "{}", path.display()); + } + } + key + }; + assert_ne!(read(), read()); + } + + #[test] + fn the_completion_route_matches_the_review_protocol() { + let protocol = include_str!("../../registry-review-protocol/src/lib.rs"); + assert!( + protocol.contains(&format!( + "pub const REVIEW_COMPLETIONS_PATH: &str = \"{REVIEW_COMPLETIONS_PATH}\";" + )), + "the review protocol moved its completion route" + ); + } + + /// BReg and the Coordinator, with the Coordinator's `registry` BReg + /// connection bound to the `coordinator-service` test person. + fn coordinator_breg_plan() -> Plan { + let mut value = plan(); + value.products = vec![ + ProductPlan { + product: Product::Breg, + project: PathBuf::from("registry"), + audience: "urn:dev:breg".to_owned(), + }, + ProductPlan { + product: Product::Coordinator, + project: PathBuf::from("coordinator"), + audience: "urn:dev:coordinator".to_owned(), + }, + ]; + value.people = BTreeMap::from([( + "coordinator-service".to_owned(), + TestPerson { + subject: "coordinator-service".to_owned(), + display_name: None, + client: "coordinator-breg-client".to_owned(), + grants: BTreeMap::from([( + Product::Breg, + grant("permit-coordinator", "registry:actions:invoke"), + )]), + }, + )]); + value.bindings = serde_json::from_value(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "coordinator-service" + }})) + .unwrap(); + value + } + + fn coordinator_breg_origins() -> BTreeMap { + BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:31001".to_owned()), + (Product::Coordinator, "http://127.0.0.1:31003".to_owned()), + ]) + } + + #[test] + fn a_coordinator_breg_client_needs_its_products_and_a_breg_identity() { + let value = coordinator_breg_plan(); + value.bindings.validate(&value).unwrap(); + let refused = |change: fn(&mut Plan)| { + let mut value = coordinator_breg_plan(); + change(&mut value); + value.bindings.validate(&value).unwrap_err().to_string() + }; + let error = refused(|plan| plan.products.retain(|entry| entry.product != Product::Breg)); + assert!(error.contains("/bindings"), "{error}"); + let error = refused(|plan| { + plan.people + .get_mut("coordinator-service") + .unwrap() + .grants + .clear(); + }); + assert!( + error.contains("/bindings/coordinatorBregClient/identity"), + "{error}" + ); + let error = refused(|plan| { + plan.bindings + .coordinator_breg_client + .as_mut() + .unwrap() + .connection = "Registry".to_owned(); + }); + assert!( + error.contains("/bindings/coordinatorBregClient/connection"), + "{error}" + ); + // dev.yaml has no member that adds a profile or scope. + let widened = serde_json::from_value::(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "coordinator-service", + "scopes": ["registry:records:write"] + }})); + assert!(widened.is_err()); + } + + #[test] + fn the_coordinator_breg_client_takes_profile_and_scopes_from_the_grant_only() { + let root = tempfile::tempdir().unwrap(); + let run = Arc::new(input(coordinator_breg_plan())); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = RuntimeBindings::prepare( + root.path(), + run.clone(), + issuer, + &coordinator_breg_origins(), + ) + .unwrap(); + let endpoint = runtime.server.as_ref().unwrap().endpoint.clone(); + let mut coordinator = json!({"connections": { + "registry": { + "type": "breg", "baseUrl": "http://127.0.0.1:1", "profile": "authored-profile", + "authorization": {"tokenEndpoint": "http://127.0.0.1:1/token", "clientId": "authored", + "scopes": ["registry:records:write"], "resource": "urn:elsewhere", + // Members the binding never writes must not survive either. + "taskAuthority": {"issuer": "https://casework.example"}, + "authoredOnly": "authored-value"} + }, + "notices": {"type": "messaging", "baseUrl": "http://127.0.0.1:2"} + }}); + runtime.configure(Product::Coordinator, &mut coordinator); + assert_eq!( + coordinator["connections"]["registry"], + json!({ + "type": "breg", "baseUrl": "http://127.0.0.1:31001", + "profile": "permit-coordinator", + "authorization": { + "tokenEndpoint": endpoint, + "clientAssertionAudience": run.plan.issuer, + "clientId": "coordinator-breg-client", + "signingKeyRef": "secret:file/coordinator-breg-client-key", + "resource": "urn:dev:breg", + "scopes": ["registry:actions:invoke"] + } + }) + ); + assert_eq!( + coordinator["connections"]["notices"], + json!({"type": "messaging", "baseUrl": "http://127.0.0.1:2"}) + ); + } + + #[test] + fn the_coordinator_obtains_a_breg_token_for_its_bound_identity() { + use base64::Engine as _; + let root = tempfile::tempdir().unwrap(); + let run = Arc::new(input(coordinator_breg_plan())); + let issuer = Arc::new(Issuer::create(root.path()).unwrap()); + let runtime = RuntimeBindings::prepare( + root.path(), + run.clone(), + issuer, + &coordinator_breg_origins(), + ) + .unwrap(); + let mut coordinator = json!({"connections": {"registry": {"type": "breg"}}}); + runtime.configure(Product::Coordinator, &mut coordinator); + let authorization = &coordinator["connections"]["registry"]["authorization"]; + let encoded = + Zeroizing::new(std::fs::read(root.path().join("coordinator-breg-client-key")).unwrap()); + let key = PrivateJwk::parse(std::str::from_utf8(&encoded).unwrap()).unwrap(); + let provider = PrivateKeyJwt::new( + PrivateKeyJwtConfig::new( + authorization["tokenEndpoint"] + .as_str() + .unwrap() + .parse() + .unwrap(), + authorization["clientId"].as_str().unwrap(), + key, + ) + .with_audience(authorization["clientAssertionAudience"].as_str().unwrap()) + .with_resource(authorization["resource"].as_str().unwrap()) + .with_scopes(vec!["registry:actions:invoke".to_owned()]), + ) + .unwrap(); + let runtime_tokens = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let token = runtime_tokens + .block_on(provider.bearer_token()) + .expect("the Coordinator obtains a BReg token"); + let header = token.authorization_header_value(); + let compact = header.to_str().unwrap().trim_start_matches("Bearer "); + let claims: Value = serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(compact.split('.').nth(1).unwrap()) + .unwrap(), + ) + .unwrap(); + assert_eq!(claims["sub"], "coordinator-service"); + assert_eq!(claims["aud"], "urn:dev:breg"); + // A scope the grant does not hold is refused. + let encoded = + Zeroizing::new(std::fs::read(root.path().join("coordinator-breg-client-key")).unwrap()); + let key = PrivateJwk::parse(std::str::from_utf8(&encoded).unwrap()).unwrap(); + let wider = PrivateKeyJwt::new( + PrivateKeyJwtConfig::new( + authorization["tokenEndpoint"] + .as_str() + .unwrap() + .parse() + .unwrap(), + authorization["clientId"].as_str().unwrap(), + key, + ) + .with_audience(authorization["clientAssertionAudience"].as_str().unwrap()) + .with_resource(authorization["resource"].as_str().unwrap()) + .with_scopes(vec!["registry:records:write".to_owned()]), + ) + .unwrap(); + assert!(runtime_tokens.block_on(wider.bearer_token()).is_err()); + } + + #[test] + fn the_coordinator_breg_identity_is_a_dedicated_machine_person() { + // Shared with the Casework context provider. + let mut shared = coordinator_breg_plan(); + shared.products.push(ProductPlan { + product: Product::Casework, + project: PathBuf::from("casework"), + audience: "urn:dev:casework".to_owned(), + }); + shared.bindings.casework_context_provider = Some(CaseworkContextProvider { + id: "registry".to_owned(), + identity: "coordinator-service".to_owned(), + action: "reviewed-change".to_owned(), + }); + let error = shared.bindings.validate(&shared).unwrap_err().to_string(); + assert!( + error.contains("/bindings/coordinatorBregClient/identity"), + "{error}" + ); + assert!(error.contains("dedicated"), "{error}"); + + // Shared with the preview actor. + let mut previewed = coordinator_breg_plan(); + previewed.preview = Some( + serde_json::from_value(json!({ + "actor": "coordinator-service", "page": "/", "breg": {}, "functions": ["renew"] + })) + .unwrap(), + ); + let error = previewed + .bindings + .validate(&previewed) + .unwrap_err() + .to_string(); + assert!( + error.contains("/bindings/coordinatorBregClient/identity"), + "{error}" + ); + } + + #[test] + fn the_coordinator_breg_client_needs_the_run_key_set() { + let mut external = coordinator_breg_plan(); + external.issuer = "http://127.0.0.1:41000".to_owned(); + external.external_jwks_uri = Some("http://127.0.0.1:41000/keys".to_owned()); + let error = external + .bindings + .validate(&external) + .unwrap_err() + .to_string(); + assert!(error.contains("/bindings/coordinatorBregClient"), "{error}"); + assert!(error.contains("externalJwksUri"), "{error}"); + } } diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 81a60bb38a..318de38fd4 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 use std::{ + cell::Cell, future::Future, + net::IpAddr, str::FromStr, thread, time::{Duration, Instant}, }; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{anyhow, bail, ensure, Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_platform_config::{DatabaseTransport, HostResolver}; use registry_platform_provision::{ @@ -262,7 +264,7 @@ type AdminConnectionTask = tokio::task::JoinHandle { + Self::Plaintext => { let (client, connection) = bounded_connection(config.connect(tokio_postgres::NoTls), timeout).await?; Ok((client, tokio::spawn(connection))) @@ -324,6 +326,24 @@ fn open_admin_session( Ok((client, connection_task, identity)) } +fn open_plaintext_candidates( + admin_url: &str, + addresses: &[IpAddr], + mut open: impl FnMut(&Config) -> Result, +) -> Result<(Config, Endpoint, T)> { + let mut last_error = None; + for &address in addresses { + let (mut candidate, endpoint) = + admin_config_with_resolver(admin_url, &move |_| Ok(vec![address]))?; + apply_session_options(&mut candidate); + match open(&candidate) { + Ok(session) => return Ok((candidate, endpoint, session)), + Err(error) => last_error = Some(error), + } + } + Err(last_error.unwrap_or_else(|| anyhow!("no checked plaintext PostgreSQL address answered"))) +} + #[derive(Clone)] pub(super) struct DatabaseUrls { pub runtime: String, @@ -387,12 +407,9 @@ impl Endpoint { DatabaseTransport::VerifiedTls => { url.query_pairs_mut().append_pair("sslmode", "require"); } - DatabaseTransport::LoopbackPlaintext => { + DatabaseTransport::LoopbackPlaintext | DatabaseTransport::PrivateNetworkPlaintext => { url.query_pairs_mut().append_pair("sslmode", "disable"); } - DatabaseTransport::PrivateNetworkPlaintext => { - bail!("private-network-plaintext is not supported by rstack dev"); - } } Ok(url.into()) } @@ -423,24 +440,26 @@ impl Database { apply_session_options(&mut admin_config); let transport = match endpoint.transport { DatabaseTransport::VerifiedTls => AdminTransport::Tls(tls_connector(ca_pem)?), - DatabaseTransport::LoopbackPlaintext => { + DatabaseTransport::LoopbackPlaintext | DatabaseTransport::PrivateNetworkPlaintext => { if ca_pem.is_some() { bail!( "RSTACK_DEV_DATABASE_CA cannot be set when the PostgreSQL administrator \ - URL uses sslmode=disable" + URL selects plaintext" ); } - AdminTransport::LoopbackPlaintext - } - DatabaseTransport::PrivateNetworkPlaintext => { - bail!("private-network-plaintext is not supported by rstack dev"); + AdminTransport::Plaintext } }; let session_context = match endpoint.transport { DatabaseTransport::LoopbackPlaintext => { "cannot establish the PostgreSQL administrator session over loopback plaintext" } - _ => "cannot establish the PostgreSQL administrator session over verified TLS", + DatabaseTransport::PrivateNetworkPlaintext => { + "cannot establish the PostgreSQL administrator session over private network plaintext" + } + DatabaseTransport::VerifiedTls => { + "cannot establish the PostgreSQL administrator session over verified TLS" + } }; let runtime = Builder::new_current_thread() .enable_all() @@ -449,48 +468,26 @@ impl Database { let ownership_lock = ownership_lock_statement(run_id)?; let session_deadline = Instant::now() + CLEANUP_ATTEMPT_TIMEOUT; let (admin_config, endpoint, client, connection_task, recovery_identity) = - if matches!(transport, AdminTransport::LoopbackPlaintext) + if matches!(transport, AdminTransport::Plaintext) && admin_config.get_hostaddrs().len() > 1 { - let mut last_error = None; - let mut connected = None; - for &address in admin_config.get_hostaddrs() { - let (mut candidate_config, candidate_endpoint) = - admin_config_with_resolver(admin_url, &move |_| Ok(vec![address]))?; - apply_session_options(&mut candidate_config); - match open_admin_session( - &runtime, - &candidate_config, - &transport, - &ownership_lock, - expected_identity, - session_deadline, - ) { - Ok((client, connection_task, recovery_identity)) => { - connected = Some(( - candidate_config, - candidate_endpoint, - client, - connection_task, - recovery_identity, - )); - break; - } - Err(error) => { - last_error = Some(error); - } - } - } - match connected { - Some(found) => found, - None => { - return Err(last_error.unwrap_or_else(|| { - anyhow!("no checked loopback PostgreSQL address answered") - })) - .context(session_context) - .map_err(super::operational); - } - } + let (config, endpoint, (client, task, identity)) = open_plaintext_candidates( + admin_url, + admin_config.get_hostaddrs(), + |candidate| { + open_admin_session( + &runtime, + candidate, + &transport, + &ownership_lock, + expected_identity, + session_deadline, + ) + }, + ) + .context(session_context) + .map_err(super::operational)?; + (config, endpoint, client, task, identity) } else { let (client, connection_task, recovery_identity) = open_admin_session( &runtime, @@ -1336,6 +1333,7 @@ fn admin_config_with_resolver( ); } let mut requested_transport: Option = None; + let mut private_plaintext = false; for (key, value) in parsed.query_pairs() { match key.as_ref() { "sslmode" => { @@ -1356,18 +1354,34 @@ fn admin_config_with_resolver( "the PostgreSQL admin URL must not set sslrootcert; set RSTACK_DEV_DATABASE_CA \ to a CA PEM file instead" ), + "transport" => { + if private_plaintext || value != "private-network-plaintext" { + bail!( + "the PostgreSQL admin URL transport may specify private-network-plaintext once" + ); + } + private_plaintext = true; + } "connect_timeout" | "application_name" => {} other => bail!("the PostgreSQL admin URL query parameter {other} is not supported"), } } - let transport = requested_transport.unwrap_or(DatabaseTransport::VerifiedTls); + let transport = if private_plaintext { + ensure!( + requested_transport != Some(DatabaseTransport::VerifiedTls), + "the PostgreSQL admin URL must not combine private-network-plaintext with TLS sslmode" + ); + DatabaseTransport::PrivateNetworkPlaintext + } else { + requested_transport.unwrap_or(DatabaseTransport::VerifiedTls) + }; // tokio-postgres does not parse verify-ca or verify-full, and the runner // sets its own TLS mode, so the checked sslmode is not passed on. let mut sanitized = parsed.clone(); let kept: Vec<(String, String)> = parsed .query_pairs() - .filter(|(key, _)| key != "sslmode") + .filter(|(key, _)| key != "sslmode" && key != "transport") .map(|(key, value)| (key.into_owned(), value.into_owned())) .collect(); if kept.is_empty() { @@ -1403,20 +1417,37 @@ fn admin_config_with_resolver( config.ssl_mode(SslMode::Disable); } DatabaseTransport::PrivateNetworkPlaintext => { - bail!("private-network-plaintext is not supported by rstack dev"); + let lookup_failed = Cell::new(false); + let checked_resolver = |host: &str| { + let result = resolve(host); + lookup_failed.set(result.as_ref().map_or(true, Vec::is_empty)); + result + }; + config = registry_platform_postgres::private_development_postgres_connection( + config, + &checked_resolver, + ) + .map_err(|_| { + if lookup_failed.get() { + super::operational(anyhow!( + "could not resolve the PostgreSQL admin host for private-network-plaintext" + )) + } else { + anyhow!("the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses") + } + })?; + config.ssl_mode(SslMode::Disable); } } let host = match transport { - DatabaseTransport::LoopbackPlaintext => { + DatabaseTransport::LoopbackPlaintext | DatabaseTransport::PrivateNetworkPlaintext => { let pinned = *config.get_hostaddrs().first().ok_or_else(|| { - anyhow!("the PostgreSQL loopback host did not resolve to an address") + anyhow!("the PostgreSQL plaintext host did not resolve to an address") })?; ip_to_url_host(pinned) } - DatabaseTransport::VerifiedTls | DatabaseTransport::PrivateNetworkPlaintext => { - parsed.host().expect("the host was checked").to_owned() - } + DatabaseTransport::VerifiedTls => parsed.host().expect("the host was checked").to_owned(), }; Ok(( config, @@ -2029,6 +2060,123 @@ mod tests { assert!(!ca_conflict.contains(password)); } + #[test] + fn explicitly_selected_private_plaintext_pins_every_checked_address() { + let url = "postgresql://admin:synthetic-url-value@postgres.compose:5432/postgres?transport=private-network-plaintext"; + let private = std::net::IpAddr::from([172, 20, 0, 7]); + let (config, endpoint) = + admin_config_with_resolver(url, &move |_| Ok(vec![private])).unwrap(); + assert_eq!(config.get_ssl_mode(), SslMode::Disable); + assert!(config.get_hosts().is_empty()); + assert_eq!(config.get_hostaddrs(), &[private]); + assert_eq!( + endpoint.transport, + DatabaseTransport::PrivateNetworkPlaintext + ); + assert_eq!( + endpoint.product_url("owned", "runtime", "pw").unwrap(), + "postgresql://runtime:pw@172.20.0.7:5432/owned?sslmode=disable" + ); + let (explicit, selected) = + admin_config_with_resolver(&format!("{url}&sslmode=disable"), &move |_| { + Ok(vec![private]) + }) + .unwrap(); + assert_eq!(explicit.get_ssl_mode(), SslMode::Disable); + assert_eq!(explicit.get_hostaddrs(), &[private]); + assert_eq!( + selected.transport, + DatabaseTransport::PrivateNetworkPlaintext + ); + for addresses in [ + vec![private, std::net::IpAddr::from([203, 0, 113, 1])], + vec![std::net::IpAddr::from([169, 254, 169, 254])], + ] { + let error = admin_config_with_resolver(url, &move |_| Ok(addresses.clone())) + .err() + .expect("public or mixed answers must be refused") + .to_string(); + assert!(error.contains("private-network-plaintext"), "{error}"); + assert!(!error.contains("synthetic-url-value")); + } + for suffix in ["&sslmode=require", "&transport=private-network-plaintext"] { + assert!(admin_config_with_resolver(&format!("{url}{suffix}"), &|_| { + panic!("contradictory inputs must be refused before lookup"); + }) + .is_err()); + } + assert!(admin_config( + "postgresql://admin:synthetic-url-value@172.20.0.7/postgres?sslmode=disable" + ) + .is_err()); + } + + #[test] + fn private_admin_url_distinguishes_lookup_failure_from_refused_addresses() { + let base = + "postgresql://admin:synthetic-url-value@postgres.compose:5432/postgres?transport="; + for value in ["", "loopback-plaintext", "verified-tls"] { + assert!(admin_config_with_resolver(&format!("{base}{value}"), &|_| { + panic!("an invalid selector must be refused before lookup"); + }) + .is_err()); + } + let url = format!("{base}private-network-plaintext"); + let failure = admin_config_with_resolver(&url, &|_| { + Err(std::io::Error::other("synthetic-private-dns-error")) + }) + .err() + .unwrap(); + let refusal = + admin_config_with_resolver(&url, &|_| Ok(vec!["203.0.113.1".parse().unwrap()])) + .err() + .unwrap(); + for (error, code, class, message) in [ + (failure, 3, "operational", "could not resolve the PostgreSQL admin host for private-network-plaintext"), + (refusal, 1, "domain", "the PostgreSQL admin URL with private-network-plaintext must resolve only to permitted private or loopback addresses"), + ] { + let mut wire = Vec::new(); + crate::reply(&mut wire, &crate::WorkerReply::failed(&error)).unwrap(); + let crate::WorkerReply::Failed { error, operational } = serde_json::from_slice(&wire).unwrap() else { + panic!("a refused lookup must produce a worker failure"); + }; + let (report, exit_code) = crate::error_report(&crate::restore_failure(error, operational)); + assert_eq!(exit_code, code); + assert_eq!(report, serde_json::json!({ + "schema_version": "registry.rstack.error.v1", + "status": "refused", + "error": {"class": class, "message": message}, + })); + } + } + + #[test] + fn private_plaintext_tries_checked_candidates_in_order_and_pins_the_winner() { + let url = "postgresql://admin:synthetic-url-value@postgres.compose:5432/postgres?transport=private-network-plaintext"; + let addresses = ["172.20.0.7", "172.20.0.9", "172.20.0.11"].map(|ip| ip.parse().unwrap()); + let (checked, _) = + admin_config_with_resolver(url, &move |_| Ok(addresses.to_vec())).unwrap(); + let mut attempted = Vec::new(); + let (config, endpoint, ()) = + open_plaintext_candidates(url, checked.get_hostaddrs(), |config| { + let [address] = config.get_hostaddrs() else { + panic!("expected one checked candidate") + }; + attempted.push(*address); + if *address == addresses[0] { + bail!("first address refused") + } + Ok(()) + }) + .unwrap(); + assert_eq!(attempted, &addresses[..2]); + assert_eq!(config.get_hostaddrs(), &addresses[1..2]); + assert_eq!( + endpoint.product_url("owned", "runtime", "pw").unwrap(), + "postgresql://runtime:pw@172.20.0.9:5432/owned?sslmode=disable" + ); + } + #[test] fn spatial_runs_are_refused_without_a_supported_postgis() { assert!(require_postgis(Some("3.5.2")).is_ok()); @@ -2922,7 +3070,7 @@ mod postgres_tests { } } -/// Loopback plaintext attach against a real server without TLS. +/// Explicit plaintext attach against a real server without TLS. /// `RSTACK_DEV_TEST_PLAINTEXT_DATABASE_URL` names a disposable loopback /// PostgreSQL administrator URL with `?sslmode=disable`. Without the variable /// the test fails on the spot: a skipped database test is not database @@ -2979,5 +3127,35 @@ mod plaintext_postgres_tests { .cleanup() .expect("cleanup drops every provisioned database and role"); assert!(database.pending_names().is_empty()); + drop(database); + + // The workflow selects this test by its existing name. Exercise the + // private selector against the same disposable server on loopback. + let mut private_url = Url::parse(&admin_url).unwrap(); + private_url + .query_pairs_mut() + .append_pair("transport", "private-network-plaintext"); + let mut database = Database::connect(private_url.as_str(), None, &run_id) + .expect("attach over the explicitly selected private transport"); + let urls = database.provision("documents", false, false).unwrap(); + assert_eq!(urls.transport, DatabaseTransport::PrivateNetworkPlaintext); + let recorded_identity = database.recovery_identity().clone(); + let mut different_cluster = recorded_identity.clone(); + different_cluster.system_identifier ^= 1; + let names = database.pending_names(); + assert!(!names.is_empty()); + drop(database); + let refusal = + Database::connect_for_recovery(private_url.as_str(), None, &run_id, &different_cluster) + .err() + .expect("a different cluster cannot take over the run"); + assert!(format!("{refusal:#}").contains("different PostgreSQL cluster")); + let mut recovery = + Database::connect_for_recovery(private_url.as_str(), None, &run_id, &recorded_identity) + .expect("recover the private attachment from the recorded cluster"); + recovery.adopt("documents", false).unwrap(); + assert_eq!(recovery.pending_names(), names); + recovery.cleanup().unwrap(); + assert!(recovery.pending_names().is_empty()); } } diff --git a/crates/registry-rstack-dev/src/dev_facts.rs b/crates/registry-rstack-dev/src/dev_facts.rs index a1f471cd14..6d0f37aadc 100644 --- a/crates/registry-rstack-dev/src/dev_facts.rs +++ b/crates/registry-rstack-dev/src/dev_facts.rs @@ -40,6 +40,7 @@ pub(super) fn load( external_jwks_uri: Option<&str>, products: &[ProductPlan], clients: &BTreeSet, + completion_destination: Option<&str>, ) -> Result> { let scratch = tempfile::tempdir()?; let scratch_root = scratch.path().canonicalize()?; @@ -72,6 +73,7 @@ pub(super) fn load( issuer, external_jwks_uri, clients, + completion_destination, &terminate, ) })(); @@ -105,6 +107,7 @@ fn load_product_facts( issuer: &str, external_jwks_uri: Option<&str>, clients: &BTreeSet, + completion_destination: Option<&str>, terminate: &AtomicBool, ) -> Result { let product = plan.product; @@ -127,6 +130,7 @@ fn load_product_facts( issuer, external_jwks_uri, clients, + completion_destination, &file, terminate, )?; @@ -205,6 +209,7 @@ fn native_facts( issuer: &str, external_jwks_uri: Option<&str>, clients: &BTreeSet, + completion_destination: Option<&str>, output: &Path, terminate: &AtomicBool, ) -> Result<()> { @@ -227,7 +232,15 @@ fn native_facts( let config_file = if product == Product::Evidence { evidence_target(project, scratch, issuer, external_jwks_uri, &plan.audience)? } else { - let config = runtime_for_facts(plan, project, scratch, &package, issuer, clients)?; + let config = runtime_for_facts( + plan, + project, + scratch, + &package, + issuer, + clients, + completion_destination, + )?; write_private(&runtime, &serde_json::to_vec(&config)?)?; runtime }; @@ -329,6 +342,7 @@ fn runtime_for_facts( package: &Path, issuer: &str, clients: &BTreeSet, + completion_destination: Option<&str>, ) -> Result { let product = plan.product; let version = format!( @@ -379,6 +393,14 @@ fn runtime_for_facts( json!(clients); } } + // The run binds this destination to the Coordinator's completion + // endpoint, so the facts runtime declares it as the run will. + if let Some(destination) = completion_destination { + config["destinations"]["hooks"][destination] = json!({ + "url": format!("http://127.0.0.1:1{}", super::bindings::REVIEW_COMPLETIONS_PATH), + "hmacSha256KeyRef": "secret:file/coordinator-completion-key", + }); + } config["audit"] .as_object_mut() .expect("audit mapping") @@ -767,6 +789,42 @@ mod tests { assert!(coordinator_profiles_for_run(&runtime, &plan).is_err()); } + #[test] + fn casework_facts_configure_the_bound_completion_destination() { + let root = tempfile::tempdir().unwrap(); + let plan: ProductPlan = serde_json::from_value(json!({ + "product": "casework", "project": ".", "audience": "urn:casework", + })) + .unwrap(); + for destination in [None, Some("coordinator-wake")] { + let config = runtime_for_facts( + &plan, + root.path(), + root.path(), + &root.path().join("package"), + "https://issuer.example.test", + &BTreeSet::new(), + destination, + ) + .unwrap(); + let hooks = &config["destinations"]["hooks"]; + match destination { + None => assert!(config.get("destinations").is_none(), "{config}"), + Some(id) => { + assert_eq!(hooks.as_object().unwrap().len(), 1, "{config}"); + assert!(hooks[id]["url"] + .as_str() + .unwrap() + .ends_with(super::super::bindings::REVIEW_COMPLETIONS_PATH)); + assert!(hooks[id]["hmacSha256KeyRef"] + .as_str() + .unwrap() + .starts_with("secret:file/")); + } + } + } + } + #[test] fn evidence_facts_projection_uses_the_run_issuer_and_matching_claim_names() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/registry-rstack-dev/src/external_breg.rs b/crates/registry-rstack-dev/src/external_breg.rs index 47b6042554..31249ffe58 100644 --- a/crates/registry-rstack-dev/src/external_breg.rs +++ b/crates/registry-rstack-dev/src/external_breg.rs @@ -3,6 +3,7 @@ use anyhow::{ensure, Context, Result}; use registry_platform_config::{SecretProvider, SecretReference}; +use registry_platform_crypto::PrivateJwk; use registry_platform_yaml::{BoundedU32, LocalId, Url}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -16,7 +17,8 @@ use std::{ use zeroize::Zeroizing; use crate::plan::{ - identifier, numeric_loopback_endpoint, require, SemanticRefusal, SemanticResult, + identifier, issuer_url, numeric_loopback_endpoint, require, Plan, Product, SemanticRefusal, + SemanticResult, }; #[derive(Deserialize, Serialize)] @@ -71,6 +73,147 @@ pub(super) struct TaskGrant { status_resource: String, } +impl TaskGrant { + pub(super) fn require_distinct_status(&self, other: &Self, root: &Path) -> SemanticResult<()> { + require( + self.status_client != other.status_client, + "/externalScheduling/taskGrant/statusClient", + "Scheduling and BReg must use different task status clients.", + "Register a separate Scheduling task status client.", + )?; + let canonical = root.canonicalize().ok(); + let thumbprint = |reference| { + let key = private_fixture(canonical.as_deref()?, reference).ok()?; + PrivateJwk::parse(std::str::from_utf8(&key).ok()?) + .ok()? + .public() + .jkt() + .ok() + }; + let distinct = thumbprint(&self.status_key_ref) + .zip(thumbprint(&other.status_key_ref)) + .is_some_and(|(scheduling, breg)| scheduling != breg); + require( + distinct, + "/externalScheduling/taskGrant/statusKeyRef", + "Scheduling and BReg need valid, distinct private JWKs for task status.", + "Use a separate owner-only key for each task status client.", + ) + } + + /// Once people are resolved from their roles, the assertion client must + /// name exactly one planned Scheduling caller. + pub(super) fn validate_scheduling_caller(&self, plan: &Plan) -> SemanticResult<()> { + require( + plan.people + .values() + .filter(|person| { + person.client == self.assertion_client + && person.grants.contains_key(&Product::Scheduling) + }) + .count() + == 1, + "/externalScheduling/taskGrant/assertionClient", + "The assertion client must name exactly one planned Scheduling caller.", + "Use the exact external booking client in one Scheduling grant entry.", + ) + } + + pub(super) fn validate_for_scheduling( + &self, + root: &Path, + plan: &Plan, + audience: &str, + ) -> SemanticResult<()> { + let same_origin = |endpoint: &str| { + url::Url::parse(endpoint) + .ok() + .zip(url::Url::parse(&plan.issuer).ok()) + .is_some_and(|(endpoint, issuer)| endpoint.origin() == issuer.origin()) + }; + require( + plan.jwks_uri().is_some_and(same_origin), + "/externalJwksUri", + "The Scheduling fixture issuer and its key endpoint must have the same origin.", + "Use the key endpoint published by the configured external issuer.", + )?; + let check = |valid, field, reason, remedy| { + require( + valid, + &format!("/externalScheduling/taskGrant/{field}"), + reason, + remedy, + ) + }; + check( + issuer_url(self.source_issuer.as_str()), + "sourceIssuer", + "The Scheduling fixture needs an exact HTTPS assertion issuer name.", + "Use the issuer name in the Casework task grant.", + )?; + check( + identifier(&self.assertion_client), + "assertionClient", + "The assertion client must name exactly one planned Scheduling caller.", + "Use the exact external booking client in one Scheduling grant entry.", + )?; + check( + crate::products::is_loopback_run_issuer(self.status_url.as_str()), + "statusUrl", + "The task status connection must use a numeric loopback HTTP origin.", + "Use the exact Casework status service origin with its port.", + )?; + check( + numeric_loopback_endpoint(self.token_endpoint.as_str()) + && same_origin(self.token_endpoint.as_str()), + "tokenEndpoint", + "The task status token endpoint must use the exact external issuer origin.", + "Use the token endpoint published by the configured external issuer.", + )?; + check( + identifier(&self.status_client) && self.status_client != self.assertion_client, + "statusClient", + "The task status client must have its own identifier.", + "Use a separate external client registered for task status reads.", + )?; + check( + registry_platform_httputil::valid_resource_uri(audience) + && registry_platform_httputil::valid_resource_uri(&self.status_resource) + && self.status_resource != audience, + "statusResource", + "The status resource must be an absolute URI distinct from the Scheduling audience.", + "Use the Casework status resource configured for the status client.", + )?; + check( + root.canonicalize() + .is_ok_and(|root| private_fixture(&root, &self.status_key_ref).is_ok()), + "statusKeyRef", + "The task status key must be a readable owner-only fixture file.", + "Use a secret:file reference to the separate status key under fixture/ with mode 0600.", + ) + } + + pub(super) fn configure( + &self, + store: impl FnOnce(&[u8]) -> Result, + root: &Path, + issuer: &str, + config: &mut Value, + ) -> Result<()> { + let key = private_fixture(root, &self.status_key_ref)?; + let private_key_ref = store(&key)?; + config["authentication"]["oidc"]["issuers"]["main"]["assertionIssuers"] + [&self.assertion_client] = json!([self.source_issuer]); + config["taskGrantStatus"] = json!([{ + "sourceIssuer": self.source_issuer, "baseUrl": self.status_url, + "tokenEndpoint": self.token_endpoint, "clientAssertionAudience": issuer, + "clientId": self.status_client, "privateKeyRef": private_key_ref, + "statusResource": self.status_resource + }]); + Ok(()) + } +} + #[derive(Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -243,15 +386,12 @@ impl ExternalBreg { }); } if let Some(grant) = &self.task_grant { - let key = private_fixture(root, &grant.status_key_ref)?; - config["authentication"]["oidc"]["issuers"]["main"]["assertionIssuers"] - [&grant.assertion_client] = json!([grant.source_issuer]); - config["taskGrantStatus"] = json!([{ - "sourceIssuer": grant.source_issuer, "baseUrl": grant.status_url, - "tokenEndpoint": grant.token_endpoint, "clientAssertionAudience": issuer, - "clientId": grant.status_client, "privateKeyRef": store("external-task-status-key", &key)?, - "statusResource": grant.status_resource - }]); + grant.configure( + |key| store("external-task-status-key", key), + root, + issuer, + config, + )?; } Ok(()) } @@ -284,8 +424,56 @@ fn require_loopback_endpoint(field: &str, value: &str) -> SemanticResult<()> { #[cfg(test)] mod tests { use super::*; + use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; use std::{fs, os::unix::fs::PermissionsExt}; + #[test] + fn scheduling_and_breg_status_clients_and_signing_keys_are_separate() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().canonicalize().unwrap(); + std::fs::create_dir(root.join("fixture")).unwrap(); + let key = generate_private_jwk(GeneratedKeyAlgorithm::Ed25519).unwrap(); + let mut same_key = key.clone(); + same_key.kid = Some("renamed-key".to_owned()); + let different_key = generate_private_jwk(GeneratedKeyAlgorithm::Ed25519).unwrap(); + for (path, key) in [ + ("breg-key", key), + ("same-key", same_key), + ("scheduling-key", different_key), + ] { + let bytes = crate::bindings::encode_private_jwk(&key).unwrap(); + crate::write_private(&root.join("fixture").join(path), &bytes).unwrap(); + } + let grant = |client, name| -> TaskGrant { + serde_json::from_value(json!({ + "sourceIssuer": "https://casework.journey.example", + "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "statusClient": client, + "statusKeyRef": format!("secret:file/{name}"), + "statusResource": "urn:example:journey:casework" + })) + .unwrap() + }; + let breg = grant("breg-status", "breg-key"); + for (client, file, field) in [ + ("breg-status", "scheduling-key", "statusClient"), + ("scheduling-status", "breg-key", "statusKeyRef"), + ("scheduling-status", "same-key", "statusKeyRef"), + ] { + let refusal = grant(client, file) + .require_distinct_status(&breg, &root) + .unwrap_err(); + assert!(refusal + .to_string() + .starts_with(&format!("dev.yaml /externalScheduling/taskGrant/{field}:"))); + } + grant("scheduling-status", "scheduling-key") + .require_distinct_status(&breg, &root) + .unwrap(); + } + #[test] fn fixture_keys_refuse_group_access_symlinks_and_paths_outside_the_project() { let scratch = tempfile::tempdir().unwrap(); diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index aeedf1dc89..4b350848a6 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -22,6 +22,7 @@ mod external_breg; pub(crate) mod guard; mod issuer; mod journey; +mod owner_report; pub(crate) mod plan; mod preview; mod products; @@ -124,6 +125,9 @@ enum Entry { deny_warnings: bool, #[arg(long)] json: bool, + #[arg(long, value_enum)] + owner_report_format: Option, + /// Plan directory, or the saved JSON file when an owner report format is selected. project: PathBuf, }, Start { @@ -609,11 +613,24 @@ pub fn run(args: Args, stdout: &mut dyn Write, stderr: &mut dyn Write) -> ExitCo project, deny_warnings, json, + owner_report_format, } => { + if let Some(format) = owner_report_format { + let (report, mut exit) = owner_report::check_file(&project, format); + if exit == 0 + && deny_warnings + && registry_platform_config::has_denied_warnings(report.diagnostics()) + { + exit = DOMAIN_REFUSAL_EXIT; + } + return ExitCode::from(write_check_report( + report, exit, json, stdout, stderr, true, + )); + } if let Err((code, message, action)) = require_development(declared(None)) { let report = Report::new(vec![Diagnostic::error(code, "", message, action)]); return ExitCode::from(write_check_report( - report, USAGE_EXIT, json, stdout, stderr, + report, USAGE_EXIT, json, stdout, stderr, false, )); } return ExitCode::from(check(&project, deny_warnings, json, stdout, stderr)); @@ -738,6 +755,20 @@ fn error_report(error: &anyhow::Error) -> (Value, u8) { (report, code) } +/// The substitution a multi-actor preview makes for development. +const PREVIEW_ACTOR_SUBSTITUTION: &str = "per-actor gateway origin (development)"; + +/// Report each actor's origin and append the development substitution: one +/// gateway origin per actor, over the same page bytes, stands in for one +/// origin with sign-in. +fn add_preview_actors(report: &mut Value, actors: &BTreeMap) { + report["previewActors"] = json!(actors); + match report["substitutions"].as_array_mut() { + Some(substitutions) => substitutions.push(json!(PREVIEW_ACTOR_SUBSTITUTION)), + None => report["substitutions"] = json!([PREVIEW_ACTOR_SUBSTITUTION]), + } +} + fn emit(output: &mut dyn Write, report: &Value, machine: bool) -> std::io::Result<()> { if machine { return writeln!(output, "{report}"); @@ -845,6 +876,20 @@ fn emit(output: &mut dyn Write, report: &Value, machine: bool) -> std::io::Resul if let Some(application) = report["application"].as_str() { writeln!(output, " Application {application}")?; } + for (name, origin) in report["previewActors"].as_object().into_iter().flatten() { + writeln!( + output, + " Actor {name} {}", + origin.as_str().unwrap_or_default() + )?; + } + for substitution in report["substitutions"].as_array().into_iter().flatten() { + writeln!( + output, + " Substitution {}", + substitution.as_str().unwrap_or_default() + )?; + } for journey in report["scenarios"].as_array().into_iter().flatten() { let Some(result) = journey["result"].as_str() else { continue; @@ -922,18 +967,21 @@ fn check( Ok(report) => (report, DOMAIN_REFUSAL_EXIT), Err(error) => { if let Some(unavailable) = error.downcast_ref::() { - let report = Report::new(vec![Diagnostic::error( + let mut diagnostic = Diagnostic::error( "rstack.dev.check-unavailable", unavailable.field(), unavailable.reason(), unavailable.remedy(), - )]); + ); + diagnostic.source = unavailable.location().cloned(); + let report = Report::new(vec![diagnostic]); return write_check_report( report, OPERATIONAL_FAILURE_EXIT, machine, stdout, stderr, + false, ); } let (code, action, exit) = if error.is::() { @@ -956,7 +1004,7 @@ fn check( } }, }; - write_check_report(report, exit, machine, stdout, stderr) + write_check_report(report, exit, machine, stdout, stderr, false) } fn write_check_report( @@ -965,20 +1013,28 @@ fn write_check_report( machine: bool, stdout: &mut dyn Write, stderr: &mut dyn Write, + structure_only: bool, ) -> u8 { let result = if machine { - let payload = json!({ + let mut payload = json!({ "ok": exit == 0, "command": "dev-check", "status": registry_cli_report::Status::from_exit(exit).as_str(), "diagnostics": report.to_json_value(), }); + if structure_only { + payload["assessment"] = json!("owner-report-structure"); + } write_check_json(stdout, payload) .map_err(io::Error::other) .and_then(|()| writeln!(stdout)) } else if exit == 0 { - writeln!(stdout, "Development plan is valid") - .and_then(|()| write!(stdout, "{}", report.render_human())) + let message = if structure_only { + "Owner report structure is valid" + } else { + "Development plan is valid" + }; + writeln!(stdout, "{message}").and_then(|()| write!(stdout, "{}", report.render_human())) } else { write!(stderr, "{}", report.render_human()) }; @@ -1513,6 +1569,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { .as_ref() .map(|_| root.join("application-preview")); let mut preview_signer = None; + let mut preview_actors = None; let prepared = catch_startup(|| { products.capture_preview_project()?; products.check()?; @@ -1690,6 +1747,7 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { preview::authorization(root, &input, &issuer, clock()? + input.ttl_seconds)?; let prepared = products.prepare_application(&urls, Some((artifact, &authorization_file)))?; + let actors = prepared.actors.clone(); let origin = products.start_application(prepared.launch)?; let page = &input .plan @@ -1698,6 +1756,12 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { .context("missing preview page")? .page; application_url = Some(format!("{origin}{page}")); + preview_actors = (!actors.is_empty()).then(|| { + actors + .iter() + .map(|(name, origin)| (name.clone(), format!("{origin}{page}"))) + .collect::>() + }); preview_signer = Some(issuer); } let expires_at = clock()? + input.ttl_seconds; @@ -1734,6 +1798,10 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { if let Some(hook_sink) = products.breg_hook_report() { report["bregHookSink"] = hook_sink; } + let hook_sinks = products.signed_hook_reports(); + if !hook_sinks.is_empty() { + report["hookSinks"] = json!(hook_sinks); + } let created_keys = products.created_kept_keys(); if !created_keys.is_empty() { report["createdKeptKeys"] = json!(created_keys.as_slice()); @@ -1748,6 +1816,9 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { (url, issuer) }); add_run_addresses(&mut report, &input.plan, application); + if let Some(actors) = &preview_actors { + add_preview_actors(&mut report, actors); + } if let (Some(state), Some(key)) = (&project_state, &input.project_key) { write_private(&state.join(format!("run-{}", input.run_id)), key.as_bytes())?; @@ -2742,9 +2813,30 @@ fn remove_run_dir(root: &Path) -> Result<()> { } _ => {} } - match fs::remove_file(root.join(preview::AUTHORIZATION_FILE)) { + for entry in fs::read_dir(root).context("cannot read the run directory")? { + let entry = entry.context("cannot read the run directory")?; + if entry + .file_name() + .to_str() + .is_some_and(|name| name.starts_with(preview::AUTHORIZATION_FILE)) + { + match fs::remove_file(entry.path()) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error).context("cannot remove the run's preview authorization"); + } + _ => {} + } + } + } + match fs::remove_file(root.join(products::FUNCTION_HOST_KEY)) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error).context("cannot remove the run's preview function host key"); + } + _ => {} + } + match fs::remove_file(root.join(bindings::COORDINATOR_COMPLETION_KEY)) { Err(error) if error.kind() != std::io::ErrorKind::NotFound => { - return Err(error).context("cannot remove the run's preview authorization"); + return Err(error).context("cannot remove the run's review completion key"); } _ => {} } @@ -3120,6 +3212,46 @@ mod tests { assert!(text.contains("Application http://127.0.0.1:4201"), "{text}"); } + #[test] + fn preview_actors_append_the_development_substitution_and_print_each_origin() { + let mut report = json!({ + "run_id": RUN_ID, "status": "ready", + "application": "http://127.0.0.1:4201/", + "substitutions": ["earlier substitution"], + }); + add_preview_actors( + &mut report, + &BTreeMap::from([ + ("applicant".to_owned(), "http://127.0.0.1:4201/".to_owned()), + ("officer".to_owned(), "http://127.0.0.1:4202/".to_owned()), + ]), + ); + assert_eq!( + report["substitutions"], + json!(["earlier substitution", PREVIEW_ACTOR_SUBSTITUTION]) + ); + assert_eq!( + report["previewActors"], + json!({"applicant": "http://127.0.0.1:4201/", "officer": "http://127.0.0.1:4202/"}) + ); + let mut output = Vec::new(); + emit(&mut output, &report, false).unwrap(); + let text = String::from_utf8(output).unwrap(); + assert!( + text.contains(" Actor applicant http://127.0.0.1:4201/\n"), + "{text}" + ); + assert!( + text.contains(" Actor officer http://127.0.0.1:4202/\n"), + "{text}" + ); + assert!( + text.contains(" Substitution earlier substitution\n") + && text.contains(" Substitution per-actor gateway origin (development)\n"), + "{text}" + ); + } + #[test] fn human_run_report_gives_each_product_one_line_that_starts_with_its_name() { // The tutorials read a product's address with @@ -3893,6 +4025,19 @@ mod tests { let root = base.join(RUN_ID); private_directory(&root).unwrap(); fs::write(root.join(products::FIELD_KEY), "key").unwrap(); + fs::write(root.join(products::FUNCTION_HOST_KEY), "host-key").unwrap(); + fs::write( + root.join(bindings::COORDINATOR_COMPLETION_KEY), + "completion-key", + ) + .unwrap(); + let actor_files = [ + format!("{}-applicant-breg", preview::AUTHORIZATION_FILE), + format!("{}-officer-casework", preview::AUTHORIZATION_FILE), + ]; + for file in &actor_files { + fs::write(root.join(file), "Authorization: Bearer token\n").unwrap(); + } fs::write(root.join(REPORT), "{}").unwrap(); // A non-empty directory at the removal name makes the rename fail, as // an interrupted deletion would leave the run behind. @@ -3902,6 +4047,11 @@ mod tests { assert!(remove_run_dir(&root).is_err()); assert!(!root.join(products::FIELD_KEY).exists()); + assert!(!root.join(products::FUNCTION_HOST_KEY).exists()); + assert!(!root.join(bindings::COORDINATOR_COMPLETION_KEY).exists()); + for file in &actor_files { + assert!(!root.join(file).exists(), "{file}"); + } assert!(root.join(REPORT).exists()); } diff --git a/crates/registry-rstack-dev/src/owner_report.rs b/crates/registry-rstack-dev/src/owner_report.rs new file mode 100644 index 0000000000..95477b8fa4 --- /dev/null +++ b/crates/registry-rstack-dev/src/owner_report.rs @@ -0,0 +1,647 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Structural read-back of bounded saved JSON reports. + +use jsonschema::{ + error::{ErrorIterator, ValidationErrorKind}, + paths::{JSONPointer, JsonPointerNode, PathChunk}, + Draft, JSONSchema, Keyword, ValidationError, +}; +use registry_platform_yaml::{ + escape_pointer_segment, ApiVersion, Diagnostic, Document, EnvelopeRule, Expect, FormatSpec, + Reader, Report, Severity, Source, MAXIMUM_DOCUMENT_BYTES, +}; +use serde_json::{json, Value}; +use std::{ + borrow::Cow, + collections::{BTreeMap, BTreeSet}, + fs::OpenOptions, + io::{self, Read}, + os::unix::fs::OpenOptionsExt, + path::Path, + sync::OnceLock, +}; + +const CASEWORK: &str = include_str!("../../../products/casework/contracts/cli/report.schema.json"); +const BREG_IDENTITY_FACTS: &str = + include_str!("../../../products/breg/generated/tools/ctl-report.v1alpha1.schema.json"); +const CASEWORK_FORMAT: FormatSpec<'static> = FormatSpec { + kind: "CaseworkReport", + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current( + "id.registrystack.org/formats/casework/report/v1alpha2", + )], + retired_api_versions: &[], + }, + removed_keys: &[], +}; +const BREG_REPORT_FORMAT: FormatSpec<'static> = FormatSpec { + kind: "BRegCtlReport", + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current( + "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + )], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] +pub(crate) enum Format { + CaseworkReport, + BregIdentityFactsReport, +} + +impl Format { + fn spec(self) -> &'static FormatSpec<'static> { + match self { + Self::CaseworkReport => &CASEWORK_FORMAT, + Self::BregIdentityFactsReport => &BREG_REPORT_FORMAT, + } + } +} + +#[derive(Debug)] +pub(crate) struct Invalid { + path: String, + code: &'static str, + message: Cow<'static, str>, + position: Option<(usize, usize)>, + schema_unavailable: bool, +} + +impl Invalid { + fn at(path: impl Into, message: &'static str) -> Self { + Self { + path: path.into(), + code: "rstack.dev.owner-report-invalid", + message: Cow::Borrowed(message), + position: None, + schema_unavailable: false, + } + } + + fn into_report(self, file: &str, format: Format) -> (Report, u8) { + let (exit, code, remedy) = if self.schema_unavailable { + ( + crate::OPERATIONAL_FAILURE_EXIT, + "rstack.dev.owner-report-schema-unavailable", + "Use an rstack development host with a valid embedded owner report schema.", + ) + } else { + (crate::DOMAIN_REFUSAL_EXIT, self.code, FORMAT_REMEDY) + }; + let mut diagnostic = Diagnostic::error(code, self.path, self.message, remedy); + diagnostic.artifact = Some(format.spec().kind.to_owned()); + diagnostic.source = Some(Source { + file: file.to_owned(), + line: self.position.map(|(line, _)| line), + column: self + .position + .and_then(|(_, column)| (column > 0).then_some(column)), + }); + let mut report = Report::new(vec![diagnostic]); + report.set_files_checked(1); + (report, exit) + } +} + +fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAXIMUM_DOCUMENT_BYTES { + return Err(Invalid::at("", "Owner report exceeds the 1 MiB limit")); + } + registry_platform_canonical_json::parse_json_preserving_integers(bytes).map_err(|error| { + Invalid { + position: parse_position(bytes, error.line(), error.column()), + ..Invalid::at( + "", + "Expected one valid JSON document with unique member names", + ) + } + }) +} + +fn parse_position(bytes: &[u8], line: usize, byte_column: usize) -> Option<(usize, usize)> { + let line_bytes = bytes + .split(|byte| *byte == b'\n') + .nth(line.checked_sub(1)?)?; + let prefix = &line_bytes[..byte_column.saturating_sub(1).min(line_bytes.len())]; + Some((line, String::from_utf8_lossy(prefix).chars().count() + 1)) +} + +fn check_bytes(file: &str, bytes: &[u8], format: Format) -> (Report, u8) { + let report = match parse(bytes) { + Ok(report) => report, + Err(error) => return error.into_report(file, format), + }; + // The JSON parser enforces the declared syntax. The shared reader checks + // the envelope and retains positions for every schema diagnostic. + let document = match Reader::new(file).read(bytes, &Expect::one(format.spec())) { + Ok(document) => document, + Err(mut report) => { + redact_structure(&mut report, format); + return (report, crate::DOMAIN_REFUSAL_EXIT); + } + }; + let issues = match validate(&report, format, Some(&document)) { + Ok(issues) => issues, + Err(error) => return error.into_report(file, format), + }; + let mut report = document.report_with(issues.into_iter().map(|issue| { + let mut diagnostic = document.diagnostic_at_value( + Severity::Error, + issue.code, + &issue.path, + &issue.message, + FORMAT_REMEDY, + ); + if let (Some((line, column)), Some(source)) = (issue.position, &mut diagnostic.source) { + source.line = Some(line); + source.column = Some(column); + } + diagnostic + })); + redact_warnings(&mut report); + let exit = u8::from(report.has_errors()); + (report, exit) +} + +const FORMAT_REMEDY: &str = + "Select the matching owner report format and capture a fresh report as JSON."; + +fn redact_structure(report: &mut Report, format: Format) { + let message = match format { + Format::CaseworkReport => "Expected a valid CaseworkReport v1alpha2 envelope and document", + Format::BregIdentityFactsReport => { + "Expected a valid BRegCtlReport v1alpha1 envelope and document" + } + }; + for diagnostic in report.diagnostics_mut() { + if diagnostic.code == "config.too-many-problems" { + continue; + } + if !matches!(diagnostic.path.as_str(), "/kind" | "/apiVersion") { + diagnostic.path.clear(); + } + diagnostic.message = message.to_owned(); + diagnostic.suggested_action = FORMAT_REMEDY.to_owned(); + diagnostic.related.clear(); + } +} + +fn redact_warnings(report: &mut Report) { + for diagnostic in report.diagnostics_mut() { + if diagnostic.severity == Severity::Warning { + diagnostic.path.clear(); + diagnostic.message = "Owner report uses a deprecated document form".to_owned(); + diagnostic.suggested_action = FORMAT_REMEDY.to_owned(); + diagnostic.related.clear(); + } + } +} + +fn validate( + report: &Value, + format: Format, + document: Option<&Document>, +) -> Result, Invalid> { + match format { + Format::CaseworkReport => validate_casework(report, document), + Format::BregIdentityFactsReport => { + static SCHEMA: OnceLock> = OnceLock::new(); + let schema = SCHEMA + .get_or_init(|| compile(serde_json::from_str(BREG_IDENTITY_FACTS).ok()?)) + .as_ref() + .ok_or_else(schema_unavailable)?; + Ok(schema.issues(report, "", document)) + } + } +} + +struct CaseworkSchemas { + family: Schema, + branches: BTreeMap, +} + +fn validate_casework(report: &Value, document: Option<&Document>) -> Result, Invalid> { + static SCHEMAS: OnceLock> = OnceLock::new(); + let schemas = SCHEMAS.get_or_init(|| { + let mut schema: Value = serde_json::from_str(CASEWORK).ok()?; + let mut branches = BTreeMap::new(); + for branch in schema["oneOf"].as_array()? { + // The generated family consists of closed branches with distinct command constants. + if branch["additionalProperties"] != false { + return None; + } + let command = branch.pointer("/properties/command/const")?.as_str()?; + let mut branch = branch.clone(); + branch["$defs"] = schema["$defs"].clone(); + if branches + .insert(command.to_owned(), compile(branch)?) + .is_some() + { + return None; + } + } + // Every selected command branch already rejects undeclared fields. + // jsonschema 0.18 misattributes evaluated properties across the root + // applicators, so compile the family without the redundant closure. + if schema.as_object_mut()?.remove("unevaluatedProperties") != Some(json!(false)) { + return None; + } + Some(CaseworkSchemas { + family: compile(schema)?, + branches, + }) + }); + let schemas = schemas.as_ref().ok_or_else(schema_unavailable)?; + let branch = report["command"] + .as_str() + .and_then(|command| schemas.branches.get(command)); + let Some(branch) = branch else { + return Ok(vec![Invalid::at( + if report.get("command").is_some() { + "/command" + } else { + "" + }, + "Expected a command from the Casework report contract", + )]); + }; + // Validate the selected branch first to retain its field-level diagnostics. + // The family also imposes shared completion and refusal rules at the root. + let issues = branch.issues(report, "", document); + if issues.is_empty() { + Ok(schemas.family.issues(report, "", document)) + } else { + Ok(issues) + } +} + +fn schema_unavailable() -> Invalid { + Invalid { + schema_unavailable: true, + ..Invalid::at("", "The embedded owner report schema could not be loaded") + } +} + +const MAX_DIAGNOSTIC_NODES: usize = 256; +const MAX_DIAGNOSTIC_TEXT_BYTES: usize = 16 * 1024; + +struct Schema { + validator: JSONSchema, + document: Value, +} + +impl Schema { + fn issues(&self, value: &Value, prefix: &str, document: Option<&Document>) -> Vec { + if self.validator.is_valid(value) { + return Vec::new(); + } + let fallback = || Invalid::at(prefix, "Owner report violates the selected schema"); + // Detailed validation eagerly collects child errors for array items. + let mut nodes = MAX_DIAGNOSTIC_NODES; + let mut text_bytes = MAX_DIAGNOSTIC_TEXT_BYTES; + if !fits_diagnostic_budget(value, &mut nodes, &mut text_bytes) { + return vec![fallback()]; + } + let Err(errors) = self.validator.validate(value) else { + return vec![fallback()]; + }; + let mut issues = Vec::new(); + let mut seen = BTreeSet::new(); + for error in errors { + let (path, instance_schema) = self.diagnostic_path(prefix, &error.instance_path); + let raw_parent = error.instance_path.to_string(); + if let ValidationErrorKind::AdditionalProperties { unexpected } = &error.kind { + for key in unexpected { + // Use the unknown key to locate it, then report only the safe parent. + let raw = format!("{raw_parent}/{}", escape_pointer_segment(key)); + let position = document + .and_then(|doc| doc.key_span_of(&raw)) + .map(|span| (span.start.line, span.start.column)); + let issue = Invalid { + code: "config.unknown-key", + position, + ..Invalid::at( + path.clone(), + "Owner report contains a member outside the selected schema", + ) + }; + issues.push(issue); + } + continue; + } + let mut issue = Invalid::at( + path, + "Owner report violates the selected schema at this location", + ); + issue.position = document + .and_then(|doc| doc.span_of(&raw_parent)) + .map(|span| (span.start.line, span.start.column)); + match &error.kind { + ValidationErrorKind::Minimum { .. } + | ValidationErrorKind::Maximum { .. } + | ValidationErrorKind::Custom { .. } => { + if let Some((minimum, maximum)) = + self.error_integer_bounds(&error, instance_schema) + { + issue.code = if integer(&error.instance).is_some() { + "config.out-of-range" + } else { + "config.wrong-type" + }; + issue.message = + format!("Expected a JSON integer from {minimum} to {maximum}").into(); + } + } + ValidationErrorKind::Required { property } => { + issue.code = "config.missing-key"; + if let Some(key) = property.as_str() { + issue.message = format!("Owner report requires the {key} member").into(); + } + issue.position = document + .and_then(|doc| doc.key_span_of(&raw_parent)) + .map(|span| (span.start.line, span.start.column)) + .or(issue.position); + } + _ => {} + } + if seen.insert(( + issue.path.clone(), + issue.position, + issue.code, + issue.message.clone(), + )) { + issues.push(issue); + } + } + issues + } + + fn error_integer_bounds( + &self, + error: &ValidationError<'_>, + instance_schema: Option<&Value>, + ) -> Option<(i128, i128)> { + let schema_path = error.schema_path.to_string(); + // A validator can report the path through a reference rather than the + // definition that holds the bounds. Use the instance schema when the + // path resolves entirely through declared properties and array items. + let reported = schema_path + .rsplit_once('/') + .and_then(|(parent, _)| self.document.pointer(parent)); + [reported, instance_schema] + .into_iter() + .flatten() + .filter_map(Value::as_object) + .find(|schema| schema.contains_key(EXACT_INTEGER)) + .map(exact_integer_bounds) + } + + fn diagnostic_path( + &self, + prefix: &str, + instance_path: &JSONPointer, + ) -> (String, Option<&Value>) { + let mut path = prefix.to_owned(); + let mut schema = &self.document; + for part in instance_path { + let Some(resolved) = self.resolve_path_schema(schema) else { + return (path, None); + }; + // Only literal properties and array items establish a safe path. + // Dynamic map members and ambiguous schema positions end the path. + match part { + PathChunk::Property(name) => { + let Some(child) = resolved["properties"].get(name.as_ref()) else { + return (path, None); + }; + schema = child; + path.push('/'); + path.push_str(&escape_pointer_segment(name)); + } + PathChunk::Index(index) => { + let Some(child) = resolved["prefixItems"] + .get(*index) + .or_else(|| resolved.get("items")) + else { + return (path, None); + }; + schema = child; + path.push('/'); + path.push_str(&index.to_string()); + } + PathChunk::Keyword(_) => return (path, None), + } + } + (path, self.resolve_path_schema(schema)) + } + + fn resolve_path_schema<'a>(&'a self, mut schema: &'a Value) -> Option<&'a Value> { + for _ in 0..16 { + let Some(reference) = schema.get("$ref") else { + return Some(schema); + }; + let pointer = reference.as_str()?.strip_prefix('#')?; + schema = self.document.pointer(pointer)?; + } + None + } +} + +fn fits_diagnostic_budget(value: &Value, nodes: &mut usize, text_bytes: &mut usize) -> bool { + let Some(remaining) = nodes.checked_sub(1) else { + return false; + }; + *nodes = remaining; + match value { + Value::Array(items) => items + .iter() + .all(|item| fits_diagnostic_budget(item, nodes, text_bytes)), + Value::Object(fields) => fields.iter().all(|(key, value)| { + spend_text_budget(key, text_bytes) && fits_diagnostic_budget(value, nodes, text_bytes) + }), + Value::String(text) => spend_text_budget(text, text_bytes), + _ => true, + } +} + +fn spend_text_budget(text: &str, budget: &mut usize) -> bool { + let Some(remaining) = budget.checked_sub(text.len()) else { + return false; + }; + *budget = remaining; + true +} + +const EXACT_INTEGER: &str = "x-rstack-report-integer"; + +fn compile(mut document: Value) -> Option { + annotate(&mut document); + let validator = JSONSchema::options() + .with_draft(Draft::Draft202012) + .with_keyword(EXACT_INTEGER, exact_integer) + .compile(&document) + .ok()?; + Some(Schema { + validator, + document, + }) +} + +// Add integer-token checks to compiler input only. The standard validator still +// applies the generated schema and resolves references and union arms normally. +fn annotate(schema: &mut Value) { + if schema["type"] == "integer" + || schema["type"] + .as_array() + .is_some_and(|types| types.iter().any(|ty| ty == "integer")) + { + schema[EXACT_INTEGER] = json!(true); + } + for key in [ + "properties", + "$defs", + "patternProperties", + "dependentSchemas", + ] { + if let Some(children) = schema.get_mut(key).and_then(Value::as_object_mut) { + for child in children.values_mut() { + annotate(child); + } + } + } + for key in ["oneOf", "anyOf", "allOf", "prefixItems"] { + if let Some(children) = schema.get_mut(key).and_then(Value::as_array_mut) { + for child in children { + annotate(child); + } + } + } + for key in [ + "items", + "additionalProperties", + "if", + "then", + "else", + "not", + "contains", + ] { + if let Some(child) = schema.get_mut(key) { + annotate(child); + } + } +} + +fn integer(value: &Value) -> Option { + value + .as_u64() + .map(i128::from) + .or_else(|| value.as_i64().map(i128::from)) +} + +struct ExactInteger { + path: JSONPointer, + minimum: i128, + maximum: i128, + nullable: bool, +} + +#[expect( + clippy::result_large_err, + reason = "jsonschema requires its keyword factory to return ValidationError by value" +)] +fn exact_integer<'a>( + parent: &'a serde_json::Map, + _: &'a Value, + path: JSONPointer, +) -> Result, ValidationError<'a>> { + let (minimum, maximum) = exact_integer_bounds(parent); + let nullable = parent + .get("type") + .and_then(Value::as_array) + .is_some_and(|types| types.iter().any(|ty| ty == "null")); + Ok(Box::new(ExactInteger { + path, + minimum, + maximum, + nullable, + })) +} + +fn exact_integer_bounds(parent: &serde_json::Map) -> (i128, i128) { + let minimum = parent + .get("minimum") + .and_then(integer) + .unwrap_or(i128::from(i64::MIN)); + let mut maximum = parent + .get("maximum") + .and_then(integer) + .unwrap_or(i128::from(u64::MAX)); + if parent.get("format").and_then(Value::as_str) == Some("uint") { + maximum = maximum.min(usize::MAX as i128); + } + (minimum, maximum) +} + +impl Keyword for ExactInteger { + fn is_valid(&self, value: &Value) -> bool { + (self.nullable && value.is_null()) + || integer(value).is_some_and(|n| (self.minimum..=self.maximum).contains(&n)) + } + + fn validate<'a>(&self, value: &'a Value, path: &JsonPointerNode) -> ErrorIterator<'a> { + if self.is_valid(value) { + Box::new(std::iter::empty()) + } else { + Box::new(std::iter::once(ValidationError::custom( + self.path.clone(), + path.clone().into(), + value, + "Expected a bounded native integer", + ))) + } + } +} + +pub(crate) fn check_file(path: &Path, format: Format) -> (Report, u8) { + let file = OpenOptions::new() + .read(true) + .custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32) + .open(path); + let bytes = file.and_then(|file| { + if !file.metadata()?.is_file() { + return Err(io::Error::other("expected a regular file")); + } + let mut bytes = Vec::new(); + file.take(MAXIMUM_DOCUMENT_BYTES as u64 + 1) + .read_to_end(&mut bytes)?; + Ok(bytes) + }); + let file = path.to_string_lossy(); + match bytes { + Ok(bytes) => check_bytes(&file, &bytes, format), + Err(_) => { + let mut diagnostic = Diagnostic::error( + "rstack.dev.owner-report-unreadable", + "", + "Cannot read the owner report as a regular file", + "Pass a readable regular JSON file to --owner-report.", + ); + diagnostic.source = Some(Source { + file: file.into_owned(), + line: None, + column: None, + }); + ( + Report::new(vec![diagnostic]), + crate::OPERATIONAL_FAILURE_EXIT, + ) + } + } +} + +#[cfg(test)] +#[path = "owner_report_tests.rs"] +mod tests; diff --git a/crates/registry-rstack-dev/src/owner_report_tests.rs b/crates/registry-rstack-dev/src/owner_report_tests.rs new file mode 100644 index 0000000000..4a7c1704e9 --- /dev/null +++ b/crates/registry-rstack-dev/src/owner_report_tests.rs @@ -0,0 +1,304 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +const CASEWORK: &str = + include_str!("../../../products/casework/examples/formats/reports/check-report.json"); +const BREG_IDENTITY_FACTS: &str = + include_str!("../../../products/breg/examples/formats/identity-facts-report.json"); + +fn decode(bytes: &[u8], format: Format) -> Result<(), Box> { + let (report, exit) = check_bytes("synthetic.json", bytes, format); + if exit == 0 { + Ok(()) + } else { + Err(Box::new( + report.into_diagnostics().into_iter().next().unwrap(), + )) + } +} + +#[test] +fn casework_checks_resolved_branch_and_exact_numeric_tokens() { + let report = |count: &str| { + let value: Value = serde_json::from_str(CASEWORK).unwrap(); + let marker = "replace-count"; + let mut value = value; + value["filesChecked"] = json!(marker); + serde_json::to_string(&value) + .unwrap() + .replace(&format!("\"{marker}\""), count) + }; + for count in ["0", &usize::MAX.to_string()] { + assert!(decode(report(count).as_bytes(), Format::CaseworkReport).is_ok()); + } + for count in ["-1", "1.0", "1e0"] { + let error = decode(report(count).as_bytes(), Format::CaseworkReport).unwrap_err(); + assert_eq!(error.path, "/filesChecked"); + } + assert!(decode( + report("18446744073709551616").as_bytes(), + Format::CaseworkReport + ) + .is_err()); + let mut check: Value = serde_json::from_str(CASEWORK).unwrap(); + check["status"] = json!("domain-refusal"); + assert!(decode(&serde_json::to_vec(&check).unwrap(), Format::CaseworkReport).is_err()); + check["status"] = json!("complete"); + check["unexpected"] = json!(true); + assert!(decode(&serde_json::to_vec(&check).unwrap(), Format::CaseworkReport).is_err()); + check.as_object_mut().unwrap().remove("unexpected"); + check["command"] = json!("package"); + assert!(decode(&serde_json::to_vec(&check).unwrap(), Format::CaseworkReport).is_err()); +} + +#[test] +fn casework_native_u32_counts_use_the_selected_command_branch() { + let mut report = json!({ + "ok": true, "command": "generate-identity-facts", "status": "complete", + "apiVersion": "id.registrystack.org/formats/casework/report/v1alpha2", + "kind": "CaseworkReport", "version": "synthetic", "diagnostics": [], + "output": "synthetic.json", "product": "casework", + "claims": u32::MAX, "accessProfiles": 0, "assertionIssuers": 0, + }); + let decode = + |report: &Value| decode(&serde_json::to_vec(report).unwrap(), Format::CaseworkReport); + assert!(decode(&report).is_ok()); + report["claims"] = json!(u64::from(u32::MAX) + 1); + assert_eq!(decode(&report).unwrap_err().path, "/claims"); +} + +#[test] +fn breg_reads_only_completed_identity_facts_report_structure() { + let format = Format::BregIdentityFactsReport; + let mut report: Value = serde_json::from_str(BREG_IDENTITY_FACTS).unwrap(); + report["artifacts"][0]["path"] = json!("never-open-this/identity-facts.yaml"); + let check = |value: &Value| decode(&serde_json::to_vec(value).unwrap(), format); + assert!(check(&report).is_ok()); + + for (pointer, value) in [ + ("/command", json!("explain")), + ("/status", json!("domain-refusal")), + ("/artifacts/0/sha256", json!("synthetic-private-digest")), + ("/artifacts/0/byteLength", json!(0)), + ("/explanation/identityFacts/claims", json!(65)), + ] { + let mut refused = report.clone(); + *refused.pointer_mut(pointer).unwrap() = value; + let issue = check(&refused).unwrap_err(); + assert_eq!(issue.path, pointer); + assert!(!issue.message.contains("synthetic-private-digest")); + assert!(issue.source.unwrap().column.is_some()); + } + + let mut wrong_kind = report; + wrong_kind["kind"] = json!("PlatformIdentityFacts"); + let issue = check(&wrong_kind).unwrap_err(); + assert_eq!(issue.path, "/kind"); + assert!(issue.message.contains("BRegCtlReport")); + assert!(decode(BREG_IDENTITY_FACTS.as_bytes(), Format::CaseworkReport).is_err()); +} + +#[test] +fn breg_reports_native_integer_bounds_through_diagnostic_references() { + let format = Format::BregIdentityFactsReport; + for (pointer, value) in [ + ("/diagnostics/0/source/column", 0), + ("/diagnostics/0/source/line", MAXIMUM_DOCUMENT_BYTES + 2), + ] { + let mut report: Value = serde_json::from_str(BREG_IDENTITY_FACTS).unwrap(); + *report.pointer_mut(pointer).unwrap() = json!(value); + let issue = decode(&serde_json::to_vec(&report).unwrap(), format).unwrap_err(); + assert_eq!(issue.path, pointer); + assert_eq!(issue.code, "config.out-of-range"); + assert!(issue.message.contains("from 1 to 1048577")); + } +} + +#[test] +fn plain_reader_refuses_duplicate_trailing_and_oversized_json() { + assert!(parse(br#"{"a":{"b":1,"b":2}}"#).is_err()); + assert!(parse(br#"{} {}"#).is_err()); + assert!(parse(&vec![b' '; MAXIMUM_DOCUMENT_BYTES + 1]).is_err()); +} + +#[test] +fn integer_constraints_follow_refs_and_selected_union_arms() { + let schema = compile(json!({ + "$defs": {"bound": {"type": ["integer", "null"], "minimum": 0, "maximum": 65535}}, + "oneOf": [ + {"type": "object", "required": ["type", "count"], + "properties": {"type": {"const": "count"}, "count": {"$ref": "#/$defs/bound"}}}, + {"type": "object", "required": ["type", "count"], + "properties": {"type": {"const": "number"}, "count": {"type": "number"}}} + ] + })) + .unwrap(); + for (raw, valid) in [ + (br#"{"type":"count","count":65535}"#.as_slice(), true), + (br#"{"type":"count","count":null}"#, true), + (br#"{"type":"count","count":65536}"#, false), + (br#"{"type":"count","count":1e0}"#, false), + (br#"{"type":"number","count":1e0}"#, true), + ] { + assert_eq!(schema.validator.is_valid(&parse(raw).unwrap()), valid); + } + let signed = + compile(json!({"type": "integer", "minimum": i64::MIN, "maximum": i64::MAX})).unwrap(); + assert!(signed.validator.is_valid(&json!(i64::MIN))); + assert!(signed.validator.is_valid(&json!(i64::MAX))); + assert!(!signed.validator.is_valid(&json!(i64::MAX as u64 + 1))); + assert!(!signed + .validator + .is_valid(&parse(b"-9223372036854775809").unwrap())); + let unsigned = compile(json!({"type": "integer", "minimum":0, "maximum": u64::MAX})).unwrap(); + for n in [(1u64 << 53) - 1, (1u64 << 53) + 1, u64::MAX - 1, u64::MAX] { + assert!(unsigned.validator.is_valid(&json!(n))); + } +} + +#[test] +fn hosted_file_check_reports_structure_and_redacts_parser_errors() { + let file = tempfile::NamedTempFile::new().unwrap(); + let run = |bytes: &[u8]| { + std::fs::write(file.path(), bytes).unwrap(); + let mut out = Vec::new(); + let mut err = Vec::new(); + let status = crate::run( + crate::Args { + entry: crate::Entry::Check { + project: file.path().to_owned(), + deny_warnings: false, + json: true, + owner_report_format: Some(Format::CaseworkReport), + }, + }, + &mut out, + &mut err, + ); + assert!(err.is_empty()); + (status, String::from_utf8(out).unwrap()) + }; + let (status, output) = run(CASEWORK.as_bytes()); + assert_eq!(status, std::process::ExitCode::SUCCESS); + let report: Value = serde_json::from_str(&output).unwrap(); + assert_eq!(report["assessment"], "owner-report-structure"); + let (status, output) = + run(b"{\n\"synthetic-private-member\": 1, \"synthetic-private-member\": 2}"); + assert_eq!(status, std::process::ExitCode::from(1)); + assert!(!output.contains("synthetic-private-member")); + let report: Value = serde_json::from_str(&output).unwrap(); + assert_eq!(report["diagnostics"][0]["source"]["line"], 2); + assert_eq!( + report["diagnostics"][0]["code"], + "rstack.dev.owner-report-invalid" + ); +} + +#[test] +fn saved_report_retains_positions_and_numeric_bounds_without_echoing_input() { + let file = tempfile::NamedTempFile::new().unwrap(); + let source = CASEWORK + .replace("\"filesChecked\": 1", "\"filesChecked\": -918204") + .replace( + "\"networkAccess\": false", + "\"networkAccess\": \"synthetic-private-value\"", + ); + std::fs::write(file.path(), source).unwrap(); + let (report, exit) = check_file(file.path(), Format::CaseworkReport); + assert_eq!(exit, 1); + assert_eq!(report.error_count(), 2); + let diagnostics = report.diagnostics(); + assert_eq!(diagnostics[0].code, "config.out-of-range"); + assert_eq!(diagnostics[0].path, "/filesChecked"); + assert!(diagnostics[0].message.contains(&usize::MAX.to_string())); + let position = diagnostics[0].source.as_ref().unwrap(); + assert_eq!((position.line, position.column), (Some(9), Some(19))); + assert_eq!(diagnostics[1].path, "/networkAccess"); + assert_eq!(diagnostics[1].source.as_ref().unwrap().line, Some(10)); + let output = report.render_human(); + assert!(!output.contains("-918204")); + assert!(!output.contains("synthetic-private-value")); +} + +#[test] +fn saved_report_retains_unknown_key_locations_and_all_envelope_refusals() { + let version = CASEWORK + .lines() + .find(|line| line.starts_with(" \"version\": ")) + .expect("the saved report states its version") + .trim_end_matches(','); + let source = CASEWORK.replacen( + version, + &format!("{version},\n \"private-canary-one\": true,\n \"private-canary-two\": false"), + 1, + ); + let (report, exit) = check_bytes("synthetic.json", source.as_bytes(), Format::CaseworkReport); + assert_eq!(exit, 1); + assert_eq!(report.error_count(), 2); + for (diagnostic, line) in report.diagnostics().iter().zip([8, 9]) { + let position = diagnostic.source.as_ref().unwrap(); + assert_eq!((position.line, position.column), (Some(line), Some(3))); + assert_eq!(diagnostic.code, "config.unknown-key"); + } + assert!(!report.render_human().contains("private-canary")); + + let source = CASEWORK.replace("CaseworkReport", "private-kind").replace( + "\"id.registrystack.org/formats/casework/report/v1alpha2\"", + "[\"private-version\"]", + ); + let (report, exit) = check_bytes("synthetic.json", source.as_bytes(), Format::CaseworkReport); + assert_eq!(exit, 1); + assert_eq!(report.error_count(), 2); + assert_eq!(report.diagnostics()[0].path, "/apiVersion"); + assert_eq!(report.diagnostics()[1].path, "/kind"); + assert!(!report.render_human().contains("private-")); +} + +#[test] +fn near_limit_invalid_diagnostics_use_the_generic_fallback() { + let mut report: Value = serde_json::from_str(CASEWORK).unwrap(); + let cell = json!("x".repeat(64)); + let cell_bytes = serde_json::to_vec(&cell).unwrap().len() + 1; + let cap = MAXIMUM_DOCUMENT_BYTES; + let overhead = serde_json::to_vec(&report).unwrap().len(); + report["diagnostics"] = json!(vec![cell; (cap - overhead) / cell_bytes]); + let bytes = serde_json::to_vec(&report).unwrap(); + assert!((cap - cell_bytes..=cap).contains(&bytes.len())); + let error = decode(&bytes, Format::CaseworkReport).unwrap_err(); + assert_eq!(error.path, ""); + assert_eq!(error.message, "Owner report violates the selected schema"); +} + +#[test] +fn ordinary_diagnostics_retain_exact_field_locations() { + let mut report: Value = serde_json::from_str(CASEWORK).unwrap(); + report["policyBindings"][0]["digest"] = json!(false); + let error = validate(&report, Format::CaseworkReport, None) + .unwrap() + .remove(0); + assert_eq!(error.path, "/policyBindings/0/digest"); + assert_eq!( + error.message, + "Owner report violates the selected schema at this location" + ); +} + +#[test] +fn dynamic_map_members_are_redacted_even_when_they_match_schema_names() { + let document: Value = serde_json::from_str(super::CASEWORK).unwrap(); + let schema = compile(json!({ + "$defs": document["$defs"], + "properties": { + "condition": {"$ref": "#/$defs/RoutingCondition"}, + "stage": {"type": "string"} + } + })) + .unwrap(); + for key in ["stage", "synthetic-private-map-key"] { + let value = json!({"condition": {"fields": {(key): false}}}); + let error = schema.issues(&value, "", None).remove(0); + assert_eq!(error.path, "/condition/fields"); + assert!(!format!("{error:?}").contains(key)); + } +} diff --git a/crates/registry-rstack-dev/src/plan.rs b/crates/registry-rstack-dev/src/plan.rs index 2508dd2f53..405f3052e3 100644 --- a/crates/registry-rstack-dev/src/plan.rs +++ b/crates/registry-rstack-dev/src/plan.rs @@ -103,35 +103,42 @@ pub(crate) fn schema() -> schemars::Schema { audiences.insert("minProperties".to_owned(), 1.into()); audiences.insert( "description".to_owned(), - "Token audiences keyed by the product IDs declared in service.yaml.".into(), + "Token audiences keyed by project ID: the member name under projects, or the product kind for a single path.".into(), + ); + let mut products = + registry_platform_config::service_compiler::product_inventory_schema(&mut generator); + products.insert( + "description".to_owned(), + "The products to start, as in service.yaml. Leave it out when a sibling service.yaml declares products.".into(), ); let mut schema = generator.into_root_schema_for::>(); - // The composed reader projects audiences into products before decoding Plan. - schema + // The composed reader projects products and audiences into the native + // product list before decoding Plan. + let properties = schema .get_mut("properties") .and_then(Value::as_object_mut) - .expect("Plan has a properties mapping") - .insert("audiences".to_owned(), audiences.to_value()); + .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 + .get_mut("$defs") + .and_then(Value::as_object_mut) + .expect("Plan has definitions") + .remove("ProductPlan"); + let required = schema .get_mut("required") .and_then(Value::as_array_mut) - .expect("Plan has required properties") - .retain(|property| property != "products"); - schema.insert( - "oneOf".to_owned(), - serde_json::json!([ - {"required": ["products"]}, - {"required": ["audiences"]} - ]), - ); + .expect("Plan has required properties"); + required.retain(|property| property != "products"); + required.push("audiences".into()); schema.insert( "allOf".to_owned(), serde_json::json!([{ "if": {"required": ["preview"]}, "then": { - "required": ["audiences"], "properties": {"issuer": {"const": "run"}}, - "not": {"required": ["application"]} + "not": {"anyOf": [{"required": ["application"]}, {"required": ["products"]}]} } }]), ); @@ -360,6 +367,9 @@ pub(super) struct Plan { /// Explicit connections from a development BReg to external fixture services. #[serde(default, skip_serializing_if = "Option::is_none")] pub external_breg: Option, + /// One external task grant and its live status provider for a Scheduling fixture. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub external_scheduling: Option, /// The products to start, each with its project directory and token audience. List each product at most once. pub products: Vec, /// The audience that products a person calls from a page will share: an absolute URI of at most 256 characters, with no fragment or user information. Only BReg can be a member, by setting its `audience` to the same value, whether or not it checks task grants. Casework keeps its own audience, Messaging takes no person token, and Evidence cannot join yet. Declaring `personAudience` alone changes nothing at run time. @@ -392,6 +402,13 @@ pub(super) struct Plan { pub preview: Option, } +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ExternalScheduling { + pub task_grant: super::external_breg::TaskGrant, +} + /// A generic Node application and its configuration command. All artifact paths are relative to the supplied built root. #[derive(Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -1066,10 +1083,8 @@ fn read_plan(root: &Path) -> Result<(AuthoredPlan, AuthoredDigests)> { super::preview::verify_native_source(source, expected)?; } } - let (value, service) = resolved.map_err(|error| match error.downcast::() { - Ok(refusal) => source_refusal_report(&document, sources.as_ref(), &refusal).into(), - Err(error) => error, - })?; + let (value, service) = + resolved.map_err(|error| authored_error(&document, sources.as_ref(), error))?; Ok(( AuthoredPlan { value, @@ -1100,34 +1115,57 @@ fn decode_authored_plan( remedy: WRITE_THE_VALUE, }) .read(&bytes, &Expect::one(&FORMAT))?; - if document.span_of("/audiences").is_none() { - let value = document.decode()?; - return Ok(( - AuthoredPlan { - value, - document, - sources: None, - }, - digest, - )); - } let projection = registry_platform_config::service_compiler::development_plan(root, &document)?; let bytes = serde_json::to_vec(&projection.native)?; let decoded = Reader::new(&name) .decode::>(&bytes, &Expect::one(&FORMAT)) .map_err(|mut report| { + // The reader positioned these diagnostics in the projected JSON. + // Keep its choice of key, value or whole file, and place each one + // and its related notes in the authored file. + let projected = Reader::new(&name).read(&bytes, &Expect::one(&FORMAT)).ok(); for diagnostic in report.diagnostics_mut() { + let original = diagnostic + .source + .as_ref() + .map(|source| (source.line, source.column)); + let at_key = projected + .as_ref() + .and_then(|json| json.key_span_of(&diagnostic.path)) + .is_some_and(|span| { + original == Some((Some(span.start.line), Some(span.start.column))) + }); let (source, path) = projection.sources.locate(&document, &diagnostic.path); - let authored = source.diagnostic_at_value( + let place = if at_key { + Document::diagnostic_at_key + } else { + Document::diagnostic_at_value + }; + let mut authored = place( + source, diagnostic.severity, &diagnostic.code, path, &diagnostic.message, &diagnostic.suggested_action, ); + if original.is_some_and(|(line, _)| line.is_none()) { + if let Some(authored) = authored.source.as_mut() { + authored.line = None; + authored.column = None; + } + } diagnostic.path = authored.path; diagnostic.source = authored.source; diagnostic.artifact = authored.artifact; + for related in &mut diagnostic.related { + let (source, path) = projection.sources.locate(&document, &related.path); + let position = source.span_of(path).map(|span| span.start); + related.file = source.file().to_owned(); + related.line = position.map(|position| position.line); + related.column = position.map(|position| position.column); + related.path = path.to_owned(); + } } report })?; @@ -1145,6 +1183,35 @@ fn refusal_report(decoded: &AuthoredPlan, refusal: &SemanticRefu source_refusal_report(&decoded.document, decoded.sources.as_ref(), refusal) } +/// A plan refusal, or an unavailable product helper, at the authored location +/// of its native plan field. Other errors pass through unchanged. +fn authored_error( + document: &Document, + sources: Option<&DevelopmentSources>, + error: anyhow::Error, +) -> anyhow::Error { + let error = match error.downcast::() { + Ok(refusal) => return source_refusal_report(document, sources, &refusal).into(), + Err(error) => error, + }; + match error.downcast::() { + Ok(unavailable) => { + let (source, field) = sources.map_or((document, unavailable.field()), |sources| { + sources.locate(document, unavailable.field()) + }); + let position = source.span_of(field).map(|span| span.start); + let located = registry_platform_yaml::Source { + file: source.file().to_owned(), + line: position.map(|position| position.line), + column: position.map(|position| position.column), + }; + let field = field.to_owned(); + unavailable.at(&field, located).into() + } + Err(error) => error, + } +} + fn source_refusal_report( document: &Document, sources: Option<&DevelopmentSources>, @@ -1226,10 +1293,11 @@ pub(crate) fn check(root: &Path) -> Result { let inspection = match inspection { Ok(inspection) => inspection, Err(error) => { - return match error.downcast::() { - Ok(refusal) => Err(refusal_report(&decoded, &refusal).into()), - Err(error) => Err(error), - } + return Err(authored_error( + &decoded.document, + decoded.sources.as_ref(), + error, + )) } }; validate_application_authority(&decoded.value, &inspection) @@ -1259,7 +1327,15 @@ fn preview_plan( let Some(preview) = &decoded.value.preview else { return Ok(None); }; - let build = preview.build_plan(root, &decoded.value, decoded.sources.is_some()); + if decoded.document.span_of("/products").is_some() { + let refusal = SemanticRefusal::new( + "/products", + "A browser preview takes its products from the sibling service.yaml.", + "Declare the one BReg project under products in service.yaml and keep only audiences in dev.yaml.", + ); + return Err(refusal_report(decoded, &refusal).into()); + } + let build = preview.build_plan(root, &decoded.value); match build { Ok(build) => { anyhow::ensure!( @@ -1281,9 +1357,12 @@ fn preview_plan( impl Plan { pub(super) fn paired_run_binding(&self) -> bool { + let has = |product| self.products.iter().any(|p| p.product == product); self.bindings.binds_run_issuer() - && self.products.iter().any(|p| p.product == Product::Breg) - && self.products.iter().any(|p| p.product == Product::Casework) + && has(Product::Casework) + && (has(Product::Breg) + || (self.bindings.coordinator_review_producer.is_some() + && has(Product::Coordinator))) } pub(super) fn runs_evidence(&self) -> bool { @@ -1334,12 +1413,16 @@ impl Plan { "Set issuer to the exact numeric loopback HTTP origin for an external key endpoint, or use `run` or a fixed HTTPS issuer for runner-managed keys.", )?; if let Some(bindings) = &self.external_breg { + let hook_only = !bindings.hooks.is_empty() + && bindings.review_authority.is_none() + && bindings.task_grant.is_none() + && bindings.schema_test_headers.is_empty(); require( - self.jwks_uri().is_some() + (self.jwks_uri().is_some() || hook_only) && self.products.iter().any(|p| p.product == Product::Breg), "/externalBreg", - "External BReg connections require BReg and an external issuer.", - "Add BReg and externalJwksUri to this plan, or remove externalBreg.", + "External BReg connections require BReg. A binding other than a hook also requires an external issuer.", + "Add BReg to the plan, and add externalJwksUri for any bindings other than hooks.", )?; bindings.validate(root)?; } @@ -1351,6 +1434,32 @@ impl Plan { "Set issuer to the exact external issuer and externalJwksUri to its key endpoint.", )?; } + if let Some(binding) = &self.external_scheduling { + let scheduling = self + .products + .iter() + .find(|entry| entry.product == Product::Scheduling); + require( + self.jwks_uri().is_some() && scheduling.is_some(), + "/externalScheduling", + "An external Scheduling task grant needs Scheduling and an external issuer.", + "Select Scheduling and set issuer and externalJwksUri to the fixture issuer and its key endpoint.", + )?; + binding.task_grant.validate_for_scheduling( + root, + self, + &scheduling.expect("validated Scheduling product").audience, + )?; + if let Some(breg_grant) = self + .external_breg + .as_ref() + .and_then(|breg| breg.task_grant.as_ref()) + { + binding + .task_grant + .require_distinct_status(breg_grant, root)?; + } + } require( (self.issuer != "run" || self.application.is_some() @@ -1359,7 +1468,7 @@ impl Plan { || self.runs_evidence()) && ((self.application.is_none() && !self.bindings.binds_run_issuer()) || self.issuer == "run"), "/issuer", - "The run issuer requires a preview, an application, an explicitly bound BReg and Casework pair, or Evidence. Applications and run issuer bindings require issuer run.", + "The run issuer requires a preview, an application, an explicitly bound BReg or Coordinator review producer paired with Casework, or Evidence. Applications and run issuer bindings require issuer run.", "Use issuer `run` with a preview, an application, the exact paired runIssuerBinding, or Evidence. Other plans use a configured issuer.", )?; require( @@ -1701,6 +1810,9 @@ impl Plan { ), )?; } + if let Some(binding) = &self.external_scheduling { + binding.task_grant.validate_scheduling_caller(self)?; + } self.bindings.validate(self)?; Ok(()) } @@ -1742,6 +1854,17 @@ impl Journey { "The step must name a test person with a grant for its product.", "Set as to a test person that has a grant for this step's product.", )?; + require( + plan.bindings + .coordinator_breg_client + .as_ref() + .is_none_or(|binding| { + step.person.as_deref() != Some(binding.identity.as_str()) + }), + &format!("{field}/as"), + "A journey step cannot act as the Coordinator's dedicated BReg identity.", + "Set as to another test person.", + )?; require( valid_path(&step.path) && (step.path != ADAPTER_CONTRACT_PATH || step.product == Product::Adapter), &format!("{field}/path"), @@ -2023,7 +2146,7 @@ impl JourneyFile { } } -fn issuer_url(value: &str) -> bool { +pub(super) fn issuer_url(value: &str) -> bool { value.len() <= 512 && ParsedUrl::parse(value).is_ok_and(|url| { url.scheme() == "https" @@ -2213,6 +2336,7 @@ mod tests { #[test] fn authored_role_and_fixture_errors_point_to_the_offending_item_or_key() { let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("registry.yaml"), "fixture").unwrap(); for (person, code, path) in [ ( "roles: [reader, reader]", @@ -2228,7 +2352,7 @@ mod tests { fs::write( root.path().join("dev.yaml"), format!( - "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: run\nproducts: []\npeople: {{reader: {{subject: reader, client: reader, {person}}}}}\njourneyFile: dev-journeys.yaml\n" + "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: run\nproducts: {{breg: {{projects: {{breg: {{path: .}}}}}}}}\naudiences: {{breg: urn:test:breg}}\npeople: {{reader: {{subject: reader, client: reader, {person}}}}}\njourneyFile: dev-journeys.yaml\n" ), ) .unwrap(); @@ -2251,11 +2375,13 @@ mod tests { fs::write(project.path().join("registry.yaml"), "fixture").unwrap(); fs::write(project.path().join("dev-journeys.yaml"), "fixture").unwrap(); fs::write(project.path().join("dev.yaml"), format!( - "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: https://issuer.example.test\nproducts: [{{product: breg, project: ., audience: urn:test:breg}}]\njourneyFile: dev-journeys.yaml\npeople: {{reader: {{subject: reader, client: reader, roles: [reader]}}}}\n" + "apiVersion: {API_VERSION}\nkind: {KIND}\nissuer: https://issuer.example.test\nproducts: {{breg: {{projects: {{breg: {{path: .}}}}}}}}\naudiences: {{breg: urn:test:breg}}\njourneyFile: dev-journeys.yaml\npeople: {{reader: {{subject: reader, client: reader, roles: [reader]}}}}\n" )).unwrap(); + // The inventory reader opens service.yaml first and refuses the link. let error = load(project.path()).err().unwrap().to_string(); + assert!(error.contains("rstack.service.read"), "{error}"); assert!( - error.contains("resolves outside the development project"), + !error.contains(&outside.path().display().to_string()), "{error}" ); } @@ -2279,6 +2405,22 @@ mod tests { (root, plan) } + #[test] + fn a_journey_cannot_act_as_the_coordinator_breg_identity() { + let (root, mut plan) = plan(json!({"id": "read", "product": "breg", + "as": "operator", "method": "GET", "path": "/v1/records", "expect": {"status": 200}})); + plan.bindings = serde_json::from_value(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "operator" + }})) + .unwrap(); + let error = journey_file(root.path(), &plan) + .validate(&plan) + .unwrap_err() + .to_string(); + assert!(error.contains("/steps/0/as"), "{error}"); + assert!(error.contains("Coordinator"), "{error}"); + } + #[test] fn an_external_issuer_accepts_loopback_keys_and_requires_an_empty_journey_pack() { let (root, mut plan) = plan(json!({"id": "read", "product": "breg", @@ -2325,6 +2467,189 @@ mod tests { } } + #[test] + fn managed_scheduling_requires_the_exact_external_grant_binding() { + let (root, mut plan) = plan(json!({"id": "read", "product": "breg", + "as": "operator", "method": "GET", "path": "/v1/records", "expect": {"status": 200}})); + fs::write(root.path().join("scheduling.yaml"), "{}").unwrap(); + fs::create_dir(root.path().join("fixture")).unwrap(); + crate::write_private( + &root.path().join("fixture/status-key"), + b"synthetic fixture credential", + ) + .unwrap(); + plan.products = serde_json::from_value(json!([{ + "product": "scheduling", "project": ".", "audience": "urn:example:journey:scheduling" + }])) + .unwrap(); + plan.people = serde_json::from_value(json!({"booker": { + "subject": "booker", "client": "task-agent", + "grants": {"scheduling": {"profile": "booker", "scopes": ["scheduling:write"]}} + }})) + .unwrap(); + plan.issuer = "http://127.0.0.1:41000".to_owned(); + plan.external_jwks_uri = Some("http://127.0.0.1:41000/oauth2/jwks".to_owned()); + let binding = json!({"taskGrant": { + "sourceIssuer": "https://casework.journey.example", + "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "statusClient": "scheduling-status", + "statusKeyRef": "secret:file/status-key", + "statusResource": "urn:example:journey:casework" + }}); + plan.external_scheduling = Some(serde_json::from_value(binding.clone()).unwrap()); + plan.validate(root.path()) + .expect("fixed external Scheduling grant"); + let mut runtime = json!({"authentication": {"oidc": {"issuers": {"main": { + "allowedClients": ["task-agent"], "issuer": plan.issuer + }}}}}); + plan.external_scheduling + .as_ref() + .unwrap() + .task_grant + .configure( + |_| Ok("secret:file/run-task-status-key".to_owned()), + &root.path().canonicalize().unwrap(), + &plan.issuer, + &mut runtime, + ) + .unwrap(); + assert_eq!( + runtime["authentication"]["oidc"]["issuers"]["main"]["assertionIssuers"], + json!({"task-agent": ["https://casework.journey.example"]}) + ); + assert_eq!( + runtime["taskGrantStatus"], + json!([{ + "sourceIssuer": "https://casework.journey.example", + "baseUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "clientAssertionAudience": "http://127.0.0.1:41000", + "clientId": "scheduling-status", + "privateKeyRef": "secret:file/run-task-status-key", + "statusResource": "urn:example:journey:casework" + }]) + ); + + for (field, value) in [ + ("sourceIssuer", "http://127.0.0.1:41001"), + ("assertionClient", "another-agent"), + ("statusUrl", "http://127.0.0.1:41001/arbitrary"), + ("tokenEndpoint", "http://127.0.0.1:41002/oauth2/token"), + ("statusClient", "task-agent"), + ("statusKeyRef", "secret:file/missing"), + ("statusResource", "urn:example:journey:scheduling"), + ] { + let mut mutated = binding.clone(); + mutated["taskGrant"][field] = json!(value); + plan.external_scheduling = Some(serde_json::from_value(mutated).unwrap()); + assert_eq!( + plan.validate(root.path()).unwrap_err().field, + format!("/externalScheduling/taskGrant/{field}") + ); + } + plan.external_scheduling = Some(serde_json::from_value(binding).unwrap()); + plan.external_jwks_uri = Some("http://127.0.0.1:41002/oauth2/jwks".to_owned()); + assert_eq!( + plan.validate(root.path()).unwrap_err().field, + "/externalJwksUri" + ); + } + + #[test] + fn plan_refuses_cross_product_task_status_credential_reuse() { + let (root, mut plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", "method": "GET", + "path": "/v1/records", "expect": {"status": 200} + })); + fs::create_dir(root.path().join("schedule")).unwrap(); + fs::write(root.path().join("schedule/scheduling.yaml"), "{}").unwrap(); + fs::create_dir(root.path().join("fixture")).unwrap(); + for file in ["breg-status", "scheduling-status"] { + let key = registry_platform_crypto::generate_private_jwk( + registry_platform_crypto::GeneratedKeyAlgorithm::Es256, + ) + .unwrap(); + let bytes = crate::bindings::encode_private_jwk(&key).unwrap(); + crate::write_private(&root.path().join("fixture").join(file), &bytes).unwrap(); + } + plan.products.push( + serde_json::from_value(json!({ + "product": "scheduling", "project": "schedule", + "audience": "urn:example:journey:scheduling" + })) + .unwrap(), + ); + plan.people.insert( + "booker".to_owned(), + serde_json::from_value(json!({ + "subject": "booker", "client": "task-agent", + "grants": {"scheduling": {"profile": "booker", "scopes": ["scheduling:write"]}} + })) + .unwrap(), + ); + plan.issuer = "http://127.0.0.1:41000".to_owned(); + plan.external_jwks_uri = Some("http://127.0.0.1:41000/oauth2/jwks".to_owned()); + let task_grant = |issuer, client, key| { + json!({"taskGrant": { + "sourceIssuer": issuer, "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:41001", + "tokenEndpoint": "http://127.0.0.1:41000/oauth2/token", + "statusClient": client, "statusKeyRef": format!("secret:file/{key}"), + "statusResource": "urn:example:journey:casework" + }}) + }; + plan.external_breg = Some( + serde_json::from_value(task_grant( + "http://127.0.0.1:41001", + "breg-status", + "breg-status", + )) + .unwrap(), + ); + for (client, key, refused_field) in [ + ("scheduling-status", "scheduling-status", None), + ("breg-status", "scheduling-status", Some("statusClient")), + ("scheduling-status", "breg-status", Some("statusKeyRef")), + ] { + plan.external_scheduling = Some( + serde_json::from_value(task_grant("https://casework.journey.example", client, key)) + .unwrap(), + ); + let validation = plan.validate(root.path()); + if let Some(field) = refused_field { + assert_eq!( + validation.unwrap_err().field, + format!("/externalScheduling/taskGrant/{field}") + ); + } else { + validation.expect("separate task-status identities"); + } + } + } + + #[test] + fn a_fixed_external_hook_may_use_the_managed_development_issuer() { + let (root, mut plan) = plan(json!({"id": "read", "product": "breg", + "as": "operator", "method": "GET", "path": "/v1/records", "expect": {"status": 200}})); + fs::create_dir(root.path().join("fixture")).unwrap(); + crate::write_private(&root.path().join("fixture/key"), b"synthetic fixture").unwrap(); + let mut external = json!({"hooks": {"events": { + "origin": "http://127.0.0.1:41000", + "path": "/events", + "keyRef": "secret:file/key", + }}}); + plan.external_breg = Some(serde_json::from_value(external.clone()).unwrap()); + plan.validate(root.path()).expect("hook-only attachment"); + + external["schemaTestHeaders"] = json!({"operator": "secret:file/key"}); + plan.external_breg = Some(serde_json::from_value(external).unwrap()); + let error = plan.validate(root.path()).unwrap_err(); + assert_eq!(error.field, "/externalBreg"); + assert!(error.reason.contains("external issuer")); + } + #[test] fn external_breg_peers_require_numeric_loopback_http() { for pointer in [ @@ -2741,7 +3066,8 @@ journeys: [] .unwrap(); let valid = json!({ "issuer": "https://issuer.example.invalid", - "products": [{"product": "breg", "project": ".", "audience": "registry"}], + "products": {"breg": {"projects": {"breg": {"path": "."}}}}, + "audiences": {"breg": "registry"}, "people": {"operator": { "subject": "operator", "client": "operator-client", "roles": ["operator"] @@ -3710,6 +4036,14 @@ mod preview_tests { "/v1/records/licences/{recordId}", true )); + for id in ["{recordId}", "{record_id}", "{taskId}", "{runId}"] { + let path = format!("/v1/records/applications/{id}/revisions/{{revision}}"); + assert!(super::super::preview::valid_path(&path, true), "{path}"); + } + assert!(super::super::preview::valid_path( + "/v1/runs/{runId}/revisions/{revision}", + true + )); assert!(super::super::preview::valid_path("/check.html", false)); for path in [ "//elsewhere", @@ -3719,6 +4053,10 @@ mod preview_tests { "/v1/records?accessProfile=admin", "/v1/records/{anything}", "/v1/records/{recordId}/{recordId}", + "/v1/records/{recordId}/{record_id}", + "/v1/review-tasks/{record_id}/{taskId}", + "/v1/runs/{runId}/{revision}/{revision}", + "/v1/records/{recordId}/revisions/{revision}/{revision}", "/v1/records/#fragment", ] { assert!(!super::super::preview::valid_path(path, true), "{path}"); diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index 7026d7895e..ef563ec312 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -23,17 +23,26 @@ pub(super) const HEALTH: &str = "/_rstack/ready"; #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct Preview { - /// Synthetic development identity whose checked BReg grant is used on the server. - pub actor: LocalId, + /// Synthetic development identity whose checked BReg grant is used on the server. Use with `breg`, or use `actors` instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor: Option, /// Initial page on the loopback preview origin. pub page: String, - /// BReg paths exposed to the page, grouped by method. - pub breg: Routes, + /// BReg paths exposed to the page of the single `actor`, grouped by method. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub breg: Option, /// Declared functions to expose on the loopback preview origin. pub functions: UniqueList, + /// One to eight synthetic identities, each served on its own loopback gateway origin over the same page, with the product paths it may reach. Use instead of `actor` and `breg`. Every actor needs a BReg grant, and a grant for each other product it reaches. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "super::plan::keyed_schema::") + )] + pub actors: Option>, } -#[derive(Deserialize, Serialize)] +#[derive(Default, Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct Routes { @@ -43,6 +52,46 @@ pub(super) struct Routes { post: UniqueList, } +impl Routes { + fn is_empty(&self) -> bool { + self.get.is_empty() && self.post.is_empty() + } +} + +/// The product paths one preview actor may reach, grouped by product and +/// method. +#[derive(Default, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields)] +pub(super) struct ActorRoutes { + #[serde(default, skip_serializing_if = "Routes::is_empty")] + breg: Routes, + #[serde(default, skip_serializing_if = "Routes::is_empty")] + casework: Routes, + #[serde(default, skip_serializing_if = "Routes::is_empty")] + coordinator: Routes, +} + +impl ActorRoutes { + fn by_product(&self) -> [(Product, &Routes); 3] { + [ + (Product::Breg, &self.breg), + (Product::Casework, &self.casework), + (Product::Coordinator, &self.coordinator), + ] + } +} + +/// A product the page reaches only through the gateway, without a +/// generated client. +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct RouteProduct { + pub id: LocalId, + pub kind: String, + pub audience: String, +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub(super) struct BuildPlan { @@ -52,6 +101,8 @@ pub(super) struct BuildPlan { functions: BTreeMap, pub product: PreviewProduct, pub declaration_digest: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub route_products: Vec, } #[derive(Deserialize, Serialize)] @@ -64,24 +115,49 @@ pub(super) struct PreviewProduct { } impl Preview { - pub(super) fn build_plan( - &self, - root: &Path, - native: &plan::Plan, - composed: bool, - ) -> Result { + /// The synthetic identities the preview serves. + pub(super) fn actor_names(&self) -> Vec<&str> { + self.actor + .iter() + .chain(self.actors.iter().flat_map(BTreeMap::keys)) + .map(LocalId::as_str) + .collect() + } + + pub(super) fn build_plan(&self, root: &Path, native: &plan::Plan) -> Result { let refusal = || { plan::refuse( "/preview", - "A browser preview requires one named BReg, a UI, declared functions, issuer run, and a composed plan.", - "Set audiences by product ID and remove any explicit application or external issuer from this preview.", + "A browser preview requires one named BReg in service.yaml, a UI, declared functions, and issuer run.", + "Declare the one BReg project under products in service.yaml, set its audience in dev.yaml, and remove any explicit application or external issuer from this preview.", ) }; - if !composed - || native.application.is_some() + let multi = self.actors.is_some(); + if (self.actor.is_some() || self.breg.is_some()) == multi + || self.actor.is_some() != self.breg.is_some() + { + return plan::refuse( + "/preview", + "A browser preview names either one actor with BReg routes or an actors map.", + "Use actor and breg for one identity, or actors for several.", + ) + .map_err(Into::into); + } + // Casework and the Coordinator are reachable only through actors. + let route_kinds = + |product: Product| multi && matches!(product, Product::Casework | Product::Coordinator); + if native.application.is_some() || native.issuer != "run" - || native.products.len() != 1 - || native.products[0].product != Product::Breg + || native + .products + .iter() + .filter(|entry| entry.product == Product::Breg) + .count() + != 1 + || native + .products + .iter() + .any(|entry| entry.product != Product::Breg && !route_kinds(entry.product)) { return refusal().map_err(Into::into); } @@ -115,10 +191,27 @@ impl Preview { let Some(ui) = service.ui else { return refusal().map_err(Into::into); }; + let kind = |product: &service::Product| match product.product { + "breg" => Some(Product::Breg), + "casework" => Some(Product::Casework), + "coordinator" => Some(Product::Coordinator), + _ => None, + }; if service.file != service_file || service.functions.is_empty() - || service.products.len() != 1 - || service.products[0].product != "breg" + || service + .products + .iter() + .filter(|product| product.product == "breg") + .count() + != 1 + || service.products.iter().any(|product| { + kind(product).is_none_or(|product| { + product != Product::Breg + && (!route_kinds(product) + || !native.products.iter().any(|entry| entry.product == product)) + }) + }) { return refusal().map_err(Into::into); } @@ -152,11 +245,24 @@ impl Preview { ) .map_err(Into::into); } - let Some(grant) = native - .people - .get(self.actor.as_str()) - .and_then(|actor| actor.grants.get(&Product::Breg)) - else { + let profile = match (&self.actor, &self.actors) { + (Some(actor), None) => native + .people + .get(actor.as_str()) + .and_then(|actor| actor.grants.get(&Product::Breg)) + .map(|grant| grant.profile.clone()), + (None, Some(actors)) => { + check_actors(native, actors)?; + actors + .keys() + .next() + .and_then(|actor| native.people.get(actor.as_str())) + .and_then(|actor| actor.grants.get(&Product::Breg)) + .map(|grant| grant.profile.clone()) + } + _ => None, + }; + let Some(profile) = profile else { return plan::refuse( "/preview/actor", "The preview actor needs a BReg grant.", @@ -172,18 +278,8 @@ impl Preview { ) .map_err(Into::into); } - for (method, routes) in [("get", &self.breg.get), ("post", &self.breg.post)] { - if routes.len() > 64 - || routes - .iter() - .any(|route| !route.starts_with("/v1/") || !valid_path(route, true)) - { - return plan::refuse( - &format!("/preview/breg/{method}"), - "Preview routes need bounded literal BReg paths.", - "Use /v1/ paths with at most one {recordId} path segment, without query strings.", - ).map_err(Into::into); - } + if let Some(routes) = &self.breg { + check_routes(routes, "/preview/breg")?; } let selected = &self.functions; if selected.is_empty() @@ -199,10 +295,36 @@ impl Preview { ) .map_err(Into::into); } + let mut route_products: Vec = service + .products + .iter() + .filter_map(|product| { + let kind = kind(product).filter(|kind| *kind != Product::Breg)?; + Some(RouteProduct { + id: product.id.clone(), + kind: kind.name().to_owned(), + audience: native.product(kind).audience.clone(), + }) + }) + .collect(); + route_products.sort_by(|a, b| a.kind.cmp(&b.kind)); + // Each actor holds one credential per product kind, so a second + // project of a routed kind would have no credential to reach it. + if route_products + .windows(2) + .any(|pair| pair[0].kind == pair[1].kind) + { + return plan::refuse( + "/preview/actors", + "An actors preview reaches one project of each routed product.", + "Keep one Casework project and one Coordinator project in service.yaml.", + ) + .map_err(Into::into); + } let product = service .products .into_iter() - .next() + .find(|product| product.product == "breg") .context("missing preview product")?; ensure!( product.project @@ -225,16 +347,86 @@ impl Preview { member: product.member.context("missing preview client member")?, project: product.project, audience: native.product(Product::Breg).audience.clone(), - profile: grant.profile.clone(), + profile, }, declaration_digest: Sha256::digest(&declaration) .iter() .map(|byte| format!("{byte:02x}")) .collect(), + route_products, }) } } +/// Bounded literal /v1/ paths with at most one product ID placeholder. +fn check_routes(routes: &Routes, field: &str) -> plan::SemanticResult<()> { + for (method, routes) in [("get", &routes.get), ("post", &routes.post)] { + if routes.len() > 64 + || routes + .iter() + .any(|route| !route.starts_with("/v1/") || !valid_path(route, true)) + { + return plan::refuse( + &format!("{field}/{method}"), + "Preview routes need bounded literal product paths.", + "Use /v1/ paths with at most one {recordId}, {record_id}, {taskId} or {runId} segment and at most one {revision} segment, without query strings.", + ); + } + } + Ok(()) +} + +/// Each actor is a declared synthetic identity with a BReg grant, and a grant +/// for every other product it reaches through bounded literal paths. +fn check_actors( + native: &plan::Plan, + actors: &BTreeMap, +) -> plan::SemanticResult<()> { + if actors.is_empty() || actors.len() > 8 { + return plan::refuse( + "/preview/actors", + "A preview has one to eight actors.", + "Declare between one and eight actors.", + ); + } + for (name, routes) in actors { + let field = format!("/preview/actors/{}", name.as_str()); + let Some(person) = native.people.get(name.as_str()) else { + return plan::refuse( + &field, + "The preview actor is not a declared synthetic identity.", + "Name a person declared in people.", + ); + }; + if !person.grants.contains_key(&Product::Breg) { + return plan::refuse( + &field, + "Each preview actor needs a BReg grant.", + "Give the person a BReg role.", + ); + } + for (product, routes) in routes.by_product() { + let field = format!("{field}/{}", product.name()); + if !routes.is_empty() && !person.grants.contains_key(&product) { + return plan::refuse( + &field, + "The preview actor has no grant for this product.", + "Give the person a role for this product, or remove its paths.", + ); + } + check_routes(routes, &field)?; + } + } + Ok(()) +} + +/// The authorization files a preview run writes: one for the single actor's +/// BReg grant, or one per actor and product it reaches. +pub(super) struct PreviewAuthorization { + pub single: Option, + pub actors: BTreeMap>, +} + fn valid_page(path: &str) -> bool { if path == "/" { return true; @@ -253,23 +445,28 @@ pub(super) fn valid_path(path: &str, parameter: bool) -> bool { let Some(rest) = path.strip_prefix('/') else { return false; }; - let mut segments = rest.split('/'); + let placeholder = + |part: &str| matches!(part, "{recordId}" | "{record_id}" | "{taskId}" | "{runId}"); + let mut identifier = false; + let mut revision = false; path.len() <= 256 - && segments - .clone() - .filter(|segment| *segment == "{recordId}") - .count() - <= 1 - && segments.all(|part| { - (parameter && part == "{recordId}") - || (part.len() <= 128 - && part - .as_bytes() - .first() - .is_some_and(u8::is_ascii_alphanumeric) - && part.bytes().all(|byte| { - byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.') - })) + && rest.split('/').all(|part| { + if parameter { + if placeholder(part) { + return !std::mem::replace(&mut identifier, true); + } + if part == "{revision}" { + return !std::mem::replace(&mut revision, true); + } + } + part.len() <= 128 + && part + .as_bytes() + .first() + .is_some_and(u8::is_ascii_alphanumeric) + && part + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) }) } @@ -278,21 +475,45 @@ pub(super) fn authorization( input: &RunInput, signer: &Issuer, run_expires: u64, -) -> Result { +) -> Result { let preview = input.plan.preview.as_ref().context("missing preview")?; - let person = input - .plan - .people - .get(preview.actor.as_str()) - .context("missing preview actor")?; let expires = issuer::token_expiry(run_expires, clock()?); - let bearer = signer.token(input, person, Product::Breg, expires)?; - let path = root.join(AUTHORIZATION_FILE); - write_private( - &path, - Zeroizing::new(format!("Authorization: Bearer {}\n", &*bearer)).as_bytes(), - )?; - Ok(path) + let write = |path: PathBuf, person, product| -> Result { + let bearer = signer.token(input, person, product, expires)?; + write_private( + &path, + Zeroizing::new(format!("Authorization: Bearer {}\n", &*bearer)).as_bytes(), + )?; + Ok(path) + }; + let mut written = PreviewAuthorization { + single: None, + actors: BTreeMap::new(), + }; + if let Some(actor) = &preview.actor { + let person = input + .plan + .people + .get(actor.as_str()) + .context("missing preview actor")?; + written.single = Some(write(root.join(AUTHORIZATION_FILE), person, Product::Breg)?); + } + for (name, routes) in preview.actors.iter().flatten() { + let person = input + .plan + .people + .get(name.as_str()) + .context("missing preview actor")?; + let mut files = BTreeMap::new(); + for (product, routes) in routes.by_product() { + if product == Product::Breg || !routes.is_empty() { + let file = format!("{AUTHORIZATION_FILE}-{}-{}", name.as_str(), product.name()); + files.insert(product, write(root.join(file), person, product)?); + } + } + written.actors.insert(name.as_str().to_owned(), files); + } + Ok(written) } pub(super) fn helper(root: &Path) -> Result { @@ -467,3 +688,396 @@ mod snapshot_tests { ); } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + const SERVICE: &str = "\ +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +products: + breg: + projects: + permits: {path: project} + casework: {path: casework} + coordinator: + projects: + permit-flow: {path: coordinator} +ui: {project: web, output: dist} +functions: [assess-permit] +"; + + /// A service with BReg, Casework and the Coordinator, a UI and one + /// function, with stub native manifests. + fn project(root: &Path) { + for (directory, file) in [ + ("project", "registry.yaml"), + ("casework", "casework.yaml"), + ("coordinator", "workflow.yaml"), + ("web/src", "page.ts"), + ("functions/assess-permit", "index.ts"), + ] { + fs::create_dir_all(root.join(directory)).unwrap(); + fs::write(root.join(directory).join(file), "{}\n").unwrap(); + } + fs::create_dir_all(root.join("web/public")).unwrap(); + fs::write(root.join("service.yaml"), SERVICE).unwrap(); + } + + fn grant(profile: &str) -> Value { + json!({"profile": profile, "scopes": ["read"]}) + } + + /// An applicant and an officer, each on its own origin. + fn native(preview: Value) -> plan::Plan { + serde_json::from_value(json!({ + "issuer": "run", + "products": [ + {"product": "breg", "project": "project", "audience": "urn:permits"}, + {"product": "casework", "project": "casework", "audience": "urn:review"}, + {"product": "coordinator", "project": "coordinator", "audience": "urn:flow"} + ], + "people": { + "applicant": {"subject": "applicant", "client": "applicant-client", "grants": { + "breg": grant("permit-applicant"), "casework": grant("permit-requester"), + "coordinator": grant("permit-starter") + }}, + "officer": {"subject": "officer", "client": "officer-client", "grants": { + "breg": grant("permit-reader"), "casework": grant("permit-officer") + }} + }, + "journeyFile": "dev-journeys.yaml", + "preview": preview + })) + .unwrap() + } + + fn actors() -> Value { + json!({ + "page": "/", + "functions": ["assess-permit"], + "actors": { + "applicant": { + "breg": {"post": ["/v1/actions/submit-application"]}, + "casework": {"post": ["/v1/review-tasks/{taskId}/decisions"]}, + "coordinator": {"get": ["/v1/workflows/permit-flow", "/v1/runs/{runId}"], "post": ["/v1/runs"]} + }, + "officer": { + "breg": {"get": ["/v1/records/permits/{recordId}"]}, + "casework": {"get": ["/v1/review-tasks"], "post": ["/v1/review-tasks/{taskId}/claim", "/v1/review-tasks/{taskId}/decisions"]} + } + } + }) + } + + fn build(preview: Value) -> Result { + build_with(preview, |_| {}) + } + + fn build_with(preview: Value, edit: impl FnOnce(&Path)) -> Result { + let root = tempfile::tempdir().unwrap(); + project(root.path()); + edit(root.path()); + let plan = native(preview); + plan.preview + .as_ref() + .unwrap() + .build_plan(root.path(), &plan) + } + + fn pointer(preview: Value) -> String { + refusal(build(preview)) + } + + fn refusal(built: Result) -> String { + let Err(error) = built else { + panic!("the preview plan was accepted"); + }; + error + .downcast_ref::() + .unwrap_or_else(|| panic!("not a semantic refusal: {error:#}")) + .to_string() + } + + #[test] + fn an_actors_preview_reaches_casework_and_the_coordinator_as_route_products() { + let build = build(actors()).unwrap(); + assert_eq!(build.product.id.as_str(), "permits"); + // Each actor carries its own BReg grant, and the build takes the + // first actor's as the generated client's profile. + assert_eq!(build.product.profile, "permit-applicant"); + assert_eq!( + serde_json::to_value(&build.route_products).unwrap(), + json!([ + {"id": "casework", "kind": "casework", "audience": "urn:review"}, + {"id": "permit-flow", "kind": "coordinator", "audience": "urn:flow"} + ]) + ); + } + + #[test] + fn an_actors_preview_refuses_each_mismatch_at_its_pointer() { + let mut both = actors(); + both["actor"] = json!("applicant"); + assert!(pointer(both).starts_with("dev.yaml /preview: ")); + + let mut stranger = actors(); + stranger["actors"]["stranger"] = json!({"breg": {"get": ["/v1/records/permits"]}}); + assert!(pointer(stranger).starts_with("dev.yaml /preview/actors/stranger: ")); + + // The officer has no Coordinator grant, so it cannot reach the Coordinator. + let mut ungranted = actors(); + ungranted["actors"]["officer"]["coordinator"] = json!({"get": ["/v1/runs/{runId}"]}); + assert!(pointer(ungranted).starts_with("dev.yaml /preview/actors/officer/coordinator: ")); + + let mut route = actors(); + route["actors"]["officer"]["casework"]["get"] = json!(["/v1/review-tasks/../admin"]); + assert!(pointer(route).starts_with("dev.yaml /preview/actors/officer/casework/get: ")); + + let mut two = actors(); + two["actors"]["officer"]["casework"]["get"] = json!(["/v1/review-tasks/{taskId}/{runId}"]); + assert!(pointer(two).starts_with("dev.yaml /preview/actors/officer/casework/get: ")); + } + + #[test] + fn an_actors_preview_refuses_an_empty_or_oversized_map_and_a_later_actor_without_breg() { + let mut empty = actors(); + empty["actors"] = json!({}); + assert_eq!( + pointer(empty), + "dev.yaml /preview/actors: A preview has one to eight actors. Next: Declare between one and eight actors." + ); + + // Two declared actors and seven more make nine. + let mut nine = actors(); + for index in 0..7 { + nine["actors"][format!("extra{index}")] = json!({}); + } + assert_eq!( + pointer(nine), + "dev.yaml /preview/actors: A preview has one to eight actors. Next: Declare between one and eight actors." + ); + + // The officer is not first in name order, and has only a Casework grant. + let mut plan = native(actors()); + plan.people + .get_mut("officer") + .unwrap() + .grants + .remove(&Product::Breg); + let root = tempfile::tempdir().unwrap(); + project(root.path()); + assert_eq!( + refusal(plan.preview.as_ref().unwrap().build_plan(root.path(), &plan)), + "dev.yaml /preview/actors/officer: Each preview actor needs a BReg grant. Next: Give the person a BReg role." + ); + } + + #[test] + fn an_actors_preview_refuses_a_product_it_cannot_route() { + let messaging = build_with(actors(), |root| { + fs::create_dir_all(root.join("messaging")).unwrap(); + fs::write(root.join("messaging/messaging.yaml"), "{}\n").unwrap(); + fs::write( + root.join("service.yaml"), + SERVICE.replace("ui: {", " messaging: {path: messaging}\nui: {"), + ) + .unwrap(); + }); + assert!(refusal(messaging).starts_with("dev.yaml /preview: ")); + } + + #[test] + fn an_actors_preview_refuses_two_projects_of_one_routed_product() { + let two = build_with(actors(), |root| { + fs::create_dir_all(root.join("second")).unwrap(); + fs::write(root.join("second/workflow.yaml"), "{}\n").unwrap(); + fs::write( + root.join("service.yaml"), + SERVICE.replace( + " permit-flow: {path: coordinator}\n", + " permit-flow: {path: coordinator}\n second-flow: {path: second}\n", + ), + ) + .unwrap(); + }); + assert_eq!( + refusal(two), + "dev.yaml /preview/actors: An actors preview reaches one project of each routed product. Next: Keep one Casework project and one Coordinator project in service.yaml." + ); + } + + fn run_input() -> RunInput { + let mut plan = serde_json::to_value(native(actors())).unwrap(); + plan["issuer"] = json!("http://127.0.0.1:45678"); + serde_json::from_value(json!({ + "run_id": "0123456789abcdef0123456789abcdef", + "project": "/project", + "ttl_seconds": 1800, + "plan": plan, + "schema_people": [], + "breg_authority": {"principal": "sub", "purpose": false, + "requires_postgis": false, "encrypts_fields": false, "named_clients": []}, + "casework_principals": {"permit-requester": "sub", "permit-officer": "sub"}, + "binaries": {} + })) + .unwrap() + } + + fn claims(file: &Path) -> Value { + use base64::Engine as _; + let line = fs::read_to_string(file).unwrap(); + let token = line + .strip_prefix("Authorization: Bearer ") + .unwrap() + .trim_end(); + let payload = token.split('.').nth(1).unwrap(); + serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .unwrap(), + ) + .unwrap() + } + + #[test] + fn authorization_writes_one_owner_only_file_per_actor_and_reached_product() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let signer = Issuer::create(root.path()).unwrap(); + let mut input = run_input(); + // The officer reaches BReg only through its always-present grant. + input + .plan + .preview + .as_mut() + .unwrap() + .actors + .as_mut() + .unwrap() + .get_mut(&LocalId::new("officer").unwrap()) + .unwrap() + .breg = Routes::default(); + let written = authorization(root.path(), &input, &signer, clock().unwrap() + 1800).unwrap(); + assert!(written.single.is_none()); + let expected = [ + ("applicant", Product::Breg, "urn:permits", "applicant"), + ("applicant", Product::Casework, "urn:review", "applicant"), + ("applicant", Product::Coordinator, "urn:flow", "applicant"), + ("officer", Product::Breg, "urn:permits", "officer"), + ("officer", Product::Casework, "urn:review", "officer"), + ]; + let listed: Vec<(&str, Product)> = written + .actors + .iter() + .flat_map(|(name, files)| files.keys().map(move |product| (name.as_str(), *product))) + .collect(); + assert_eq!( + listed, + expected + .iter() + .map(|(name, product, ..)| (*name, *product)) + .collect::>() + ); + for (name, product, audience, subject) in expected { + let file = &written.actors[name][&product]; + assert_eq!( + file, + &root + .path() + .join(format!("{AUTHORIZATION_FILE}-{name}-{}", product.name())) + ); + assert_eq!( + fs::metadata(file).unwrap().permissions().mode() & 0o777, + 0o600 + ); + let claims = claims(file); + assert_eq!(claims["aud"], audience, "{name} {product:?}"); + assert_eq!(claims["sub"], subject, "{name} {product:?}"); + } + } + + #[test] + fn each_actor_run_input_carries_its_own_origin_products_and_profiles() { + let build = build(actors()).unwrap(); + let plan = native(actors()); + let file = |name: &str| PathBuf::from(format!("/run/{name}")); + let authorization = PreviewAuthorization { + single: None, + actors: BTreeMap::from([ + ( + "applicant".to_owned(), + BTreeMap::from([ + (Product::Breg, file("a-breg")), + (Product::Coordinator, file("a-flow")), + ]), + ), + ( + "officer".to_owned(), + BTreeMap::from([ + (Product::Breg, file("o-breg")), + (Product::Casework, file("o-casework")), + ]), + ), + ]), + }; + let urls = BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:34567".to_owned()), + (Product::Casework, "http://127.0.0.1:34568".to_owned()), + (Product::Coordinator, "http://127.0.0.1:34569".to_owned()), + ]); + let super::super::products::PreviewActorInputs { + actors, + origins, + held, + } = super::super::products::preview_actor_inputs( + &plan, + &build, + &authorization, + &urls, + ("http://127.0.0.1:23456", 23456), + ) + .unwrap(); + assert_eq!(held.len(), 1); + let officer = format!("http://{}", held[0].local_addr().unwrap()); + assert_eq!( + origins, + [ + ("applicant".to_owned(), "http://127.0.0.1:23456".to_owned()), + ("officer".to_owned(), officer.clone()), + ] + ); + assert_eq!( + Value::from(actors), + json!([ + {"name": "applicant", "origin": "http://127.0.0.1:23456", "port": 23456, "products": { + "permits": {"baseUrl": "http://127.0.0.1:34567", "audience": "urn:permits", + "profile": "permit-applicant", "authorizationFile": "/run/a-breg"}, + "permit-flow": {"baseUrl": "http://127.0.0.1:34569", "audience": "urn:flow", + "profile": null, "authorizationFile": "/run/a-flow"}, + }}, + {"name": "officer", "origin": officer, "port": held[0].local_addr().unwrap().port(), "products": { + "permits": {"baseUrl": "http://127.0.0.1:34567", "audience": "urn:permits", + "profile": "permit-reader", "authorizationFile": "/run/o-breg"}, + "casework": {"baseUrl": "http://127.0.0.1:34568", "audience": "urn:review", + "profile": "permit-officer", "authorizationFile": "/run/o-casework"}, + }}, + ]) + ); + } + + #[test] + fn a_single_actor_preview_keeps_one_breg_product() { + let mut single = json!({ + "actor": "applicant", "page": "/", "functions": ["assess-permit"], + "breg": {"get": ["/v1/records/permits"]} + }); + // Casework and the Coordinator are reachable only through actors. + assert!(pointer(single.clone()).starts_with("dev.yaml /preview: ")); + single["breg"] = json!({}); + single.as_object_mut().unwrap().remove("actor"); + assert!(pointer(single).starts_with("dev.yaml /preview")); + } +} diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 667e2caeef..916f58479c 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -27,7 +27,7 @@ use std::{ }; use super::{ - bindings::{Bindings, BregReviewAuthority, RunIssuerBinding, RuntimeBindings}, + bindings::{Bindings, RunInitiator, RunProducer, RuntimeBindings}, browser::BrowserClient, clock, database::{Database, DatabaseUrls}, @@ -120,11 +120,28 @@ pub(super) struct ApplicationLaunch { pub(super) workdir: PathBuf, pub(super) environment: BTreeMap, pub(super) reservation: TcpListener, + /// Further loopback ports the application binds, such as the preview's + /// private function host and each further actor's gateway, held until + /// it starts. + pub(super) held: Vec, pub(super) health_path: String, } +/// The preview's private function host: a loopback port reserved before any +/// product starts, so Coordinator can name it, and a per-run key that only +/// the function host accepts. Coordinator presents the key as the bearer of +/// its service function calls; no product accepts it. +struct FunctionHost { + listener: RefCell>, + port: u16, + key_ref: String, + key_file: PathBuf, +} + pub(super) struct PreparedApplication { pub(super) launch: ApplicationLaunch, + /// Each preview actor and the loopback origin its gateway serves. + pub(super) actors: Vec<(String, String)>, pub(super) client: Option, } @@ -346,10 +363,12 @@ pub(super) struct ProductRunner<'a> { /// The loopback key set server Evidence's target names, stopped with the run. jwks: Option, coordinator_issuer: Option, + function_host: Option, /// The mock gateway Messaging's `http` providers send to, stopped with the /// run. gateway: Option, hook_sink: Option, + signed_hook_sinks: BTreeMap, /// Where each Messaging provider's sent messages can be read, by provider /// ID. sinks: BTreeMap, @@ -387,8 +406,10 @@ impl<'a> ProductRunner<'a> { issuer_listener: None, jwks: None, coordinator_issuer: None, + function_host: None, gateway: None, hook_sink: None, + signed_hook_sinks: BTreeMap::new(), sinks: BTreeMap::new(), messaging_providers: None, runtime_configs: BTreeMap::new(), @@ -555,6 +576,7 @@ impl<'a> ProductRunner<'a> { &issuer.public_jwks(), )?); } + self.reserve_function_host()?; // Keep the reservations for later products until each is ready to bind. let ports: Vec<_> = self .input @@ -685,6 +707,7 @@ impl<'a> ProductRunner<'a> { let log = open_log(self.root, "application-runtime")?; command.stdout(log.try_clone()?).stderr(log); drop(launch.reservation); + drop(launch.held); let child = command .spawn() .context("cannot start application") @@ -732,7 +755,7 @@ impl<'a> ProductRunner<'a> { pub(super) fn prepare_application( &self, urls: &BTreeMap, - preview_artifact: Option<(&Path, &Path)>, + preview_artifact: Option<(&Path, &super::preview::PreviewAuthorization)>, ) -> Result { self.ensure_active()?; let preview = self.input.preview.as_ref(); @@ -768,12 +791,38 @@ impl<'a> ProductRunner<'a> { .map_err(operational)?; let address = reservation.local_addr()?; let origin = format!("http://{address}"); - let (run, client) = if let Some((_, authorization_file)) = preview_artifact { + let mut held = Vec::new(); + let mut actor_origins = Vec::new(); + let (run, client) = if let Some((_, authorization)) = preview_artifact { let build = &preview.context("missing captured preview build")?.plan; ensure!( bounded_version(node, Some(&prepare))? == super::preview::VERSION, "The built preview helper version does not match this Stack version." ); + let mut run_preview = json!({ + "productId": build.product.id, + "profile": build.product.profile, + "declarationDigest": build.declaration_digest, + "functionHost": self.function_host_input()?, + }); + if let Some(file) = &authorization.single { + run_preview["authorizationFile"] = json!(file); + } else { + let PreviewActorInputs { + actors, + origins, + held: listeners, + } = preview_actor_inputs( + &self.input.plan, + build, + authorization, + urls, + (&origin, address.port()), + )?; + held.extend(listeners); + actor_origins.extend(origins); + run_preview["actors"] = json!(actors); + } ( json!({ "schema": plan.config_schema, @@ -785,12 +834,7 @@ impl<'a> ProductRunner<'a> { "baseUrl": urls[&Product::Breg], "audience": self.input.plan.product(Product::Breg).audience, }, - "preview": { - "productId": build.product.id, - "profile": build.product.profile, - "declarationDigest": build.declaration_digest, - "authorizationFile": authorization_file, - }, + "preview": run_preview, }), None, ) @@ -868,9 +912,19 @@ impl<'a> ProductRunner<'a> { workdir: root.to_owned(), environment, reservation, + held: preview_artifact + .and_then(|_| { + self.function_host + .as_ref() + .and_then(|host| host.listener.borrow_mut().take()) + }) + .into_iter() + .chain(held) + .collect(), health_path: plan.health_path.clone(), }, client, + actors: actor_origins, }) } @@ -1298,6 +1352,88 @@ impl<'a> ProductRunner<'a> { }) } + pub(super) fn signed_hook_reports(&self) -> serde_json::Map { + self.signed_hook_sinks + .iter() + .map(|(product, sink)| { + ( + product.name().to_owned(), + json!({"receivedUrl": format!("{}/received", sink.origin)}), + ) + }) + .collect() + } + + fn bind_signed_hooks( + &mut self, + product: Product, + project: &Path, + runtime: &mut Value, + ) -> Result<()> { + use registry_platform_crypto::delivery_signature::{DeliveryKey, DeliveryKeys}; + use registry_platform_yaml::LocalId; + + let project_file = match product { + Product::Documents => "documents.yaml", + Product::Scheduling => "scheduling.yaml", + _ => return Ok(()), + }; + // The product has already validated and packaged the authored policy. + // Read only the URL destination names the development runtime must bind. + let document = authored_document(&project.join(project_file))?; + let hooks = match &document["hooks"] { + Value::Null => Vec::new(), + Value::Array(hooks) if product == Product::Documents => hooks.iter().collect(), + Value::Object(hooks) if product == Product::Scheduling => hooks.values().collect(), + _ => anyhow::bail!("unexpected observer hook inventory in the checked project"), + }; + let destinations = hooks + .into_iter() + .filter(|hook| hook["handler"]["type"] == "url") + .map(|hook| { + let id = hook["handler"]["destinationId"] + .as_str() + .context("the URL observer must name a destination")?; + LocalId::new(id).context("invalid URL observer destination identifier")?; + Ok::<_, anyhow::Error>(id) + }) + .collect::>>()?; + if destinations.is_empty() { + return Ok(()); + } + + let mut keys = BTreeMap::new(); + let mut references = BTreeMap::new(); + for id in destinations { + let key = random_key_bytes()?; + let reference = + self.secret(&format!("{}-hook-{id}", product.name()), key.as_slice())?; + references.insert(id, reference); + keys.insert( + id.to_owned(), + DeliveryKeys::new(DeliveryKey::new(key.as_slice())?, None)?, + ); + } + let sink = GatewayServer::start_signed_hooks(keys)?; + let configs: serde_json::Map = references + .into_iter() + .map(|(id, reference)| { + ( + id.to_owned(), + json!({ + "url": format!("{}/events/{id}", sink.origin), + "hmacSha256KeyRef": reference, + "attemptTimeoutMilliseconds": 2000, + "maximumAttempts": 5, + }), + ) + }) + .collect(); + runtime["destinations"]["hooks"] = json!(configs); + self.signed_hook_sinks.insert(product, sink); + Ok(()) + } + fn activate_casework( &self, database: &mut Database, @@ -1363,7 +1499,7 @@ impl<'a> ProductRunner<'a> { } fn activate_additional( - &self, + &mut self, product: Product, database: Option<&mut Database>, project: &Path, @@ -1397,8 +1533,9 @@ impl<'a> ProductRunner<'a> { } else { None }; - let configuration = + let mut configuration = self.additional_config(product, project, bind, &package, database_urls.as_ref())?; + self.bind_signed_hooks(product, project, &mut configuration)?; let path = self.root.join(format!("{name}-runtime.yaml")); write_private(&path, &serde_json::to_vec(&configuration)?)?; @@ -1494,6 +1631,14 @@ impl<'a> ProductRunner<'a> { config["authentication"] = json!({"oidc": issuer_set(oidc)}); if product == Product::Scheduling { config["taskGrantStatus"] = json!("unchecked-final-fifteen-minutes"); + if let Some(external) = &self.input.plan.external_scheduling { + external.task_grant.configure( + |bytes| self.secret("scheduling-external-task-status-key", bytes), + &self.input.project, + &self.input.plan.issuer, + &mut config, + )?; + } config["retention"] = json!({}); } else { config["storage"] = json!({"type": "database"}); @@ -1535,6 +1680,7 @@ impl<'a> ProductRunner<'a> { authentication["accessProfiles"] = json!(profiles); let key = |file| self.retained_secret(name, file, random_key_bytes()?.as_slice()); let mut connections = runtime["connections"].clone(); + self.bind_service_functions(&mut connections)?; if let Some(connections) = connections.as_object_mut() { for (id, connection) in connections { registry_platform_yaml::LocalId::new(id.as_str()) @@ -1570,7 +1716,13 @@ impl<'a> ProductRunner<'a> { } } } - return Ok(json!({ + if let Some(casework) = + product_root(&self.input.project, &self.input.plan, Product::Casework)? + { + checked_coordinator_review_runtime(&self.input.plan, &casework.root, &runtime)?; + } + checked_coordinator_breg_runtime(&self.input.plan, &runtime)?; + let mut coordinator = json!({ "apiVersion": config["apiVersion"], "kind": "CoordinatorRuntimeConfig", "secretProviders": config["secretProviders"], @@ -1589,7 +1741,11 @@ impl<'a> ProductRunner<'a> { "stateKeys": {"1": {"keyRef": key("coordinator-state-key")?}}, "admissionKeyRef": key("coordinator-admission-key")?, } - })); + }); + if let Some(bindings) = &self.bindings { + bindings.configure(Product::Coordinator, &mut coordinator); + } + return Ok(coordinator); } Product::Adapter => { let template = authored_document(&project.join("runtime.example.yaml"))?; @@ -1808,6 +1964,86 @@ impl<'a> ProductRunner<'a> { Ok(path) } + /// Reserve the preview function host before products start. The port is + /// kept with the Coordinator state, like its issuer, because a live + /// workflow binds the function host address. + fn reserve_function_host(&mut self) -> Result<()> { + if self.input.plan.preview.is_none() || self.function_host.is_some() { + return Ok(()); + } + let state = self + .input + .plan + .products + .iter() + .any(|entry| entry.product == Product::Coordinator) + .then(|| self.product_state("coordinator")) + .flatten(); + let listener = retained_loopback_listener( + state.as_deref(), + "preview-function-host-port", + "the preview function host", + )?; + let port = listener.local_addr()?.port(); + let key_ref = self.secret(FUNCTION_HOST_KEY, random_secret()?.as_bytes())?; + self.function_host = Some(FunctionHost { + listener: RefCell::new(Some(listener)), + port, + key_ref, + key_file: self.root.join(FUNCTION_HOST_KEY), + }); + Ok(()) + } + + /// Bind each `service-function` connection to the preview function host + /// and its per-run key. The function must be one the preview serves, + /// which `service.yaml` declares. + fn bind_service_functions(&self, connections: &mut Value) -> Result<()> { + let Some(connections) = connections.as_object_mut() else { + return Ok(()); + }; + for (id, connection) in connections { + if connection["type"] != "service-function" { + continue; + } + let host = self.function_host.as_ref().with_context(|| { + format!("Coordinator connection {id} calls a service function, which needs the preview function host. Declare preview.functions in dev.yaml.") + })?; + let function = connection["function"] + .as_str() + .with_context(|| format!("Coordinator connection {id} names no function"))?; + let served = self.input.plan.preview.as_ref().is_some_and(|preview| { + preview + .functions + .iter() + .any(|name| name.as_str() == function) + }); + ensure!( + served, + "Coordinator connection {id} binds function {function}, which the preview does not serve. Declare it in service.yaml functions and dev.yaml preview.functions." + ); + let object = connection + .as_object_mut() + .context("a Coordinator connection must be a mapping")?; + object.remove("authorization"); + object.insert( + "baseUrl".into(), + json!(format!("http://127.0.0.1:{}/", host.port)), + ); + object.insert("hostKeyRef".into(), json!(host.key_ref)); + } + Ok(()) + } + + /// The preview run input's function host member. + fn function_host_input(&self) -> Result { + let host = self + .function_host + .as_ref() + .context("missing preview function host reservation")?; + Ok(json!({"port": host.port, "keyFile": host.key_file})) + } + fn product_state(&self, name: &str) -> Option { self.input .project_state(self.root) @@ -1971,6 +2207,7 @@ impl<'a> ProductRunner<'a> { drop(self.coordinator_issuer.take()); drop(self.gateway.take()); drop(self.hook_sink.take()); + self.signed_hook_sinks.clear(); Ok(()) } @@ -2000,19 +2237,32 @@ fn needs_stable_issuer(runtime: &Value, external_jwks: Option<&str>) -> bool { } fn coordinator_issuer_listener(state: Option<&Path>) -> Result { + retained_loopback_listener( + state, + "coordinator-issuer-port", + "the Coordinator development issuer", + ) +} + +/// The run file holding the preview function host key. +pub(super) const FUNCTION_HOST_KEY: &str = "preview-function-host-key"; + +/// A loopback listener whose port is kept in the project state, so a resumed +/// run binds the same address its live workflows name. +fn retained_loopback_listener(state: Option<&Path>, name: &str, what: &str) -> Result { let Some(state) = state else { return Ok(TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?); }; - let file = state.join("coordinator-issuer-port"); + let file = state.join(name); let port = match super::read_private(&file)? { Some(saved) => std::str::from_utf8(&saved)? .parse::() - .context("the retained Coordinator issuer port is invalid")? + .with_context(|| format!("the retained port of {what} is invalid"))? .get(), None => 0, }; let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).with_context(|| { - format!("cannot bind the Coordinator development issuer on loopback port {port}, which is kept for resumable workflow connections. Start with --clean") + format!("cannot bind {what} on loopback port {port}, which is kept for resumable workflow connections. Start with --clean") })?; if port == 0 { write_private(&file, listener.local_addr()?.port().to_string().as_bytes())?; @@ -2359,10 +2609,15 @@ fn shared_config( "runtimeUrlRef": secret_ref(&format!("{name}-runtime-url")), "migrationUrlRef": secret_ref(&format!("{name}-migration-url")) }); - if database_transport == DatabaseTransport::LoopbackPlaintext { - database["transport"] = json!("loopback-plaintext"); - } else if root.join("postgres-ca").is_file() { - database["caBundleRef"] = json!(secret_ref("postgres-ca")); + match database_transport { + DatabaseTransport::LoopbackPlaintext => database["transport"] = json!("loopback-plaintext"), + DatabaseTransport::PrivateNetworkPlaintext => { + database["transport"] = json!("private-network-plaintext"); + } + DatabaseTransport::VerifiedTls if root.join("postgres-ca").is_file() => { + database["caBundleRef"] = json!(secret_ref("postgres-ca")); + } + DatabaseTransport::VerifiedTls => {} } let audit = json!({ "hashKeyRef": secret_ref(&format!("{name}-audit-key")), @@ -2503,6 +2758,7 @@ pub(super) struct ProductInspection { #[error("{reason}")] pub(super) struct InspectionUnavailable { field: String, + location: Option, reason: String, remedy: String, } @@ -2511,6 +2767,7 @@ impl InspectionUnavailable { fn new(field: &str, reason: &str, remedy: &str) -> Self { Self { field: field.to_owned(), + location: None, reason: reason.to_owned(), remedy: remedy.to_owned(), } @@ -2520,6 +2777,18 @@ impl InspectionUnavailable { &self.field } + /// The authored file and position of the field, once located. + pub(super) fn location(&self) -> Option<®istry_platform_yaml::Source> { + self.location.as_ref() + } + + /// The same refusal at the authored location of its native plan field. + pub(super) fn at(mut self, field: &str, location: registry_platform_yaml::Source) -> Self { + field.clone_into(&mut self.field); + self.location = Some(location); + self + } + pub(super) fn reason(&self) -> &str { &self.reason } @@ -2600,6 +2869,9 @@ pub(super) fn inspect_with( let breg_authority = breg_authority(root, plan, terminate, &tool)?; let casework_principals = casework_principals(root, plan, breg_authority.as_ref(), terminate, &tool)?; + if let Some(coordinator) = product_root(root, plan, Product::Coordinator)? { + checked_coordinator_breg_client(plan, &coordinator.root)?; + } Ok(ProductInspection { breg_authority, casework_principals, @@ -2867,6 +3139,9 @@ fn casework_principals( if has_run_source(plan) { checked_casework_run_issuer(plan, &project.root)?; } + if let Some(coordinator) = product_root(root, plan, Product::Coordinator)? { + checked_coordinator_review_producer(plan, &project.root, &coordinator.root)?; + } if let Some(binding) = &plan.bindings.casework_context_provider { check_casework_binding(&tool, &project, plan, binding, terminate)?; } @@ -3686,26 +3961,61 @@ pub(super) fn schema_people( Ok(bindings) } -/// The dev.yaml member that carries the run issuer binding. -const RUN_ISSUER_BINDING: &str = "/bindings/bregReviewAuthority/runIssuerBinding"; +/// One Casework producer a run binds to its issuer: the dev.yaml binding +/// that names it, the producer, the test person whose grant and subject it +/// uses, and the exact guards. +struct GuardedProducer<'a> { + binding: &'static str, + producer: &'a str, + identity: &'a str, + guard: &'a RunProducer, + initiator: Option<&'a RunInitiator>, +} + +/// Every producer the plan binds to the run issuer. +fn guarded_producers(plan: &Plan) -> Vec> { + let mut producers = Vec::new(); + if let Some(binding) = &plan.bindings.breg_review_authority { + if let Some(guard) = &binding.run_issuer_binding { + producers.push(GuardedProducer { + binding: "/bindings/bregReviewAuthority", + producer: &binding.producer, + identity: &binding.identity, + guard: &guard.producer, + initiator: guard.initiator.as_ref(), + }); + } + } + if let Some(binding) = &plan.bindings.coordinator_review_producer { + producers.push(GuardedProducer { + binding: "/bindings/coordinatorReviewProducer", + producer: &binding.producer, + identity: &binding.identity, + guard: &binding.run_issuer_binding.producer, + initiator: None, + }); + } + producers +} /// Writes the run's loopback issuer into a copy of the Casework project at -/// `bound`. The source project is never edited. The copy changes only the -/// selected producer's `issuer`, and its `trustedInitiatorIssuer` when the +/// `bound`. The source project is never edited. The copy changes only each +/// bound producer's `issuer`, and its `trustedInitiatorIssuer` when the /// 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 (binding, guard) = run_issuer_binding(plan)?; 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 ); - let entry = &mut document["trustedProducers"][&binding.producer]; - entry["issuer"] = json!(plan.issuer); - if guard.initiator.is_some() { - entry["trustedInitiatorIssuer"] = json!(plan.issuer); + for bound_producer in guarded_producers(plan) { + let entry = &mut document["trustedProducers"][bound_producer.producer]; + entry["issuer"] = json!(plan.issuer); + if bound_producer.initiator.is_some() { + entry["trustedInitiatorIssuer"] = json!(plan.issuer); + } } copy_project(project, bound)?; write_private( @@ -3714,35 +4024,19 @@ fn bind_casework_run_issuer(plan: &Plan, project: &Path, bound: &Path) -> Result ) } -fn run_issuer_binding(plan: &Plan) -> Result<(&BregReviewAuthority, &RunIssuerBinding)> { - let binding = plan - .bindings - .breg_review_authority - .as_ref() - .context("the run issuer binding needs a review authority binding")?; - let guard = binding - .run_issuer_binding - .as_ref() - .context("the review authority binding has no run issuer binding")?; - Ok((binding, guard)) -} - /// 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 /// before binding the run issuer. fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { - let (binding, guard) = run_issuer_binding(plan)?; let refuse = |pointer: String, message: &str, action: &str| { anyhow::Error::from(plan::SemanticRefusal::new(&pointer, message, action)) }; - let identity = &plan.people[&binding.identity]; - let grant = &identity.grants[&Product::Casework]; - let person = format!( - "/people/{}", - registry_platform_yaml::escape_pointer_segment(&binding.identity) + let producers = guarded_producers(plan); + ensure!( + !producers.is_empty(), + "the plan binds no producer to the run issuer" ); - let source = project.join("casework.yaml"); let bytes = fs::read(&source).with_context(|| format!("cannot read {}", source.display()))?; let document = registry_platform_yaml::Reader::new(source.display().to_string()) @@ -3750,63 +4044,320 @@ fn checked_casework_run_issuer(plan: &Plan, project: &Path) -> Result { .map_err(|_| anyhow::anyhow!("{} is not valid YAML", source.display()))? .with_context(|| format!("{} is empty", source.display()))? .to_json_value(); - let producer = document["trustedProducers"][&binding.producer].clone(); - if !producer.is_object() { + for GuardedProducer { + binding, + producer: id, + identity: alias, + guard: expected, + initiator, + } in producers + { + 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( + format!("{binding}/producer"), + "The Casework project has no trusted producer with this ID.", + "Set producer to a trustedProducers entry in casework.yaml.", + )); + } + let text = |member: &str| producer[member].as_str().unwrap_or_default(); + if text("issuer") != expected.expected_issuer { + return Err(refuse( + format!("{run_issuer_binding}/producer/expectedIssuer"), + "The producer's issuer in casework.yaml is not the issuer the binding expects.", + "Set expectedIssuer to the issuer the Casework project pins for this producer.", + )); + } + if text("profile") != expected.expected_profile + || grant.profile != expected.expected_profile + { + return Err(refuse( + format!("{run_issuer_binding}/producer/expectedProfile"), + "The producer's profile in casework.yaml, the binding and the identity's Casework grant must be the same profile.", + "Set expectedProfile and the identity's Casework grant profile to the producer's profile.", + )); + } + if text("subject") != expected.expected_subject + || identity.subject != expected.expected_subject + { + return Err(refuse( + format!("{run_issuer_binding}/producer/expectedSubject"), + "The producer's subject in casework.yaml, the binding and the identity's subject must be the same subject.", + "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.", + )); + } + if let Some(initiator) = initiator { + if producer["trustedInitiatorIssuer"].as_str() + != Some(initiator.expected_issuer.as_str()) + { + return Err(refuse( + format!("{run_issuer_binding}/initiator/expectedIssuer"), + "The producer's trustedInitiatorIssuer in casework.yaml is not the issuer the binding expects.", + "Set expectedIssuer to the trustedInitiatorIssuer the Casework project pins for this producer.", + )); + } + } + } + Ok(document) +} + +/// Refuses, at the dev.yaml pointer, 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 +/// guards do not match. `check` runs this before any product starts and +/// `start` again before rendering the Coordinator. +fn checked_coordinator_review_producer( + plan: &Plan, + casework: &Path, + coordinator: &Path, +) -> Result<()> { + let runtime = authored_document(&coordinator.join("runtime.yaml"))?; + checked_coordinator_review_runtime(plan, casework, &runtime) +} + +/// The same check over a Coordinator runtime document already read, so +/// `start` checks exactly the document it renders. +fn checked_coordinator_review_runtime(plan: &Plan, casework: &Path, runtime: &Value) -> Result<()> { + const BINDING: &str = "/bindings/coordinatorReviewProducer"; + let refuse = |pointer: String, message: &str, action: &str| { + anyhow::Error::from(plan::SemanticRefusal::new(&pointer, message, action)) + }; + let Some(binding) = &plan.bindings.coordinator_review_producer else { + let producers = runtime["connections"] + .as_object() + .is_some_and(|connections| { + connections + .values() + .any(|connection| connection["type"] == "casework-review-producer") + }); + if producers + && plan + .products + .iter() + .any(|entry| entry.product == Product::Casework) + { + return Err(refuse( + "/bindings".to_owned(), + "A Coordinator casework-review-producer connection needs bindings.coordinatorReviewProducer before Casework trusts it in this run.", + "Add bindings.coordinatorReviewProducer naming the connection, producer, identity, completion destination and run issuer guards.", + )); + } + return Ok(()); + }; + let unbound = runtime["connections"] + .as_object() + .is_some_and(|connections| { + connections.iter().any(|(name, connection)| { + name != &binding.connection && connection["type"] == "casework-review-producer" + }) + }); + if unbound { return Err(refuse( - "/bindings/bregReviewAuthority/producer".to_owned(), - "The Casework project has no trusted producer with this ID.", - "Set producer to a trustedProducers entry in casework.yaml.", + format!("{BINDING}/connection"), + "Another Coordinator casework-review-producer connection has no binding, so Casework would not trust it in this run.", + "Keep one casework-review-producer connection, the one this binding names.", )); } - let text = |member: &str| producer[member].as_str().unwrap_or_default(); - let expected = &guard.producer; - if text("issuer") != expected.expected_issuer { + let connection = &runtime["connections"][&binding.connection]; + if connection["type"] != "casework-review-producer" { return Err(refuse( - format!("{RUN_ISSUER_BINDING}/producer/expectedIssuer"), - "The producer's issuer in casework.yaml is not the issuer the binding expects.", - "Set expectedIssuer to the issuer the Casework project pins for this producer.", + format!("{BINDING}/connection"), + "The Coordinator runtime.yaml has no casework-review-producer connection with this name.", + "Set connection to the Coordinator connection that submits review requests to Casework.", )); } - if text("profile") != expected.expected_profile || grant.profile != expected.expected_profile { + if connection["producer"].as_str() != Some(binding.producer.as_str()) { return Err(refuse( - format!("{RUN_ISSUER_BINDING}/producer/expectedProfile"), - "The producer's profile in casework.yaml, the binding and the identity's Casework grant must be the same profile.", - "Set expectedProfile and the identity's Casework grant profile to the producer's profile.", + format!("{BINDING}/producer"), + "The Coordinator connection names another Casework producer.", + "Set producer to the producer the Coordinator connection names.", )); } - if text("subject") != expected.expected_subject || identity.subject != expected.expected_subject - { + let grant = &plan.people[&binding.identity].grants[&Product::Casework]; + if connection["profile"].as_str() != Some(grant.profile.as_str()) { return Err(refuse( - format!("{RUN_ISSUER_BINDING}/producer/expectedSubject"), - "The producer's subject in casework.yaml, the binding and the identity's subject must be the same subject.", - "Set expectedSubject and the identity's subject to the producer's subject.", + format!("{BINDING}/connection"), + "The Coordinator connection's profile is not the identity's Casework grant profile.", + "Set the connection's profile to the producer's Casework profile.", )); } - 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)) - { + let Some(recipient) = connection["completion"]["recipientBinding"].as_str() else { + return Err(refuse( + format!("{BINDING}/connection"), + "The Coordinator connection has no completion, so Casework could not wake the waiting run.", + "Add completion with the recipientBinding casework.yaml names; the run supplies its key.", + )); + }; + let document = checked_casework_run_issuer(plan, casework)?; + let completion = &document["trustedProducers"][&binding.producer]["completion"]; + if completion["destinationId"].as_str() != Some(binding.completion_destination.as_str()) { 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.", + format!("{BINDING}/completionDestination"), + "The producer's completion destination in casework.yaml is not the binding's.", + "Set completionDestination to the producer's completion destinationId in casework.yaml.", )); } - if let Some(initiator) = &guard.initiator { - if producer["trustedInitiatorIssuer"].as_str() != Some(initiator.expected_issuer.as_str()) { - return Err(refuse( - format!("{RUN_ISSUER_BINDING}/initiator/expectedIssuer"), - "The producer's trustedInitiatorIssuer in casework.yaml is not the issuer the binding expects.", - "Set expectedIssuer to the trustedInitiatorIssuer the Casework project pins for this producer.", - )); + if completion["recipientBinding"].as_str() != Some(recipient) { + return Err(refuse( + format!("{BINDING}/connection"), + "The Coordinator connection's completion recipientBinding is not the one casework.yaml names for this producer.", + "Use the same recipientBinding in the Coordinator connection and the producer's completion.", + )); + } + Ok(()) +} + +/// The run input for each preview actor, in name order: one gateway origin +/// per actor, the first on the run's reserved address and every further actor +/// on its own reserved listener, with a credential file, audience and pinned +/// profile (none for the Coordinator) for each product the actor reaches. +pub(super) struct PreviewActorInputs { + /// The `preview.actors` run input. + pub actors: Vec, + /// Each actor's name and gateway origin. + pub origins: Vec<(String, String)>, + /// The further actors' reserved listeners, held until their gateways bind. + pub held: Vec, +} + +pub(super) fn preview_actor_inputs( + plan: &Plan, + build: &super::preview::BuildPlan, + authorization: &super::preview::PreviewAuthorization, + urls: &BTreeMap, + first: (&str, u16), +) -> Result { + let mut actors = Vec::new(); + let mut origins = Vec::new(); + let mut held = Vec::new(); + for (index, (name, files)) in authorization.actors.iter().enumerate() { + let (actor_origin, port) = if index == 0 { + (first.0.to_owned(), first.1) + } else { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .context("reserve preview actor loopback listener") + .map_err(operational)?; + let address = listener.local_addr()?; + held.push(listener); + (format!("http://{address}"), address.port()) + }; + let person = plan.people.get(name).context("missing preview actor")?; + let mut products = serde_json::Map::new(); + for (product, file) in files { + let id = if *product == Product::Breg { + build.product.id.as_str().to_owned() + } else { + build + .route_products + .iter() + .find(|route| route.kind == product.name()) + .context("missing preview route product")? + .id + .as_str() + .to_owned() + }; + let profile = if *product == Product::Coordinator { + None + } else { + Some( + person + .grants + .get(product) + .context("missing preview actor grant")? + .profile + .clone(), + ) + }; + products.insert( + id, + json!({ + "baseUrl": urls.get(product).context("missing preview product origin")?, + "audience": plan.product(*product).audience, + "profile": profile, + "authorizationFile": file, + }), + ); } + origins.push((name.clone(), actor_origin.clone())); + actors.push(json!({ + "name": name, "origin": actor_origin, "port": port, "products": products, + })); } - Ok(document) + Ok(PreviewActorInputs { + actors, + origins, + held, + }) +} + +/// Refuses, at the dev.yaml pointer, a Coordinator BReg client binding whose +/// connection is not a `breg` connection without task authority, using the +/// identity's BReg grant profile. `check` runs this before any product starts +/// and `start` again before rendering the Coordinator. +fn checked_coordinator_breg_client(plan: &Plan, coordinator: &Path) -> Result<()> { + if plan.bindings.coordinator_breg_client.is_none() { + return Ok(()); + } + let runtime = authored_document(&coordinator.join("runtime.yaml"))?; + checked_coordinator_breg_runtime(plan, &runtime) +} + +/// The same check over a Coordinator runtime document already read, so +/// `start` checks exactly the document it renders. +fn checked_coordinator_breg_runtime(plan: &Plan, runtime: &Value) -> Result<()> { + const CONNECTION: &str = "/bindings/coordinatorBregClient/connection"; + let Some(binding) = &plan.bindings.coordinator_breg_client else { + return Ok(()); + }; + let refuse = |message: &str, action: &str| { + Err(anyhow::Error::from(plan::SemanticRefusal::new( + CONNECTION, message, action, + ))) + }; + let connection = &runtime["connections"][&binding.connection]; + if connection["type"] != "breg" { + return refuse( + "The Coordinator runtime.yaml has no breg connection with this name.", + "Set connection to the Coordinator connection that invokes BReg Actions.", + ); + } + if !connection["authorization"]["taskAuthority"].is_null() { + return refuse( + "The connection delegates to task authority, which this binding never supplies.", + "Remove taskAuthority from the bound connection.", + ); + } + let grant = &plan.people[&binding.identity].grants[&Product::Breg]; + if connection["profile"].as_str() != Some(grant.profile.as_str()) { + return refuse( + "The connection's profile is not the identity's BReg grant profile.", + "Set the connection's profile to the identity's BReg grant profile.", + ); + } + Ok(()) } /// Only a reserved loopback run URL is bound, never a remote issuer. @@ -4155,9 +4706,393 @@ mod tests { identity: "context-reader".to_owned(), action: "review-action".to_owned(), }), + coordinator_review_producer: None, + coordinator_breg_client: None, } } + /// A Casework and Coordinator plan whose Coordinator `review` connection is + /// bound as the `coordinator` producer, with its casework.yaml and the + /// Coordinator runtime.yaml. + fn coordinator_producer_fixture() -> (Value, Value, Value) { + let plan = json!({ + "issuer": "http://127.0.0.1:41000/", + "products": [ + {"product": "casework", "project": "casework", "audience": "review"}, + {"product": "coordinator", "project": "coordinator", "audience": "urn:coordinator"} + ], + "people": {"coordinator": { + "subject": "coordinator-producer", "client": "coordinator-client", + "grants": {"casework": {"profile": "coordinator-producer", "scopes": ["review.write"]}} + }}, + "journeyFile": "dev-journeys.yaml", + "bindings": {"coordinatorReviewProducer": { + "connection": "review", "producer": "coordinator", "identity": "coordinator", + "completionDestination": "coordinator-wake", + "runIssuerBinding": {"producer": { + "expectedIssuer": PRODUCER_ISSUER, + "expectedProfile": "coordinator-producer", + "expectedSubject": "coordinator-producer" + }} + }} + }); + let casework = json!({ + "name": "synthetic-project", + "accessProfiles": {"coordinator-producer": {"requiredScopes": ["review.write"]}}, + "trustedProducers": { + "coordinator": { + "issuer": PRODUCER_ISSUER, "profile": "coordinator-producer", + "subject": "coordinator-producer", + "completion": {"destinationId": "coordinator-wake", "recipientBinding": "coordinator-v1"} + }, + "other-producer": {"issuer": "https://other.example.invalid/"} + } + }); + let coordinator = json!({"connections": {"review": { + "type": "casework-review-producer", "baseUrl": "http://127.0.0.1:1", + "profile": "coordinator-producer", "producer": "coordinator", + "completion": {"recipientBinding": "coordinator-v1", "hmacSha256KeyRef": "secret:file/authored"} + }}}); + (plan, casework, coordinator) + } + + fn coordinator_producer_projects( + root: &Path, + casework: &Value, + coordinator: &Value, + ) -> (PathBuf, PathBuf) { + let casework = write_casework_project(root, casework); + let project = root.join("coordinator"); + fs::create_dir(&project).unwrap(); + fs::write( + project.join("runtime.yaml"), + serde_norway::to_string(coordinator).unwrap(), + ) + .unwrap(); + (casework, project) + } + + #[test] + fn a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer() { + type Break = fn(&mut Value, &mut Value, &mut Value); + // Each case names its pointer and a fragment of its own refusal, so + // two refusals at one pointer cannot stand in for each other. + const BINDING: &str = "/bindings/coordinatorReviewProducer"; + let cases: [(&str, String, &str, Break); 13] = [ + ( + "the producer issuer differs from the binding", + format!("{BINDING}/runIssuerBinding/producer/expectedIssuer"), + "issuer in casework.yaml", + |_, casework, _| { + casework["trustedProducers"]["coordinator"]["issuer"] = + json!("https://elsewhere.example.invalid/") + }, + ), + ( + "casework.yaml profile differs from the binding", + format!("{BINDING}/runIssuerBinding/producer/expectedProfile"), + "profile in casework.yaml", + |_, casework, _| { + casework["trustedProducers"]["coordinator"]["profile"] = json!("other-profile") + }, + ), + ( + "the identity subject differs from the binding", + format!("{BINDING}/runIssuerBinding/producer/expectedSubject"), + "subject in casework.yaml", + |plan, _, _| plan["people"]["coordinator"]["subject"] = json!("someone-else"), + ), + ( + "the producer is not in casework.yaml", + format!("{BINDING}/producer"), + "no trusted producer", + |_, casework, _| { + casework["trustedProducers"] + .as_object_mut() + .unwrap() + .remove("coordinator"); + }, + ), + ( + "the connection is missing", + format!("{BINDING}/connection"), + "no casework-review-producer connection", + |_, _, coordinator| { + coordinator["connections"] + .as_object_mut() + .unwrap() + .remove("review"); + }, + ), + ( + "the connection is of another type", + format!("{BINDING}/connection"), + "no casework-review-producer connection", + |_, _, coordinator| coordinator["connections"]["review"]["type"] = json!("breg"), + ), + ( + "the connection names another producer", + format!("{BINDING}/producer"), + "names another Casework producer", + |_, _, coordinator| { + coordinator["connections"]["review"]["producer"] = json!("other-producer") + }, + ), + ( + "the connection profile differs from the grant", + format!("{BINDING}/connection"), + "profile is not the identity", + |_, _, coordinator| { + coordinator["connections"]["review"]["profile"] = json!("other-profile") + }, + ), + ( + "the producer has no completion destination", + format!("{BINDING}/completionDestination"), + "completion destination in casework.yaml", + |_, casework, _| { + casework["trustedProducers"]["coordinator"] + .as_object_mut() + .unwrap() + .remove("completion"); + }, + ), + ( + "the completion destination differs", + format!("{BINDING}/completionDestination"), + "completion destination in casework.yaml", + |_, casework, _| { + casework["trustedProducers"]["coordinator"]["completion"]["destinationId"] = + json!("elsewhere") + }, + ), + ( + "the recipient binding differs", + format!("{BINDING}/connection"), + "recipientBinding is not", + |_, _, coordinator| { + coordinator["connections"]["review"]["completion"]["recipientBinding"] = + json!("other-v1") + }, + ), + ( + "the connection has no completion key", + format!("{BINDING}/connection"), + "has no completion", + |_, _, coordinator| { + coordinator["connections"]["review"] + .as_object_mut() + .unwrap() + .remove("completion"); + }, + ), + ( + "a second casework-review-producer connection is unbound", + format!("{BINDING}/connection"), + "Another Coordinator", + |_, _, coordinator| { + let second = coordinator["connections"]["review"].clone(); + coordinator["connections"]["second-review"] = second; + }, + ), + ]; + let root = tempfile::tempdir().unwrap(); + for (index, (name, pointer, fragment, break_it)) in cases.into_iter().enumerate() { + let (mut plan, mut casework, mut coordinator) = coordinator_producer_fixture(); + break_it(&mut plan, &mut casework, &mut coordinator); + let case_root = root.path().join(index.to_string()); + fs::create_dir(&case_root).unwrap(); + let (casework, coordinator) = + coordinator_producer_projects(&case_root, &casework, &coordinator); + let plan: Plan = serde_json::from_value(plan).unwrap(); + let error = + checked_coordinator_review_producer(&plan, &casework, &coordinator).unwrap_err(); + let refusal = error + .downcast_ref::() + .unwrap_or_else(|| panic!("{name}: not a semantic refusal: {error}")); + assert!( + refusal + .to_string() + .starts_with(&format!("dev.yaml {pointer}: ")) + && refusal.to_string().contains(fragment), + "{name}: {refusal}" + ); + } + } + + #[test] + fn a_coordinator_casework_producer_without_its_binding_is_refused() { + let root = tempfile::tempdir().unwrap(); + let (mut plan, casework, coordinator) = coordinator_producer_fixture(); + plan.as_object_mut().unwrap().remove("bindings"); + let (casework, coordinator) = + coordinator_producer_projects(root.path(), &casework, &coordinator); + let plan: Plan = serde_json::from_value(plan).unwrap(); + let error = + checked_coordinator_review_producer(&plan, &casework, &coordinator).unwrap_err(); + let refusal = error.downcast_ref::().unwrap(); + assert!( + refusal.to_string().starts_with("dev.yaml /bindings: "), + "{refusal}" + ); + assert!( + refusal.to_string().contains("coordinatorReviewProducer"), + "{refusal}" + ); + } + + #[test] + fn a_bound_coordinator_producer_trusts_only_the_run_issuer_for_that_producer() { + let root = tempfile::tempdir().unwrap(); + let (plan, casework, coordinator) = coordinator_producer_fixture(); + let (project, coordinator_project) = + coordinator_producer_projects(root.path(), &casework, &coordinator); + let plan: Plan = serde_json::from_value(plan).unwrap(); + checked_coordinator_review_producer(&plan, &project, &coordinator_project).unwrap(); + assert!(has_run_source(&plan)); + let bound = root.path().join("bound"); + bind_casework_run_issuer(&plan, &project, &bound).unwrap(); + // Only the bound producer's issuer changes; every other member of the + // document stays exactly as written. + let mut expected = casework.clone(); + expected["trustedProducers"]["coordinator"]["issuer"] = json!(plan.issuer); + let document = authored_document(&bound.join("casework.yaml")).unwrap(); + assert_eq!(document, expected); + } + + #[test] + fn both_bound_producers_are_checked_and_rebound() { + let (breg_plan, breg_casework) = run_issuer_fixture(false); + let (mut plan, mut casework, _) = coordinator_producer_fixture(); + plan["products"] + .as_array_mut() + .unwrap() + .push(json!({"product": "breg", "project": "breg", "audience": "registry"})); + plan["people"]["authority"] = breg_plan["people"]["authority"].clone(); + plan["bindings"]["bregReviewAuthority"] = + breg_plan["bindings"]["bregReviewAuthority"].clone(); + casework["accessProfiles"]["review-producer"] = + breg_casework["accessProfiles"]["review-producer"].clone(); + casework["trustedProducers"]["producer"] = + breg_casework["trustedProducers"]["producer"].clone(); + let root = tempfile::tempdir().unwrap(); + let project = write_casework_project(root.path(), &casework); + let checked: Plan = serde_json::from_value(plan.clone()).unwrap(); + let bound = root.path().join("bound"); + bind_casework_run_issuer(&checked, &project, &bound).unwrap(); + let mut expected = casework.clone(); + expected["trustedProducers"]["producer"]["issuer"] = json!(checked.issuer); + expected["trustedProducers"]["coordinator"]["issuer"] = json!(checked.issuer); + assert_eq!( + authored_document(&bound.join("casework.yaml")).unwrap(), + expected + ); + + // The second producer's guards are checked as well as the first's. + let mut broken = casework.clone(); + broken["trustedProducers"]["coordinator"]["issuer"] = + json!("https://elsewhere.example.invalid/"); + let other = root.path().join("broken"); + fs::create_dir(&other).unwrap(); + let project = write_casework_project(&other, &broken); + let error = checked_casework_run_issuer(&checked, &project).unwrap_err(); + assert!( + error.to_string().contains( + "/bindings/coordinatorReviewProducer/runIssuerBinding/producer/expectedIssuer" + ), + "{error}" + ); + } + + #[test] + fn a_coordinator_breg_client_refuses_each_mismatch_at_its_connection() { + const CONNECTION: &str = "/bindings/coordinatorBregClient/connection"; + let plan: Plan = serde_json::from_value(json!({ + "issuer": "http://127.0.0.1:41000/", + "products": [ + {"product": "breg", "project": "breg", "audience": "registry"}, + {"product": "coordinator", "project": "coordinator", "audience": "urn:coordinator"} + ], + "people": {"coordinator": { + "subject": "coordinator-service", "client": "coordinator-client", + "grants": {"breg": {"profile": "permit-coordinator", "scopes": ["registry:actions:invoke"]}} + }}, + "journeyFile": "dev-journeys.yaml", + "bindings": {"coordinatorBregClient": {"connection": "registry", "identity": "coordinator"}} + })) + .unwrap(); + let connection = json!({ + "type": "breg", "baseUrl": "http://127.0.0.1:1", "profile": "permit-coordinator" + }); + type Break = fn(&mut Value); + // Each case names a fragment of its own refusal. + let cases: [(&str, &str, Break); 4] = [ + ( + "the connection is missing", + "no breg connection", + |runtime| { + runtime["connections"] + .as_object_mut() + .unwrap() + .remove("registry"); + }, + ), + ( + "the connection is of another type", + "no breg connection", + |runtime| { + runtime["connections"]["registry"]["type"] = json!("messaging"); + }, + ), + ( + "the connection names another profile", + "grant profile", + |runtime| { + runtime["connections"]["registry"]["profile"] = json!("permit-reader"); + }, + ), + ( + "the connection delegates to task authority", + "task authority", + |runtime| { + runtime["connections"]["registry"]["authorization"] = + json!({"taskAuthority": {"issuer": "https://casework.example"}}); + }, + ), + ]; + let root = tempfile::tempdir().unwrap(); + for (index, (name, fragment, break_it)) in cases.into_iter().enumerate() { + let mut runtime = json!({"connections": {"registry": connection.clone()}}); + break_it(&mut runtime); + let project = root.path().join(index.to_string()); + fs::create_dir(&project).unwrap(); + fs::write( + project.join("runtime.yaml"), + serde_norway::to_string(&runtime).unwrap(), + ) + .unwrap(); + let error = checked_coordinator_breg_client(&plan, &project).unwrap_err(); + let refusal = error + .downcast_ref::() + .unwrap_or_else(|| panic!("{name}: not a semantic refusal: {error}")); + assert!( + refusal + .to_string() + .starts_with(&format!("dev.yaml {CONNECTION}: ")) + && refusal.to_string().contains(fragment), + "{name}: {refusal}" + ); + } + let project = root.path().join("accepted"); + fs::create_dir(&project).unwrap(); + fs::write( + project.join("runtime.yaml"), + serde_norway::to_string(&json!({"connections": {"registry": connection}})).unwrap(), + ) + .unwrap(); + checked_coordinator_breg_client(&plan, &project).unwrap(); + } + #[test] fn breg_binding_ids_are_resolved_with_typed_value_free_refusals() { let bindings = product_bindings(); @@ -4597,6 +5532,21 @@ mod tests { ); assert_eq!(plaintext["database"]["transport"], "loopback-plaintext"); assert!(plaintext["database"].get("caBundleRef").is_none()); + + let private = casework_config( + &runner.input.plan, + "casework", + &root, + &package, + &identity, + "127.0.0.1:0", + DatabaseTransport::PrivateNetworkPlaintext, + ); + assert_eq!( + private["database"]["transport"], + "private-network-plaintext" + ); + assert!(private["database"].get("caBundleRef").is_none()); } #[test] @@ -5198,6 +6148,7 @@ mod tests { workdir: root.to_path_buf(), environment, reservation, + held: Vec::new(), health_path: "/health".to_owned(), }, port, @@ -5350,6 +6301,204 @@ mod tests { assert_eq!(restarted.local_addr().unwrap(), address); } + /// A Coordinator project whose runtime declares one service function + /// connection, run with a preview serving `served`. + fn function_runner_input(served: Option<&[&str]>) -> RunInput { + let mut input = breg_input(false); + input.plan.products = serde_json::from_value(json!([ + {"product": "breg", "project": ".", "audience": "registry"}, + {"product": "coordinator", "project": ".", "audience": "urn:example:local"} + ])) + .unwrap(); + input.plan.people.clear(); + input.plan.people.insert( + "tester".to_owned(), + serde_json::from_value(json!({ + "subject": "tester", "client": "console", + "grants": {"coordinator": {"profile": "local-console", "scopes": ["read"]}} + })) + .unwrap(), + ); + input.plan.preview = served.map(|functions| { + serde_json::from_value(json!({ + "actor": "tester", "page": "/", "breg": {}, "functions": functions + })) + .unwrap() + }); + input + } + + fn function_project(root: &Path) -> PathBuf { + let package = root.join("package"); + fs::create_dir(&package).unwrap(); + fs::write(package.join("SHA256SUMS"), b"test checksum file").unwrap(); + fs::write(root.join("workflow.yaml"), "project: {id: notices}").unwrap(); + fs::write( + root.join("runtime.yaml"), + "connections:\n drafts:\n type: service-function\n baseUrl: http://127.0.0.1:1/\n function: draft-notice\n authorization: {tokenEndpoint: 'http://127.0.0.1:1/token', clientAssertionAudience: 'http://127.0.0.1:1', clientId: authored, signingKeyRef: 'secret:file/authored-key', resource: 'urn:example:authored', scopes: [x]}\n responseSchema: {type: object}\n", + ) + .unwrap(); + package + } + + fn coordinator_config(runner: &ProductRunner, root: &Path, package: &Path) -> Result { + let database = DatabaseUrls { + runtime: "postgresql://runtime@localhost/database".to_owned(), + migration: "postgresql://migration@localhost/database".to_owned(), + transport: DatabaseTransport::VerifiedTls, + }; + runner.additional_config( + Product::Coordinator, + root, + "127.0.0.1:34567", + package, + Some(&database), + ) + } + + #[test] + fn start_rechecks_the_bound_breg_connection_it_renders() { + // check passed earlier; the runtime.yaml start renders has since + // changed the bound connection's profile. + let root = tempfile::tempdir().unwrap(); + let package = root.path().join("package"); + fs::create_dir(&package).unwrap(); + fs::write(package.join("SHA256SUMS"), b"test checksum file").unwrap(); + fs::write(root.path().join("workflow.yaml"), "project: {id: permits}").unwrap(); + fs::write( + root.path().join("runtime.yaml"), + "connections:\n registry:\n type: breg\n baseUrl: http://127.0.0.1:1\n profile: changed-profile\n", + ) + .unwrap(); + let mut input = breg_input(false); + input.plan.products = serde_json::from_value(json!([ + {"product": "breg", "project": ".", "audience": "registry"}, + {"product": "coordinator", "project": ".", "audience": "urn:example:local"} + ])) + .unwrap(); + input.plan.people.clear(); + input.plan.people.insert( + "coordinator".to_owned(), + serde_json::from_value(json!({ + "subject": "coordinator-service", "client": "coordinator-client", + "grants": {"breg": {"profile": "permit-coordinator", "scopes": ["registry:actions:invoke"]}} + })) + .unwrap(), + ); + input.plan.bindings = serde_json::from_value(json!({"coordinatorBregClient": { + "connection": "registry", "identity": "coordinator" + }})) + .unwrap(); + let terminate = AtomicBool::new(false); + let runner = ProductRunner::new(Arc::new(input), root.path(), &terminate).unwrap(); + let database = DatabaseUrls { + runtime: "postgresql://runtime@localhost/database".to_owned(), + migration: "postgresql://migration@localhost/database".to_owned(), + transport: DatabaseTransport::VerifiedTls, + }; + let error = runner + .additional_config( + Product::Coordinator, + root.path(), + "127.0.0.1:34567", + &package, + Some(&database), + ) + .unwrap_err(); + let refusal = error + .downcast_ref::() + .unwrap_or_else(|| panic!("not a semantic refusal: {error:#}")); + assert!( + refusal + .to_string() + .starts_with("dev.yaml /bindings/coordinatorBregClient/connection: ") + && refusal.to_string().contains("grant profile"), + "{refusal}" + ); + } + + #[test] + fn a_service_function_connection_names_the_preview_host_and_its_run_key() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let terminate = AtomicBool::new(false); + let mut runner = ProductRunner::new( + Arc::new(function_runner_input(Some(&[ + "draft-notice", + "publish-notice", + ]))), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + let host = runner.function_host.as_ref().unwrap(); + let port = host.port; + let config = coordinator_config(&runner, root.path(), &package).unwrap(); + let drafts = &config["connections"]["drafts"]; + assert_eq!(drafts["baseUrl"], format!("http://127.0.0.1:{port}/")); + assert_eq!(drafts["hostKeyRef"], secret_ref(FUNCTION_HOST_KEY)); + assert!(drafts.get("authorization").is_none(), "{drafts}"); + + // The key is an owner-only bearer-safe secret in the run directory, + // the same file the preview host reads. + let key_file = root.path().join(FUNCTION_HOST_KEY); + let key = fs::read_to_string(&key_file).unwrap(); + assert!( + key.len() >= 32 + && key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + ); + assert_eq!( + fs::metadata(&key_file).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + runner.function_host_input().unwrap(), + json!({"port": port, "keyFile": key_file}) + ); + // The port stays reserved until the preview host starts. + assert!(TcpListener::bind((Ipv4Addr::LOCALHOST, port)).is_err()); + } + + #[test] + fn a_service_function_the_preview_does_not_serve_is_refused() { + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let terminate = AtomicBool::new(false); + let mut runner = ProductRunner::new( + Arc::new(function_runner_input(Some(&["publish-notice"]))), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + let error = coordinator_config(&runner, root.path(), &package) + .unwrap_err() + .to_string(); + assert!( + error.contains("draft-notice") && error.contains("service.yaml"), + "{error}" + ); + + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let mut runner = ProductRunner::new( + Arc::new(function_runner_input(None)), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + assert!(runner.function_host.is_none()); + let error = coordinator_config(&runner, root.path(), &package) + .unwrap_err() + .to_string(); + assert!(error.contains("preview.functions"), "{error}"); + } + #[test] fn additional_runtime_configuration_uses_run_authority_and_loopback() { let root = tempfile::tempdir().unwrap(); @@ -5553,6 +6702,56 @@ INVENTORY } } + #[test] + fn signed_observer_hooks_connect_only_declared_destinations_to_the_run_sink() { + let root = tempfile::tempdir().unwrap(); + let terminate = AtomicBool::new(false); + let mut runner = + ProductRunner::new(Arc::new(breg_input(false)), root.path(), &terminate).unwrap(); + for (product, name) in [ + (Product::Documents, "documents.yaml"), + (Product::Scheduling, "scheduling.yaml"), + ] { + let policy = root.path().join(name); + let (empty, declared) = match product { + Product::Documents => ( + "hooks: []\n", + "hooks:\n - handler: {type: url, destinationId: events}\n - handler: {type: url, destinationId: events}\n", + ), + Product::Scheduling => ( + "hooks: {}\n", + "hooks:\n booking: {handler: {type: url, destinationId: events}}\n cancellation: {handler: {type: url, destinationId: events}}\n", + ), + _ => unreachable!(), + }; + fs::write(&policy, empty).unwrap(); + let mut config = json!({}); + runner + .bind_signed_hooks(product, root.path(), &mut config) + .unwrap(); + assert_eq!(config, json!({})); + assert!(!runner.signed_hook_reports().contains_key(product.name())); + + fs::write(&policy, declared).unwrap(); + runner + .bind_signed_hooks(product, root.path(), &mut config) + .unwrap(); + let hooks = config["destinations"]["hooks"].as_object().unwrap(); + assert_eq!(hooks.len(), 1); + let report = runner.signed_hook_reports(); + let received = report[product.name()]["receivedUrl"].as_str().unwrap(); + let origin = received.strip_suffix("/received").unwrap(); + assert!(origin.starts_with("http://127.0.0.1:")); + assert_eq!(hooks["events"]["url"], format!("{origin}/events/events")); + let file = format!("{}-hook-events", product.name()); + assert_eq!( + hooks["events"]["hmacSha256KeyRef"], + format!("secret:file/{file}") + ); + assert_eq!(fs::metadata(runner.root.join(file)).unwrap().len(), 32); + } + } + #[test] fn external_hook_ids_must_match_the_inventory_exactly() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/registry-rstack-dev/src/roles.rs b/crates/registry-rstack-dev/src/roles.rs index 292c02571f..244c4a2859 100644 --- a/crates/registry-rstack-dev/src/roles.rs +++ b/crates/registry-rstack-dev/src/roles.rs @@ -168,6 +168,7 @@ pub(super) fn resolve( issuer, external_jwks_uri, external_breg, + external_scheduling, products, person_audience, people, @@ -229,6 +230,10 @@ pub(super) fn resolve( .values() .map(|person| person.client.clone()) .collect(), + bindings + .coordinator_review_producer + .as_ref() + .map(|binding| binding.completion_destination.as_str()), )? }; if let Some(service) = &service_roles { @@ -257,6 +262,7 @@ pub(super) fn resolve( issuer, external_jwks_uri, external_breg, + external_scheduling, products, person_audience, people: resolved, diff --git a/crates/registry-rstack-dev/src/sinks.rs b/crates/registry-rstack-dev/src/sinks.rs index 9a3765c8cd..cdebee7091 100644 --- a/crates/registry-rstack-dev/src/sinks.rs +++ b/crates/registry-rstack-dev/src/sinks.rs @@ -20,14 +20,18 @@ use axum::{ routing::{get, post}, Json, Router, }; -use registry_platform_crypto::mac::{constant_time_eq, hmac_sha256}; +use registry_platform_crypto::{ + delivery_signature::DeliveryKeys, + mac::{constant_time_eq, hmac_sha256}, +}; +use registry_platform_hooks::receiver::{verify_hook_delivery, DeliveryFreshness, HookDelivery}; use serde_json::{json, Value}; use std::{ - collections::{BTreeSet, HashMap, VecDeque}, + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, net::{Ipv4Addr, TcpListener}, sync::{mpsc, Arc, Mutex}, thread, - time::Duration, + time::{Duration, SystemTime}, }; use zeroize::Zeroizing; @@ -117,6 +121,18 @@ impl GatewayServer { Self::start_router(router, "rstack-dev-hook-sink") } + pub(super) fn start_signed_hooks(keys: BTreeMap) -> Result { + let router = Router::new() + .route("/events/{destination}", post(receive_signed_hook)) + .route("/received", get(list_signed_hooks)) + .layer(DefaultBodyLimit::max(HOOK_BODY_LIMIT)) + .with_state(Arc::new(SignedHooks { + keys, + deliveries: Mutex::new(VecDeque::new()), + })); + Self::start_router(router, "rstack-dev-signed-hook-sink") + } + fn start_router(router: Router, name: &str) -> Result { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) .context("cannot reserve a loopback port for the HTTP sink")?; @@ -195,11 +211,63 @@ impl GatewayServer { type HookDeliveries = Arc>>; +struct SignedHooks { + keys: BTreeMap, + deliveries: Mutex>, +} + +async fn receive_signed_hook( + State(sink): State>, + Path(destination): Path, + headers: HeaderMap, + body: Bytes, +) -> StatusCode { + let Some(keys) = sink.keys.get(&destination) else { + return StatusCode::NOT_FOUND; + }; + if [ + "authorization", + "registry-source-authorization", + "proxy-authorization", + "cookie", + ] + .iter() + .any(|name| headers.contains_key(*name)) + || verify_hook_delivery( + HookDelivery { + headers: headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_bytes())), + body: &body, + keys, + }, + DeliveryFreshness::default_at(SystemTime::now()), + ) + .is_err() + { + return StatusCode::FORBIDDEN; + } + record_hook(&sink.deliveries, headers, body); + StatusCode::NO_CONTENT +} + +async fn list_signed_hooks(State(sink): State>) -> Json { + Json(json!(*sink + .deliveries + .lock() + .expect("signed hook sink lock"))) +} + async fn receive_hook( State(deliveries): State, headers: HeaderMap, body: Bytes, ) -> StatusCode { + record_hook(&deliveries, headers, body); + StatusCode::NO_CONTENT +} + +fn record_hook(deliveries: &Mutex>, headers: HeaderMap, body: Bytes) { use base64::{engine::general_purpose::STANDARD, Engine as _}; let headers: Vec<_> = headers @@ -223,7 +291,6 @@ async fn receive_hook( |text| json!(text), ), })); - StatusCode::NO_CONTENT } async fn list_hooks(State(deliveries): State) -> Json { @@ -524,6 +591,54 @@ mod tests { .contains(&json!({"name": "x-delivery-number", "value": "1000"}))); } + #[test] + fn signed_hook_capture_checks_destination_signature_and_headers() { + use registry_platform_crypto::delivery_signature::{sign, DeliveryKey, DeliveryKeys}; + use std::{collections::BTreeMap, time::SystemTime}; + + const ID: &str = "00000000-0000-4000-8000-000000000001"; + const BODY: &str = r#"{"causation":{"hop":0,"root":"00000000-0000-4000-8000-000000000001"},"data":{},"dataschema":"urn:example:schema","id":"00000000-0000-4000-8000-000000000001","source":"urn:example:source","subject":{"recordReference":"example/case/42","recordRevision":3},"time":"2026-08-30T00:00:00Z","type":"case-created"}"#; + let keys = |byte| DeliveryKeys::new(DeliveryKey::new(&[byte; 32]).unwrap(), None).unwrap(); + let sink = GatewayServer::start_signed_hooks(BTreeMap::from([ + ("expected".to_owned(), keys(31)), + ("other".to_owned(), keys(32)), + ])) + .unwrap(); + let timestamp = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_secs(); + let signature = sign(&keys(31), ID, timestamp, BODY.as_bytes()).unwrap(); + + for (destination, credential, expected) in [ + ("other", false, 403), + ("expected", true, 403), + ("missing", false, 404), + ("expected", false, 204), + ] { + let (status, _) = call(|client| { + let request = client + .post(format!("{}/events/{destination}", sink.origin)) + .header("content-type", "application/json") + .header("webhook-id", ID) + .header("webhook-timestamp", timestamp.to_string()) + .header("webhook-signature", &signature) + .body(BODY); + if credential { + request.bearer_auth("synthetic-canary") + } else { + request + } + }); + assert_eq!(status, expected, "{destination}"); + } + let (status, received) = call(|client| client.get(format!("{}/received", sink.origin))); + assert_eq!(status, 200); + assert_eq!(received.as_array().unwrap().len(), 1); + assert_eq!(received[0]["body"], BODY); + assert!(!received.to_string().contains("synthetic-canary")); + } + #[test] fn dropping_the_gateway_stops_its_listener() { let gateway = gateway("http://127.0.0.1:9"); diff --git a/crates/registry-rstack-dev/tests/dev_schema.rs b/crates/registry-rstack-dev/tests/dev_schema.rs index 0be4e1bb61..b51e06b193 100644 --- a/crates/registry-rstack-dev/tests/dev_schema.rs +++ b/crates/registry-rstack-dev/tests/dev_schema.rs @@ -113,42 +113,55 @@ fn the_plan_schema_names_the_rstack_dev_format() { } #[test] -fn the_dev_schema_accepts_either_native_products_or_service_audiences() { +fn the_dev_schema_takes_the_service_inventory_and_requires_audiences() { let documents = documents().expect("the development schemas generate"); let schema = compile(&documents["dev.v1alpha1.schema.json"]); - let native = example(EXAMPLES[0].1); - assert!(schema.is_valid(&native)); + let plan = example(EXAMPLES[0].1); + assert!(schema.is_valid(&plan)); - let mut composed = native; - let products = composed + let mut without_audiences = plan.clone(); + without_audiences .as_object_mut() .expect("the development example is a mapping") - .remove("products") - .expect("the native development example declares its products"); - assert!(!schema.is_valid(&composed)); + .remove("audiences"); + assert!( + !schema.is_valid(&without_audiences), + "audiences are required" + ); - let audiences = json!({"licences": "urn:example:licences", "casework": "urn:example:casework"}); - composed["audiences"] = audiences.clone(); + let mut service_owned = plan.clone(); + service_owned + .as_object_mut() + .expect("the development example is a mapping") + .remove("products"); assert!( - schema.is_valid(&composed), - "the runner accepts service audiences" + schema.is_valid(&service_owned), + "a sibling service.yaml may own the inventory" ); + for products in [ + json!([{"product": "breg", "project": "registry", "audience": "urn:example:licences"}]), + json!({"unknown": {"path": "registry"}}), + json!({"casework": {"projects": {"casework": {"path": "casework"}}}}), + ] { + let mut changed = plan.clone(); + changed["products"] = products; + assert!(!schema.is_valid(&changed), "{changed}"); + } + + let audiences = plan["audiences"].clone(); + let mut changed = plan; for invalid in [ json!({}), json!({"licences.branch": "urn:example:licences"}), json!({"licences": ""}), json!({"licences": null}), ] { - composed["audiences"] = invalid; - assert!(!schema.is_valid(&composed), "{composed}"); + changed["audiences"] = invalid; + assert!(!schema.is_valid(&changed), "{changed}"); } - composed["audiences"] = audiences; - composed["products"] = products; - assert!( - !schema.is_valid(&composed), - "the two product sources are exclusive" - ); + changed["audiences"] = audiences; + assert!(schema.is_valid(&changed)); } #[test] @@ -417,12 +430,10 @@ fn the_preview_examples_satisfy_the_composed_dev_and_service_schemas() { settings["issuer"] = json!("https://example.invalid"); assert!(!dev.is_valid(&settings), "a preview uses the run issuer"); settings["issuer"] = json!("run"); - settings.as_object_mut().unwrap().remove("audiences"); - settings["products"] = - json!([{"product":"breg", "project":"project", "audience":"urn:test:preview"}]); + settings["products"] = json!({"breg": {"projects": {"businesses": {"path": "project"}}}}); assert!( !dev.is_valid(&settings), - "a preview needs a composed service" + "a preview takes its products from service.yaml" ); } } diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index da79b8d4f5..9a2d48a022 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -260,12 +260,25 @@ struct ClientGenerate { #[derive(Subcommand)] enum DevCommand { - /// Validate a development plan without starting services. - #[command(after_help = "Example:\n rstack dev check ./my-registry-project")] + /// Validate a development plan or the structure of a saved owner report without starting services. + #[command( + after_help = "Examples:\n rstack dev check ./my-registry-project\n rstack dev check --owner-report ./report.json --owner-report-format casework-report\n rstack dev check --owner-report ./identity-facts-report.json --owner-report-format breg-identity-facts-report" + )] Check { /// Project directory containing dev.yaml and, when it declares audiences, service.yaml. - #[arg(value_name = "PROJECT")] - project: PathBuf, + #[arg(value_name = "PROJECT", required_unless_present = "owner_report")] + project: Option, + /// Saved JSON report to check structurally. + #[arg( + long, + value_name = "FILE", + conflicts_with = "project", + requires = "owner_report_format" + )] + owner_report: Option, + /// Exact saved document format. + #[arg(long, requires = "owner_report", conflicts_with = "project", value_parser = ["casework-report", "breg-identity-facts-report"])] + owner_report_format: Option, /// Refuse an unaccepted warning. /// Development posture listings do not count. #[arg(long)] @@ -283,7 +296,9 @@ enum DevCommand { /// Root of an already-built local application when dev.yaml declares one. #[arg(long, value_name = "DIRECTORY")] application_root: Option, - /// PostgreSQL administrator URL (verified TLS, or loopback with sslmode=disable). + /// PostgreSQL administrator URL. Defaults to verified TLS. For development, select + /// loopback plaintext with sslmode=disable or private network plaintext with + /// transport=private-network-plaintext. /// Defaults to RSTACK_DEV_DATABASE_URL; without either, the run starts its own /// PostgreSQL server in Docker. #[arg(long, value_name = "URL")] @@ -340,9 +355,9 @@ enum DevCommand { /// Remove the project's managed PostgreSQL volume and state after stopping. #[arg(long, conflicts_with = "recover")] clean: bool, - /// PostgreSQL administrator URL for --recover (verified TLS, or loopback with - /// sslmode=disable). Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own - /// server needs none. + /// The same PostgreSQL administrator URL used at start, including its transport + /// choice. Defaults to RSTACK_DEV_DATABASE_URL; a run that started its own server + /// needs none. #[arg(long, value_name = "URL", requires = "recover")] database_url: Option, }, @@ -1979,10 +1994,11 @@ impl DevNeeds { } } -/// The hosting products the project's dev.yaml lists under -/// `/products/*/product`, in hosting order. A missing, unreadable, oversized -/// or unparsable plan, or one without a products list, lists none: the first -/// available host then reports the real plan error, with the positioned +/// The hosting products the project's inventory names, in hosting order: the +/// product kinds under dev.yaml `products`, or else those of the sibling +/// service.yaml when dev.yaml only gives `audiences`. A missing, unreadable, +/// oversized or unparsable plan, or one without an inventory, lists none: the +/// first available host then reports the real plan error, with the positioned /// diagnostics every product gives for a malformed configuration file. fn plan_dev_products(project: &std::path::Path) -> Vec<&'static DevHost> { use registry_platform_yaml::{NodeValue, Reader, MAXIMUM_DOCUMENT_BYTES}; @@ -1998,30 +2014,25 @@ fn plan_dev_products(project: &std::path::Path) -> Vec<&'static DevHost> { let Ok(Some(root)) = Reader::new(file.display().to_string()).scan(&bytes) else { return Vec::new(); }; - if root.pointer("/audiences").is_some() { - let Ok(kinds) = service_plan::development_product_kinds(project) else { - return Vec::new(); - }; - return DEV_HOSTS + match root.pointer("/products").map(|node| &node.value) { + Some(NodeValue::Mapping(_)) => DEV_HOSTS .iter() - .filter(|host| kinds.contains(&host.component)) - .collect(); - } - let Some(NodeValue::Sequence(entries)) = root.pointer("/products").map(|node| &node.value) - else { - return Vec::new(); - }; - DEV_HOSTS - .iter() - .filter(|host| { - entries.iter().any(|entry| { - matches!( - entry.pointer("/product").map(|node| &node.value), - Some(NodeValue::String(text)) if text.text == host.component - ) + .filter(|host| { + root.pointer(&format!("/products/{}", host.component)) + .is_some() }) - }) - .collect() + .collect(), + None if root.pointer("/audiences").is_some() => { + let Ok(kinds) = service_plan::development_product_kinds(project) else { + return Vec::new(); + }; + DEV_HOSTS + .iter() + .filter(|host| kinds.contains(&host.component)) + .collect() + } + _ => Vec::new(), + } } /// The refusal when no host is available for an action that any host serves. @@ -2079,7 +2090,11 @@ fn dev_help(format: ReportFormat) -> Result<(), CliFailure> { fn admit_dev(action: &DevCommand, format: ReportFormat) -> Result<(), CliFailure> { if !matches!( action, - DevCommand::Check { .. } | DevCommand::Start { .. } | DevCommand::Issuer { .. } + DevCommand::Check { + owner_report: None, + .. + } | DevCommand::Start { .. } + | DevCommand::Issuer { .. } ) { return Ok(()); } @@ -2146,17 +2161,36 @@ fn dispatch_dev(cli: &Cli, action: &DevCommand, format: ReportFormat) -> Result< let (name, mut options, target, database_url, needs) = match action { DevCommand::Check { project, + owner_report, + owner_report_format, deny_warnings, - } => ( - "check", - deny_warnings + } => { + let mut options = deny_warnings .then(|| OsString::from("--deny-warnings")) .into_iter() - .collect::>(), - project.as_os_str(), - None, - DevNeeds::check(project), - ), + .collect::>(); + if let (Some(file), Some(format)) = (owner_report, owner_report_format) { + options.push(option("owner-report-format", format.as_ref())); + ( + "check", + options, + file.as_os_str(), + None, + DevNeeds::any_host(), + ) + } else { + let project = project + .as_ref() + .expect("clap requires a project or owner report"); + ( + "check", + options, + project.as_os_str(), + None, + DevNeeds::check(project), + ) + } + } DevCommand::Start { project, application_root, @@ -2554,6 +2588,55 @@ fn set_selected_generation_environment( mod tests { use super::*; + #[test] + fn dev_check_owner_report_requires_an_explicit_exclusive_format() { + let parse = |args: &[&str]| { + Cli::try_parse_from( + ["rstack", "dev", "check"] + .into_iter() + .chain(args.iter().copied()), + ) + }; + assert!(parse(&["./project", "--deny-warnings"]).is_ok()); + assert!(parse(&[ + "--owner-report", + "./report.json", + "--owner-report-format", + "casework-report", + "--deny-warnings", + ]) + .is_ok()); + assert!(parse(&[ + "--owner-report", + "./report.json", + "--owner-report-format", + "breg-identity-facts-report", + "--deny-warnings", + ]) + .is_ok()); + for args in [ + &[][..], + &["--owner-report", "./report.json"], + &["--owner-report-format", "casework-report"], + &["./project", "--owner-report-format", "casework-report"], + &[ + "--owner-report", + "./report.json", + "--owner-report-format", + "guess", + ], + &[ + "./project", + "--owner-report", + "./report.json", + "--owner-report-format", + "casework-report", + ], + ] { + assert!(parse(args).is_err(), "{args:?}"); + } + } + #[test] fn selected_generation_projects_optional_service_binaries() { let generation = tempfile::tempdir().unwrap(); diff --git a/crates/registry-rstack/src/model.rs b/crates/registry-rstack/src/model.rs index 7192f6debe..1f8f7df973 100644 --- a/crates/registry-rstack/src/model.rs +++ b/crates/registry-rstack/src/model.rs @@ -11,7 +11,7 @@ const RELEASE_SCHEMAS: [&str; 2] = [ const PLATFORMS: [&str; 3] = ["linux-amd64", "linux-arm64", "macos-arm64"]; // Binaries published as standalone release assets that rstack never installs. // Mirrors DISTRIBUTION_ONLY_BINARIES in release/scripts/rstack_components.py. -const DISTRIBUTION_ONLY_BINARIES: [&str; 1] = ["registry-language-server"]; +const DISTRIBUTION_ONLY_BINARIES: [&str; 2] = ["registry-language-server", "registry-session"]; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] diff --git a/crates/registry-rstack/tests/dev.rs b/crates/registry-rstack/tests/dev.rs index 5a5fae55f6..2126544891 100644 --- a/crates/registry-rstack/tests/dev.rs +++ b/crates/registry-rstack/tests/dev.rs @@ -619,15 +619,23 @@ fn root_and_dev_help_need_no_installation_or_binary_overrides() { fn write_plan(project: &Path, products: &[&str]) { let entries: Vec = products .iter() - .map(|product| { - format!(" - {{product: {product}, project: {product}, audience: \"urn:example:{product}\"}}\n") + .map(|product| match *product { + "breg" | "coordinator" | "evidence" => { + format!(" {product}: {{projects: {{{product}: {{path: {product}}}}}}}\n") + } + _ => format!(" {product}: {{path: {product}}}\n"), }) .collect(); + let audiences: Vec = products + .iter() + .map(|product| format!(" {product}: \"urn:example:{product}\"\n")) + .collect(); fs::write( project.join("dev.yaml"), format!( - "issuer: https://issuer.example\nproducts:\n{}", - entries.concat() + "issuer: https://issuer.example\nproducts:\n{}audiences:\n{}", + entries.concat(), + audiences.concat() ), ) .unwrap(); @@ -1086,11 +1094,11 @@ fn missing_breg_names_the_install_command_before_the_overrides() { } #[test] -fn casework_text_outside_the_products_list_does_not_require_casework() { +fn casework_text_outside_the_inventory_does_not_require_casework() { let tools = SourceTools::new(); fs::write( tools.project.join("dev.yaml"), - "# product: casework\nissuer: https://issuer.example\nproducts:\n - {product: breg, project: breg, audience: \"urn:example:breg\"}\njourneyFile: dev-journeys.yaml\nnotes:\n - name: \"product: casework\"\n", + "# casework: {path: casework}\nissuer: https://issuer.example\nproducts:\n breg: {projects: {breg: {path: breg}}}\naudiences:\n breg: \"urn:example:breg\"\njourneyFile: dev-journeys.yaml\nnotes:\n casework: {path: casework}\n", ) .unwrap(); let output = tools @@ -1114,7 +1122,7 @@ fn unreadable_plan_is_reported_by_the_first_available_host() { for plan in [ Some("products: [\n"), Some("issuer: https://issuer.example\n"), - Some("products:\n - {product: unrecognised, project: c, audience: c}\n"), + Some("products:\n unrecognised: {path: c}\naudiences: {unrecognised: c}\n"), None, ] { match plan { diff --git a/crates/registry-rstack/tests/dev_run.rs b/crates/registry-rstack/tests/dev_run.rs index ad381c9433..0cf07b6c62 100644 --- a/crates/registry-rstack/tests/dev_run.rs +++ b/crates/registry-rstack/tests/dev_run.rs @@ -182,7 +182,7 @@ fn launcher_selects_scheduling_for_a_scheduling_only_plan() { fs::set_permissions(&probe, fs::Permissions::from_mode(0o700)).unwrap(); fs::write( scratch.path().join("dev.yaml"), - "products: [{product: scheduling}]\n", + "products: {scheduling: {path: .}}\naudiences: {scheduling: urn:example:scheduling}\n", ) .unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_rstack")) @@ -524,7 +524,7 @@ fn project(root: &std::path::Path, extra: &str) { apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {{product: breg, project: ., audience: registry}}\n\ +products:\n breg: {{projects: {{breg: {{path: .}}}}}}\naudiences:\n breg: registry\n\ people:\n operator:\n subject: operator\n client: operator-client\n roles: [operator]\n\ journeyFile: dev-journeys.yaml\n\ {extra}" @@ -1035,7 +1035,7 @@ fn semantic_project(root: &std::path::Path, product: &str, step_extra: &str) { "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {product: breg, project: ., audience: private-audience-marker}\n\ +products:\n breg: {projects: {breg: {path: .}}}\naudiences:\n breg: private-audience-marker\n\ people:\n operator:\n subject: private-subject-marker\n client: private-client-marker\n roles: [operator]\n\ journeyFile: dev-journeys.yaml\n", ) @@ -1267,7 +1267,7 @@ fn casework_reference_project( "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {{product: breg, project: ., audience: \"urn:example:registry\"}}\n - {{product: casework, project: casework, audience: \"urn:example:review\"}}\n\ +products:\n breg: {{projects: {{breg: {{path: .}}}}}}\n casework: {{path: casework}}\naudiences:\n breg: \"urn:example:registry\"\n casework: \"urn:example:review\"\n\ people:\n operator:\n subject: operator\n client: operator-client\n roles: [operator]\n reviewer:\n subject: reviewer\n client: reviewer-client\n roles: [reviewer]\n\ journeyFile: dev-journeys.yaml\n\ {bindings}" @@ -1353,7 +1353,7 @@ fn composed_project(root: &std::path::Path) -> String { fs::write(root.join("service.yaml"), DIRECT_SERVICE).unwrap(); let dev_file = root.join("dev.yaml"); let dev = fs::read_to_string(&dev_file).unwrap().replace( - "products:\n - {product: breg, project: ., audience: registry}\n", + "products:\n breg: {projects: {breg: {path: .}}}\naudiences:\n breg: registry\n", "audiences: {demo: registry}\n", ); fs::write(dev_file, &dev).unwrap(); @@ -1387,7 +1387,7 @@ fn check_assembles_products_from_service_without_writing_a_dev_plan() { fn check_rejects_competing_native_and_composed_product_lists() { let scratch = tempfile::tempdir().unwrap(); let state = scratch.path().join("state"); - project(scratch.path(), "audiences: {demo: registry}\n"); + project(scratch.path(), ""); fs::write(scratch.path().join("service.yaml"), DIRECT_SERVICE).unwrap(); let output = check(scratch.path(), &state, true); @@ -1420,7 +1420,7 @@ fn check_rejects_competing_native_and_composed_product_lists() { "{report}" ); assert!( - message.contains("The service file supplies the development products."), + message.contains("The service file already declares the development products."), "{report}" ); assert!(!state.exists()); @@ -1827,7 +1827,10 @@ fn check_and_start_refuse_a_fixture_symlink_outside_the_breg_project() { fs::write(scratch.path().join("breg/registry.yaml"), "fixture\n").unwrap(); let plan = fs::read_to_string(scratch.path().join("dev.yaml")) .unwrap() - .replace("product: breg, project: .", "product: breg, project: breg"); + .replace( + "breg: {projects: {breg: {path: .}}}", + "breg: {projects: {breg: {path: breg}}}", + ); fs::write(scratch.path().join("dev.yaml"), plan).unwrap(); fs::create_dir(scratch.path().join("breg/tests")).unwrap(); std::os::unix::fs::symlink( @@ -1841,7 +1844,7 @@ fn check_and_start_refuse_a_fixture_symlink_outside_the_breg_project() { assert_eq!(checked.status.code(), Some(1), "{checked:?}"); let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/0/project"); + assert_eq!(diagnostic["path"], "/products/breg/projects/breg/path"); assert_eq!( diagnostic["message"], "The BReg fixture journeys file must be a readable regular file inside the BReg product project." @@ -1858,7 +1861,10 @@ fn check_and_start_refuse_a_fixture_symlink_outside_the_breg_project() { let report: serde_json::Value = serde_json::from_slice(&started.stdout).unwrap(); assert_error_envelope(&report, "domain"); let error = report["error"]["message"].as_str().unwrap(); - assert!(error.contains("/products/0/project"), "{error}"); + assert!( + error.contains("/products/breg/projects/breg/path"), + "{error}" + ); assert!(error.contains("fixture journeys file must be"), "{error}"); assert!(error.contains("without linking it outside"), "{error}"); assert!(!state.exists()); @@ -1949,8 +1955,8 @@ fn check_refuses_a_breg_project_directory_that_resolves_outside_the_project() { let plan = fs::read_to_string(scratch.path().join("dev.yaml")) .unwrap() .replace( - "product: breg, project: .", - "product: breg, project: linked-breg", + "breg: {projects: {breg: {path: .}}}", + "breg: {projects: {breg: {path: linked-breg}}}", ); fs::write(scratch.path().join("dev.yaml"), plan).unwrap(); @@ -1959,10 +1965,10 @@ fn check_refuses_a_breg_project_directory_that_resolves_outside_the_project() { assert_eq!(result.status.code(), Some(1), "{result:?}"); let report: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/0/project"); + assert_eq!(diagnostic["path"], "/products/breg/projects/breg/path"); assert_eq!( diagnostic["message"], - "The product project resolves outside the development project." + "This path must resolve to a directory inside the workspace." ); assert!(!state.exists()); } @@ -2036,6 +2042,36 @@ fn old_kind_is_refused_with_the_new_name() { assert!(!state.exists()); } +#[test] +fn check_refuses_the_retired_product_list_in_dev_yaml() { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + project(scratch.path(), ""); + let dev = scratch.path().join("dev.yaml"); + let mapping = "products:\n breg: {projects: {breg: {path: .}}}\n"; + let text = fs::read_to_string(&dev).unwrap(); + assert!(text.contains(mapping), "{text}"); + fs::write( + &dev, + text.replace( + mapping, + "products:\n - {product: breg, project: ., audience: registry}\n", + ), + ) + .unwrap(); + + let result = check(scratch.path(), &state, true); + + assert_eq!(result.status.code(), Some(1), "{result:?}"); + let report: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "rstack.dev.products-list", "{report}"); + assert_eq!(diagnostic["path"], "/products", "{report}"); + assert_eq!(diagnostic["source"]["file"], utf8(&dev), "{report}"); + assert!(diagnostic["source"]["line"].is_u64(), "{report}"); + assert!(!state.exists()); +} + #[test] fn check_renders_both_locations_of_a_duplicate_key() { let scratch = tempfile::tempdir().unwrap(); @@ -2048,7 +2084,7 @@ fn check_renders_both_locations_of_a_duplicate_key() { assert!(result.stdout.is_empty()); let human = String::from_utf8(result.stderr).unwrap(); assert!(human.starts_with("error[yaml.duplicate-key] "), "{human}"); - assert!(human.contains("dev.yaml:13:1 /issuer"), "{human}"); + assert!(human.contains("dev.yaml:15:1 /issuer"), "{human}"); assert!(human.contains("dev.yaml:4:1 /issuer"), "{human}"); assert!( human.contains("next: Keep one definition of the key."), @@ -2233,7 +2269,7 @@ fn start_rejects_a_role_with_no_breg_profile_facts_before_allocating_state() { "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\n\ kind: RStackDev\n\ issuer: https://issuer.example.invalid\n\ -products:\n - {product: breg, project: ., audience: registry}\n\ +products:\n breg: {projects: {breg: {path: .}}}\naudiences:\n breg: registry\n\ people:\n editor:\n subject: editor\n client: editor-client\n roles: [editor]\n claims: {breg: {jurisdiction: zone-a}}\n unused:\n subject: unused\n client: unused-client\n roles: [unused]\n\ journeyFile: dev-journeys.yaml\n", ) @@ -2411,9 +2447,9 @@ fn check_refuses_binding_configuration_the_products_would_refuse_at_the_plan_fie ), ( "audience", - "audience: \"urn:example:registry\"", - "audience: registry", - "/products/0/audience", + "breg: \"urn:example:registry\"", + "breg: registry", + "/audiences/breg", "Casework refuses", ), ] { @@ -2448,6 +2484,146 @@ fn check_refuses_binding_configuration_the_products_would_refuse_at_the_plan_fie } } +/// `rstack dev check` over the permit-review preview, with the real BReg, +/// Casework and Coordinator tools, before any product starts. +fn check_permit_review(root: &std::path::Path, state: &std::path::Path) -> std::process::Output { + rstack_dev(state, true) + .args(["check", utf8(root), "--deny-warnings"]) + .env("RSTACK_CASEWORKCTL_BIN", host("caseworkctl")) + .env("RSTACK_COORDINATORCTL_BIN", host("coordinatorctl")) + .env("RSTACK_COORDINATOR_BIN", system_binary("false")) + .output() + .unwrap() +} + +#[test] +fn permit_review_check_refuses_each_widened_coordinator_binding_at_its_dev_yaml_field() { + let source = example_project("platform/examples/service-previews/permit-review"); + let copy = |root: &std::path::Path| { + fs::create_dir_all(root).unwrap(); + for entry in fs::read_dir(&source).unwrap() { + let entry = entry.unwrap(); + if entry.file_name() == "node_modules" { + continue; + } + let target = root.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).unwrap(); + } + } + }; + + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + let root = scratch.path().join("permit-review"); + copy(&root); + let checked = check_permit_review(&root, &state); + assert!( + checked.status.success(), + "{} {}", + String::from_utf8_lossy(&checked.stdout), + String::from_utf8_lossy(&checked.stderr) + ); + assert!(!state.exists()); + + let unbound_review = concat!( + " review-copy:\n", + " type: casework-review-producer\n", + " baseUrl: https://casework.example.org\n", + " profile: coordinator-producer\n", + " producer: coordinator\n", + " authorization:\n", + " tokenEndpoint: https://identity.permit-review.example.test/oauth/token\n", + " clientAssertionAudience: https://identity.permit-review.example.test\n", + " clientId: coordinator-producer\n", + " signingKeyRef: secret:file/review-client-key\n", + " resource: urn:example:permit-review\n", + " scopes: [casework:permit:review]\n", + " completion:\n", + " recipientBinding: coordinator-copy\n", + " hmacSha256KeyRef: secret:file/review-completion-key\n", + " permits:\n", + ); + for (case, edits, path, message) in [ + ( + // Casework refuses first: its producer names a completion + // destination that only the binding configures. + "producer binding removed", + vec![("dev.yaml", " coordinatorReviewProducer:\n connection: review\n producer: coordinator\n identity: coordinator-producer\n completionDestination: coordinator-wake\n runIssuerBinding:\n producer:\n expectedIssuer: https://identity.permit-review.example.test\n expectedProfile: coordinator-producer\n expectedSubject: coordinator-producer\n", "")], + "/products/casework/path", + "The owning casework tool refused this project's identity facts (casework.runtime.unconfigured-review-completion-destination).", + ), + ( + "producer binding and completion removed", + vec![ + ("dev.yaml", " coordinatorReviewProducer:\n connection: review\n producer: coordinator\n identity: coordinator-producer\n completionDestination: coordinator-wake\n runIssuerBinding:\n producer:\n expectedIssuer: https://identity.permit-review.example.test\n expectedProfile: coordinator-producer\n expectedSubject: coordinator-producer\n", ""), + ( + "casework/casework.yaml", + " completion:\n destinationId: coordinator-wake\n recipientBinding: coordinator-v1\n", + "", + ), + ], + "/bindings", + "A Coordinator casework-review-producer connection needs bindings.coordinatorReviewProducer before Casework trusts it in this run.", + ), + ( + "second producer connection", + vec![("coordinator/runtime.yaml", " permits:\n", unbound_review)], + "/bindings/coordinatorReviewProducer/connection", + "Another Coordinator casework-review-producer connection has no binding, so Casework would not trust it in this run.", + ), + ( + // The facts runtime configures the binding's destination, so + // Casework refuses the producer's unconfigured one first. + "completion destination", + vec![("dev.yaml", "completionDestination: coordinator-wake", "completionDestination: another-wake")], + "/products/casework/path", + "The owning casework tool refused this project's identity facts (casework.runtime.unconfigured-review-completion-destination).", + ), + ( + "BReg profile", + vec![("coordinator/runtime.yaml", " profile: permit-coordinator\n", " profile: permit-reader\n")], + "/bindings/coordinatorBregClient/connection", + "The connection's profile is not the identity's BReg grant profile.", + ), + ( + "BReg connection", + vec![("dev.yaml", " connection: permits\n", " connection: review\n")], + "/bindings/coordinatorBregClient/connection", + "The Coordinator runtime.yaml has no breg connection with this name.", + ), + ( + "BReg identity shared with a preview actor", + vec![("dev.yaml", " connection: permits\n identity: coordinator-service\n", " connection: permits\n identity: applicant\n")], + "/bindings/coordinatorBregClient/identity", + "The Coordinator's BReg identity must be a dedicated machine person that no other binding or preview actor uses.", + ), + ] { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + let root = scratch.path().join("permit-review"); + copy(&root); + for (file, from, to) in edits { + let edited = root.join(file); + let text = fs::read_to_string(&edited).unwrap(); + assert_eq!(text.matches(from).count(), 1, "{case}: {file}"); + fs::write(&edited, text.replace(from, to)).unwrap(); + } + + let checked = check_permit_review(&root, &state); + + assert_eq!(checked.status.code(), Some(1), "{case}: {checked:?}"); + let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); + assert_eq!(report["status"], "domain-refusal", "{case}: {report}"); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["path"], path, "{case}: {diagnostic}"); + assert_eq!(diagnostic["message"], message, "{case}: {diagnostic}"); + assert!(!state.exists(), "{case}"); + } +} + #[test] fn check_refuses_a_context_provider_binding_with_the_rule_caseworkctl_check_names() { let scratch = tempfile::tempdir().unwrap(); @@ -2461,7 +2637,7 @@ fn check_refuses_a_context_provider_binding_with_the_rule_caseworkctl_check_name let text = fs::read_to_string(&dev).unwrap(); fs::write( &dev, - text.replace("audience: \"urn:example:registry\"", "audience: registry"), + text.replace("breg: \"urn:example:registry\"", "breg: registry"), ) .unwrap(); @@ -2471,7 +2647,7 @@ fn check_refuses_a_context_provider_binding_with_the_rule_caseworkctl_check_name let report: serde_json::Value = serde_json::from_slice(&checked.stdout).unwrap(); assert_eq!(report["status"], "domain-refusal"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/0/audience"); + assert_eq!(diagnostic["path"], "/audiences/breg"); assert_eq!( diagnostic["message"], "Casework refuses the binding configuration the run writes from this value: \ @@ -2510,7 +2686,7 @@ fragment or userinfo." let report: serde_json::Value = serde_json::from_slice(&unavailable.stdout).unwrap(); assert_eq!(report["status"], "operational-failure"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!( diagnostic["message"], "The selected `caseworkctl` helper could not check the Casework configuration the run writes: caseworkctl check did not report a result for the binding." @@ -2560,8 +2736,14 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let report: serde_json::Value = serde_json::from_slice(&unavailable.stdout).unwrap(); assert_eq!(report["status"], "operational-failure"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!(diagnostic["code"], "rstack.dev.check-unavailable"); + assert_eq!( + diagnostic["source"]["file"], + utf8(&scratch.path().join("dev.yaml")), + "{report}" + ); + assert!(diagnostic["source"]["line"].is_u64(), "{report}"); assert!( diagnostic["message"] .as_str() @@ -2598,8 +2780,14 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let report: serde_json::Value = serde_json::from_slice(&helper_failure.stdout).unwrap(); assert_eq!(report["status"], "operational-failure"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!(diagnostic["code"], "rstack.dev.check-unavailable"); + assert_eq!( + diagnostic["source"]["file"], + utf8(&scratch.path().join("dev.yaml")), + "{report}" + ); + assert!(diagnostic["source"]["line"].is_u64(), "{report}"); assert!( diagnostic["message"] .as_str() @@ -2630,7 +2818,7 @@ fn check_distinguishes_an_unavailable_casework_helper_from_an_invalid_project() let report: serde_json::Value = serde_json::from_slice(&invalid.stdout).unwrap(); assert_eq!(report["status"], "domain-refusal"); let diagnostic = &report["diagnostics"][0]; - assert_eq!(diagnostic["path"], "/products/1/project"); + assert_eq!(diagnostic["path"], "/products/casework/path"); assert_eq!( diagnostic["message"], "The owning casework tool refused this project's identity facts (casework.project.invalid)." @@ -2648,7 +2836,7 @@ fn a_malformed_plan_names_its_field_before_allocating_run_state() { let state = scratch.path().join("state"); fs::write( scratch.path().join("dev.yaml"), - "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\nkind: RStackDev\nissuer: https://example.test\nproducts: [{product: unrecognised, project: registry, audience: test}]\npeople: {}\njourneyFile: dev-journeys.yaml\n", + "apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1\nkind: RStackDev\nissuer: https://example.test\nproducts: {unrecognised: {path: registry}}\naudiences: {unrecognised: test}\npeople: {}\njourneyFile: dev-journeys.yaml\n", ) .unwrap(); // The plan lists no hosting product, so the first available host reports @@ -2662,7 +2850,7 @@ fn a_malformed_plan_names_its_field_before_allocating_run_state() { report["error"]["message"] .as_str() .unwrap() - .contains("/products/0/product"), + .contains("/products/unrecognised"), "{report}" ); assert!(!state.exists()); @@ -2770,7 +2958,8 @@ fn worker_restores_a_valid_plan_whose_captured_input_exceeds_512_kib() { "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": "https://issuer.example.invalid", - "products": [{"product": "breg", "project": ".", "audience": "registry"}], + "products": {"breg": {"projects": {"breg": {"path": "."}}}}, + "audiences": {"breg": "registry"}, "people": {"operator": { "subject": "operator", "client": "operator-client", "roles": ["operator"] @@ -3014,7 +3203,9 @@ fn casework_only_project(root: &std::path::Path) { "kind: RStackDev\n", "issuer: https://issuer.example.invalid\n", "products:\n", - " - {product: casework, project: casework, audience: \"urn:example:review\"}\n", + " casework: {path: casework}\n", + "audiences:\n", + " casework: \"urn:example:review\"\n", "people:\n", " staff:\n", " subject: staff\n", @@ -3481,6 +3672,164 @@ fn breg_alone_runs_end_to_end() { ); } +#[test] +#[cfg(target_os = "linux")] +#[ignore = "requires Docker, its pinned receiver image, and built BReg binaries"] +fn breg_attaches_to_an_independent_signed_hook_receiver() { + let scratch = tempfile::tempdir().unwrap(); + let state = scratch.path().join("state"); + let project = scratch.path().join("project"); + copy_tree(&example_project("breg/examples/minimal"), &project); + let fixture = project.join("fixture"); + fs::create_dir(&fixture).unwrap(); + let key = fixture.join("event-hmac"); + use std::io::Write; + fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&key) + .unwrap() + .write_all(b"synthetic attach-test signing material") + .unwrap(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let plan = project.join("dev.yaml"); + let mut text = fs::read_to_string(&plan).unwrap(); + text.push_str(&format!( + "\nexternalBreg:\n hooks:\n contact-sink: {{origin: \"http://127.0.0.1:{port}\", path: /events, keyRef: \"secret:file/event-hmac\"}}\n" + )); + fs::write(plan, text).unwrap(); + let registry = project.join("registry.yaml"); + let text = fs::read_to_string(®istry).unwrap().replacen( + "\nactions:\n", + "\n hooks:\n - id: contact-created\n phase: after\n trigger: created\n projection: [name, jurisdiction]\n handler: {type: url, destinationId: contact-sink}\n\nactions:\n", + 1, + ); + fs::write(registry, text).unwrap(); + let command = |arguments: &[&str]| { + rstack_dev(&state, true) + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .env("RSTACK_BREG_BIN", host("breg")) + .env_remove("REGISTRY_STACK_POSTURE") + .args(arguments) + .output() + .unwrap() + }; + let checked = command(&["check", utf8(&project)]); + assert!( + checked.status.success(), + "check refused the hook attachment: {}", + String::from_utf8_lossy(&checked.stdout) + ); + + let receiver = example_project("platform/journeys/projects/hook-receiver.py"); + let receiver_mount = format!( + "type=bind,source={},target=/receiver.py,readonly", + receiver.display() + ); + let fixture_mount = format!("type=bind,source={},target=/fixture", fixture.display()); + let name = format!( + "v051-hook-{}", + scratch.path().file_name().unwrap().to_string_lossy() + ); + let docker = |args: &[&str]| Command::new("docker").args(args).output().unwrap(); + let image = "mcr.microsoft.com/playwright:v1.60.0-noble@sha256:9bd26ad900bb5e0f4dee75839e957a89ae89c2b7ab1e76050e559790e946b948"; + drop(listener); + let started = docker(&[ + "run", + "--detach", + "--rm", + "--pull=never", + "--network=host", + "--name", + &name, + "--mount", + &receiver_mount, + "--mount", + &fixture_mount, + "--entrypoint", + "python3", + image, + "/receiver.py", + &port.to_string(), + "/events", + "contact-created", + "/fixture/event-hmac", + "/fixture/event.json", + ]); + assert!( + started.status.success(), + "{}", + String::from_utf8_lossy(&started.stderr) + ); + let origin = format!("http://127.0.0.1:{port}"); + let ready = Command::new("curl") + .args([ + "--fail", + "--silent", + "--noproxy", + "*", + "--retry", + "5", + "--retry-connrefused", + "--max-time", + "2", + ]) + .arg(format!("{origin}/ready")) + .output() + .unwrap(); + let run = ready + .status + .success() + .then(|| command(&["start", utf8(&project), "--ttl", "1m"])); + let receipt_path = fixture.join("event.json"); + let receipt = run + .as_ref() + .filter(|output| output.status.success()) + .and_then(|_| { + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline { + if let Some(event) = fs::read(&receipt_path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|event| event["data"]["values"]["name"] == "Example contact") + { + return Some(event); + } + thread::sleep(Duration::from_millis(100)); + } + None + }); + let report = run + .as_ref() + .and_then(|output| serde_json::from_slice::(&output.stdout).ok()); + let stopped = report + .as_ref() + .and_then(|report| report["run_id"].as_str()) + .map(|id| command(&["stop", id, "--clean"])); + let receiver_stopped = docker(&["stop", &name]); + + assert!(receiver_stopped.status.success(), "receiver did not stop"); + assert!( + ready.status.success(), + "the sibling receiver did not become ready" + ); + let started = run.expect("start was attempted"); + assert!( + started.status.success(), + "start refused the hook attachment: {}", + String::from_utf8_lossy(&started.stdout) + ); + let run = report.expect("valid start report"); + assert!(run["bregHookSink"].is_null()); + assert_eq!(run["scenarios"][0]["result"], "passed"); + assert!(stopped.expect("BReg stopped and cleaned").status.success()); + let event = receipt.expect("signed event received"); + assert_eq!(event["type"], "contact-created"); + assert_eq!(event["data"]["values"]["name"], "Example contact"); +} + #[test] #[ignore = "requires RSTACK_DEV_DATABASE_URL, RSTACK_DEV_DATABASE_CA and built caseworkctl and casework binaries"] fn casework_alone_runs_end_to_end() { @@ -4166,6 +4515,38 @@ fn preview_check_is_offline_and_reports_invalid_actor_and_routes() { "{diagnostic}" ); assert!(!state.exists()); + + // A preview takes its products from service.yaml, not from dev.yaml. + let products = "products:\n breg:\n projects:\n demo: {path: .}\n"; + assert!(original.contains(products), "{original}"); + fs::write(&service, original.replace(products, "")).unwrap(); + fs::write( + project.join("dev.yaml"), + format!( + "{}{preview}", + dev.replace( + "audiences: {demo: registry}\n", + &format!("{products}audiences: {{demo: registry}}\n"), + ) + ), + ) + .unwrap(); + let refused = check(project, &state, true); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + let report: serde_json::Value = serde_json::from_slice(&refused.stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["path"], "/products", "{report}"); + assert_eq!( + diagnostic["source"]["file"], + utf8(&project.join("dev.yaml")), + "{report}" + ); + assert_eq!( + diagnostic["message"], + "A browser preview takes its products from the sibling service.yaml." + ); + assert!(!state.exists()); + fs::write(project.join("dev.yaml"), format!("{dev}{preview}")).unwrap(); fs::write(&service, original).unwrap(); let started = dev_json(&state, &["start", utf8(project)]); diff --git a/crates/registry-rstack/tests/release_manifest.rs b/crates/registry-rstack/tests/release_manifest.rs index 574d34ed9c..1f8e96ae8c 100644 --- a/crates/registry-rstack/tests/release_manifest.rs +++ b/crates/registry-rstack/tests/release_manifest.rs @@ -245,6 +245,18 @@ fn distribution_only_language_server_needs_no_component() { .contains_key("language-server")); } +#[test] +fn distribution_only_session_needs_no_component() { + let mut value = stack_v3_document(); + for platform in ["linux-amd64", "linux-arm64", "macos-arm64.tar.gz"] { + push_binary_payload(&mut value, &format!("registry-session-v0.44.0-{platform}")); + } + + let manifest = ReleaseManifest::parse(&serde_json::to_vec(&value).unwrap()) + .expect("the session service is a release asset, not an rstack component"); + assert!(!manifest.components.components.contains_key("session")); +} + #[test] fn unclassified_binary_payload_is_rejected() { for name in [ @@ -253,6 +265,8 @@ fn unclassified_binary_payload_is_rejected() { "registry-language-server-v0.44.0-windows-amd64", "registry-language-server-v0.44.0-macos-arm64", "registry-language-server-extra-v0.44.0-linux-amd64", + "registry-session-v0.44.0-macos-arm64", + "registry-session-v0.44.0-windows-amd64", ] { let mut value = stack_v3_document(); push_binary_payload(&mut value, name); diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index 0f8b2328a2..ce061cf4d2 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -1339,12 +1339,12 @@ impl RuntimeConfig { ) } JwksSource::Static { document_ref } | JwksSource::TestIssuer { document_ref } => { - let document = secrets.resolve(document_ref).map_err(|error| { - RuntimeConfigError::OidcJwksSecret { + let document = secrets + .resolve_public_document(document_ref) + .map_err(|error| RuntimeConfigError::OidcJwksSecret { issuer: id.to_owned(), message: describe_secret_failure(&document_field, document_ref, &error), - } - })?; + })?; let jwks = parse_static_jwks(document.expose_secret()).map_err(|error| { match error { // The operator's document broke a key set rule: say diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index d70eebedb7..ead4b590e5 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -5693,13 +5693,15 @@ fn tls_connector( return Err(StoreError::Configuration); } if let Some(reference) = &config.ca_bundle_ref { - let certificate = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure( - "database.caBundleRef", - reference, - &error, - )) - })?; + let certificate = secrets + .resolve_public_document(reference) + .map_err(|error| { + StoreError::SecretConfiguration(describe_secret_failure( + "database.caBundleRef", + reference, + &error, + )) + })?; let mut roots = rustls::RootCertStore::empty(); use rustls::pki_types::pem::PemObject as _; let mut count = 0usize; diff --git a/crates/registry-schedulingctl/Cargo.toml b/crates/registry-schedulingctl/Cargo.toml index bf39cf0de9..670ef6edbd 100644 --- a/crates/registry-schedulingctl/Cargo.toml +++ b/crates/registry-schedulingctl/Cargo.toml @@ -22,6 +22,8 @@ workspace = true registry-rstack-dev.workspace = true registry-cli-report.workspace = true anyhow.workspace = true +chrono.workspace = true +chrono-tz.workspace = true clap.workspace = true registry-cli-api.workspace = true registry-platform-audit.workspace = true @@ -45,7 +47,6 @@ zeroize.workspace = true # already demand. Asking for it here instead would turn it on for every build # holding both crates, and the runtime's own database suite would then be # compiled and run by shards that have no server to offer it. -chrono.workspace = true registry-platform-provision = { workspace = true, features = ["test-support"] } tokio-postgres.workspace = true diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index bb22fa267f..d45787e680 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -973,7 +973,8 @@ fn write_explicit_setting( ) -> io::Result<()> { writeln!( out, - "Explicit production setting {code} at {pointer}. {summary}." + "{}", + registry_platform_config::explicit_setting_notice(code, pointer, summary) ) } @@ -2676,6 +2677,54 @@ mod tests { assert_eq!(report["status"], "operational-failure"); } + #[test] + fn the_compose_mount_policy_is_listed_by_check_and_recorded_for_startup() { + let (root, project) = initialized("standalone-exact-time"); + let runtime = runtime_config(root.path(), &project); + let text = std::fs::read_to_string(&runtime).unwrap(); + let providers = "secretProviders:\n file:\n"; + assert!(text.contains(providers), "{text}"); + std::fs::write( + &runtime, + text.replacen( + providers, + &format!("{providers} mountPolicy: compose-native\n"), + 1, + ), + ) + .unwrap(); + let (exit, report, _) = run_json(&[ + "check", + project.to_str().unwrap(), + "--runtime-config", + runtime.to_str().unwrap(), + ]); + assert_eq!(exit, ExitCode::SUCCESS, "{report}"); + assert!( + report["explicitProductionSettings"] + .as_array() + .unwrap() + .iter() + .any( + |line| line["code"] == "platform.posture.compose-native-secret-mount" + && line["pointer"] == "/secretProviders/file/mountPolicy" + ), + "{report}" + ); + // Startup logs every setting the loaded posture records. + let config = registry_scheduling::config::RuntimeConfig::load( + &runtime, + registry_scheduling::config::DEFAULT_POSTURE, + ) + .expect("the runtime file loads"); + assert!(config + .posture_report() + .explicit_setting_notices() + .iter() + .any(|notice| notice + .contains("compose-native-secret-mount at /secretProviders/file/mountPolicy"))); + } + /// `check --runtime-config` lists the settings the file states on purpose /// as facts for a reviewer. They never change the verdict. #[test] diff --git a/crates/registry-schedulingctl/src/project.rs b/crates/registry-schedulingctl/src/project.rs index 694cea0228..51aeb41a56 100644 --- a/crates/registry-schedulingctl/src/project.rs +++ b/crates/registry-schedulingctl/src/project.rs @@ -2,11 +2,10 @@ //! Project loading and the offline init, check, test, and explain reports. //! -//! Everything here runs without a network, a database, or a clock: the -//! authored policy, its records, and its fixtures are read from the project -//! directory through the shared reader, checked and replayed through the -//! pure core, and rendered as one JSON report per command. A refused project -//! is the reader's own report, every diagnostic at its position. +//! Init dates a new starter from today's UTC date. The other offline commands +//! read the policy, records, and fixtures through the shared reader and pure +//! core without reading the clock. A refused project is the reader's own +//! report, every diagnostic at its position. use registry_platform_config::DeclaredPosture; use std::collections::BTreeMap; @@ -14,6 +13,7 @@ use std::fs; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; +use chrono::{NaiveDate, Utc}; use registry_platform_config::package::{plan_package, write_package}; use registry_platform_config::{sha256_uri, UNAVAILABLE_CODE}; use registry_platform_yaml::{Decoded, Diagnostic, Report, Source}; @@ -37,6 +37,10 @@ const FIXTURES_DIRECTORY: &str = "fixtures"; const NO_FIXTURES_CODE: &str = "scheduling.fixture.none"; pub(super) fn init(project: &Path, template: &str) -> Result { + init_on(project, template, Utc::now().date_naive()) +} + +fn init_on(project: &Path, template: &str, today: NaiveDate) -> Result { let Some(files) = templates::template_files(template) else { anyhow::bail!( "unknown template {template:?}; available templates: standalone-exact-time, standalone-arrival-window, resource-reservations" @@ -58,7 +62,8 @@ pub(super) fn init(project: &Path, template: &str) -> Result { fs::create_dir(staging.path().join(FIXTURES_DIRECTORY))?; let mut created = Vec::new(); for (relative, contents) in &files { - fs::write(staging.path().join(relative), contents)?; + let contents = templates::date_file(template, relative, contents, today)?; + fs::write(staging.path().join(relative), contents.as_bytes())?; created.push((*relative).to_owned()); } let staging_path = staging.keep(); @@ -856,13 +861,113 @@ fn absolute_lexical(path: &Path) -> std::io::Result { mod tests { use super::*; use registry_scheduling::config::RuntimeConfig; + use registry_scheduling_core::location_open_intervals; + + #[test] + fn fresh_starters_publish_supply_after_the_original_example_dates() { + let root = tempfile::tempdir().unwrap(); + let posture = registry_scheduling::config::DEFAULT_POSTURE; + for day in ["2027-01-01", "2028-02-29", "2037-11-02"] { + let today = day.parse::().unwrap(); + let now = today.and_hms_opt(0, 0, 0).unwrap().and_utc(); + for (template, expected_cases) in [ + ("standalone-exact-time", 8), + ("standalone-arrival-window", 6), + ("resource-reservations", 11), + ] { + let project = root.path().join(day).join(template); + init_on(&project, template, today).unwrap(); + let context = format!("{day} {template}"); + let checked = check(&project, false, posture).unwrap(); + assert_eq!(checked["diagnostics"], json!([]), "{context}"); + let replay = test(&project, posture).unwrap(); + let mut case_count = 0; + for fixture in replay["fixtures"].as_array().unwrap() { + assert_eq!(fixture["status"], "passed", "{context}: {fixture}"); + for case in fixture["cases"].as_array().unwrap() { + assert_eq!(case["status"], "pass", "{context}: {case}"); + case_count += 1; + } + } + assert_eq!(case_count, expected_cases, "{context}"); + + let authored = read_project(&project, true, posture).unwrap(); + let policy = authored.policy.unwrap().value; + let facts = authored.facts.unwrap(); + for offering in &policy.offerings { + let location = facts.location(&offering.location).unwrap(); + let intervals = + location_open_intervals(&policy, &location.id, &location.timezone, &[]) + .unwrap(); + assert!( + intervals.iter().any(|open| open.end > now), + "{context}: {}", + offering.id + ); + if let Some(arrival) = &offering.arrival { + let window = offering.served_windows(&facts.windows).next().unwrap(); + assert!(window.start > now + chrono::TimeDelta::days(1), "{context}"); + assert!( + window.start + < now + chrono::TimeDelta::days(i64::from(arrival.horizon_days)), + "{context}" + ); + } + } + } + } + } + + #[test] + fn init_reproduces_the_committed_examples_on_their_reference_date() { + let root = tempfile::tempdir().unwrap(); + for template in [ + "standalone-exact-time", + "standalone-arrival-window", + "resource-reservations", + ] { + let project = root.path().join(template); + init_on(&project, template, templates::EXAMPLE_DATE).unwrap(); + for (relative, bytes) in templates::template_files(template).unwrap() { + assert_eq!( + fs::read(project.join(relative)).unwrap(), + bytes.as_bytes(), + "{template}/{relative}" + ); + } + } + } + + #[test] + fn init_does_not_publish_a_starter_for_a_fold_missing_from_the_timezone_data() { + let root = tempfile::tempdir().unwrap(); + let before_fold = "2026-10-31".parse().unwrap(); + // In 2006 the fold had already happened in October. This also tests + // the refusal without depending on where the installed data ends. + let before_regular_sunday = "2006-10-31".parse().unwrap(); + for template in ["standalone-exact-time", "resource-reservations"] { + let supported = root.path().join("supported").join(template); + init_on(&supported, template, before_fold).unwrap(); + + let refused = root.path().join("refused").join(template); + let error = init_on(&refused, template, before_regular_sunday).unwrap_err(); + assert!(error + .to_string() + .contains("America/New_York fold on 2006-11-05")); + assert!(!refused.exists()); + } + + let arrival = root.path().join("standalone-arrival-window"); + init_on(&arrival, "standalone-arrival-window", before_regular_sunday).unwrap(); + assert!(arrival.is_dir()); + } /// A tempdir holding one freshly initialized template project, plus the /// paths the tempdir keeps alive. fn initialized(template: &str) -> (tempfile::TempDir, PathBuf) { let root = tempfile::tempdir().unwrap(); let project = root.path().join("project"); - init(&project, template).unwrap(); + init_on(&project, template, templates::EXAMPLE_DATE).unwrap(); (root, project) } diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs index a4d30ea8db..7190cef0ab 100644 --- a/crates/registry-schedulingctl/src/provision.rs +++ b/crates/registry-schedulingctl/src/provision.rs @@ -6,7 +6,7 @@ use std::path::Path; -use registry_platform_config::describe_secret_failure; +use registry_platform_config::{describe_secret_failure, DatabaseMember}; use registry_platform_provision::{ provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, }; @@ -74,17 +74,18 @@ pub(crate) fn load( "Correct secretProviders in the runtime file, then run provision again.", ) })?; - let resolve = |member: &str, reference: &str| { - secrets.resolve(reference).map_err(|error| { + let resolve = |member: DatabaseMember, reference: &str| { + let read = member.read(&secrets, reference); + read.map_err(|error| { refuse( "config.refused", &format!("/database/{member}"), describe_secret_failure(&format!("database.{member}"), reference, &error), - "Check the secret provider and that the secret exists, then run provision again.", + error.suggested_action(), ) }) }; - let url = |member: &str, reference: &str| { + let url = |member: DatabaseMember, reference: &str| { let secret = resolve(member, reference)?; std::str::from_utf8(secret.expose_secret()) .map(|text| Zeroizing::new(text.trim().to_owned())) @@ -97,13 +98,16 @@ pub(crate) fn load( ) }) }; - let migration_url = url("migrationUrlRef", &config.database.migration_url_ref)?; - let runtime_url = url("runtimeUrlRef", &config.database.runtime_url_ref)?; + let migration_url = url( + DatabaseMember::MigrationUrl, + &config.database.migration_url_ref, + )?; + let runtime_url = url(DatabaseMember::RuntimeUrl, &config.database.runtime_url_ref)?; let ca_pem = config .database .ca_bundle_ref .as_deref() - .map(|reference| resolve("caBundleRef", reference)) + .map(|reference| resolve(DatabaseMember::CaBundle, reference)) .transpose()? .map(|secret| secret.expose_secret().to_vec()); Ok(ProvisionInput { @@ -112,5 +116,6 @@ pub(crate) fn load( runtime_url, ca_pem, transport: provision_transport(&config.database), + explicit_settings: config.posture_report().explicit_setting_notices(), }) } diff --git a/crates/registry-schedulingctl/src/records.rs b/crates/registry-schedulingctl/src/records.rs index d0ec950cd5..dc309bbdba 100644 --- a/crates/registry-schedulingctl/src/records.rs +++ b/crates/registry-schedulingctl/src/records.rs @@ -18,7 +18,7 @@ use std::fs; use std::path::Path; use anyhow::{anyhow, Context, Result}; -use registry_platform_config::{SecretProvider, SecretResolver}; +use registry_platform_config::SecretResolver; use registry_scheduling::audit::{with_event_id, SchedulingAudit}; use registry_scheduling::config::RuntimeConfig; use registry_scheduling::runtime::open_audit; @@ -223,23 +223,14 @@ fn counts(facts: &SchedulingFacts) -> Value { }) } +/// The runtime's own resolver: the providers it enables, its file mount +/// policy and its development witness, so the tool reads a secret exactly +/// as the runtime does. pub(crate) fn secret_resolver(config: &RuntimeConfig) -> Result { - let mut providers = Vec::new(); - if config.secret_providers.file.is_some() { - providers.push(SecretProvider::File); - } - if config.secret_providers.environment.is_some() { - providers.push(SecretProvider::Environment); - } - SecretResolver::new( - providers, - config - .secret_providers - .file - .as_ref() - .map_or_else(|| Path::new(""), |file| file.root.as_path()), - ) - .context("configuring the Scheduling secret providers") + config + .secret_providers + .resolver(config.development_witness()) + .context("configuring the Scheduling secret providers") } #[cfg(test)] diff --git a/crates/registry-schedulingctl/src/templates.rs b/crates/registry-schedulingctl/src/templates.rs index 39c43313f1..7be5529380 100644 --- a/crates/registry-schedulingctl/src/templates.rs +++ b/crates/registry-schedulingctl/src/templates.rs @@ -5,8 +5,138 @@ //! Each template is a working project: its policy passes the check with zero //! findings and its fixtures replay all-Pass offline, which the tests prove //! end to end. The files are the committed examples under -//! `products/scheduling/examples`, so the two cannot drift, and every file -//! carries its schema modeline on its first line. +//! `products/scheduling/examples`, dated as of a common reference day. +//! Init moves their date groups together so the live supply is usable and +//! each fixture still proves the same scenario. Every file carries its +//! schema modeline on its first line. + +use std::borrow::Cow; + +use anyhow::{ensure, Result}; +use chrono::{Datelike, Days, NaiveDate, Offset, TimeDelta, TimeZone, Weekday}; +use chrono_tz::America::New_York; + +#[cfg(test)] +pub(super) const EXAMPLE_DATE: NaiveDate = example_date(10, 1); +const EXAMPLE_COUNTER: NaiveDate = example_date(10, 5); +const EXAMPLE_ARRIVAL: NaiveDate = example_date(10, 10); +const EXAMPLE_FOLD: NaiveDate = example_date(11, 1); + +const fn example_date(month: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, month, day).expect("valid starter reference date") +} + +pub(super) fn date_file<'a>( + template: &str, + relative: &str, + contents: &'a str, + today: NaiveDate, +) -> Result> { + let counter_shift = || { + // The example opens on the Thursday before the Monday fixture. Shift + // by whole weeks and choose a Monday whose opening has begun today. + let monday = on_or_after(today - Days::new(2), Weekday::Mon); + monday - EXAMPLE_COUNTER + }; + let fold_shift = || next_new_york_fold(today).map(|fold| fold - EXAMPLE_FOLD); + Ok(match (template, relative) { + ("standalone-exact-time", "scheduling.yaml") => { + let counter = counter_shift(); + let fold = fold_shift()?; + shift_dates(contents, |date| { + date + if date == EXAMPLE_FOLD { fold } else { counter } + }) + } + ("standalone-exact-time", "fixtures/counter-stations.yaml") => { + let shift = counter_shift(); + shift_dates(contents, |date| date + shift) + } + ("standalone-exact-time", "records.yaml" | "fixtures/fold-day-rebooking.yaml") + | ("resource-reservations", "records.yaml" | "fixtures/named-intervals.yaml") => { + let shift = fold_shift()?; + shift_dates(contents, |date| date + shift) + } + ( + "standalone-arrival-window", + "scheduling.yaml" + | "records.yaml" + | "fixtures/household-morning.yaml" + | "fixtures/household-afternoon.yaml", + ) => { + // Both named blocks need to be on the same Saturday, far enough + // ahead for their lead time and the example cancellation cutoff. + let saturday = on_or_after(today + Days::new(7), Weekday::Sat); + let shift = saturday - EXAMPLE_ARRIVAL; + shift_dates(contents, |date| date + shift) + } + ("resource-reservations", "scheduling.yaml") => { + let year = next_new_york_fold(today)?.year(); + // Cover the fixture's November fold and the live dates leading up + // to it, including when the fold will land in the next year. + shift_dates(contents, |date| { + let shifted = date.with_year(year).expect("valid opening date"); + if date == example_date(1, 1) { + shifted.min(today) + } else { + shifted + } + }) + } + _ => Cow::Borrowed(contents), + }) +} + +fn on_or_after(date: NaiveDate, weekday: Weekday) -> NaiveDate { + date + Days::new(u64::from(weekday.days_since(date.weekday()))) +} + +fn next_new_york_fold(today: NaiveDate) -> Result { + // America/New_York returns to standard time on the first Sunday in November. + let fold = |year| { + let november = NaiveDate::from_ymd_opt(year, 11, 1).expect("valid November date"); + on_or_after(november, Weekday::Sun) + }; + let this_year = fold(today.year()); + let fold = if this_year > today { + this_year + } else { + fold(today.year() + 1) + }; + // Both fixtures keep their original UTC clock times. Verify the offset + // change at precisely 06:00 UTC with the same timezone data as replay. + let transition = fold.and_hms_opt(6, 0, 0).expect("valid UTC time"); + let offset_seconds = |instant| { + New_York + .offset_from_utc_datetime(&instant) + .fix() + .local_minus_utc() + }; + ensure!( + offset_seconds(transition - TimeDelta::seconds(1)) == -4 * 3600 + && offset_seconds(transition) == -5 * 3600, + "America/New_York fold on {fold} does not match the starter's 06:00 UTC transition in the installed timezone data" + ); + Ok(fold) +} + +/// Move ISO date prefixes in the built-in YAML, including the dates in UTC +/// timestamps. Keep the emitted file formatting and all clock times intact. +fn shift_dates(contents: &str, shift: impl Fn(NaiveDate) -> NaiveDate) -> Cow<'_, str> { + let date_char = |c: char| c.is_ascii_digit() || c == '-'; + let mut output = String::with_capacity(contents.len()); + for token in contents.split_inclusive(|c| !date_char(c)) { + let date = token.trim_end_matches(|c| !date_char(c)); + if date.len() == 10 { + if let Ok(parsed) = NaiveDate::parse_from_str(date, "%Y-%m-%d") { + output.push_str(&shift(parsed).format("%Y-%m-%d").to_string()); + output.push_str(&token[date.len()..]); + continue; + } + } + output.push_str(token); + } + Cow::Owned(output) +} /// The example directory one template's files are read from. macro_rules! example { diff --git a/crates/registry-session/Cargo.toml b/crates/registry-session/Cargo.toml index dc1419efbd..cbc2295a76 100644 --- a/crates/registry-session/Cargo.toml +++ b/crates/registry-session/Cargo.toml @@ -43,6 +43,7 @@ schemars = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true sha2.workspace = true +tempfile.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true @@ -54,7 +55,6 @@ zeroize.workspace = true jsonschema.workspace = true registry-platform-testing.workspace = true reqwest.workspace = true -tempfile.workspace = true tower = { workspace = true, features = ["util"] } [[example]] diff --git a/crates/registry-session/README.md b/crates/registry-session/README.md index 63f38ece6d..a301d4453a 100644 --- a/crates/registry-session/README.md +++ b/crates/registry-session/README.md @@ -8,8 +8,10 @@ bearer token to attach. The service checks. It never proxies. This is not an identity provider or a token issuer. It uses the configured identity provider's authorization-code and refresh-token flows. Sessions and pending sign-ins live only in memory, in one replica. A restart loses them. -The binary is source-build only while `SESSION_FIRST_RELEASE` in -`release/scripts/release_roster.py` is unset. +Numbered releases ship the binary for Linux amd64, Linux arm64 and macOS arm64 +from v0.51.0, as `SESSION_FIRST_RELEASE` in +`release/scripts/release_roster.py` sets. It is a standalone release asset: +`rstack` does not install it, and it has no installer or container image. ## Configuration and commands @@ -42,7 +44,9 @@ audit destination before listening. `registry-session --runtime-config /absolute/path/session-runtime.yaml check` checks the same runtime model offline. It reads no secret, calls no provider, opens no socket and writes no audit file. `--format json` writes a -`PlatformSessionCtlReport`. It exits 0 when accepted, 1 when refused (or on +`PlatformSessionCtlReport`, which lists each explicit production setting the +file states under `explicitProductionSettings`. The human output prints each +as a notice on stderr. It exits 0 when accepted, 1 when refused (or on a warning with `--deny-warnings`), 2 for usage errors and 3 for unreadable input. Without `--environment`, environment expressions are checked only for syntax and position. `--identity-receipt /absolute/path/identity-receipt.json` @@ -55,6 +59,13 @@ them byte for byte. `--verify-assembled /absolute/path/envoy.yaml` checks the assembled static gateway configuration against the runtime file. Regenerate, splice and verify after every runtime change. +For a gateway and upstreams on one host, use `gateway envoy --standalone-out +/absolute/path/envoy.json --listen 127.0.0.1:8080 --upstream +registry=127.0.0.1:8100`. Set `gateway.service.host` to a numeric loopback +address. Supply one `--upstream` for every cluster named by a module or page, +then run `envoy --mode validate --config-path /absolute/path/envoy.json`. +Place an HTTPS-terminating reverse proxy on the same host for a public origin. + The session cookie is `__Host-registry-session` and holds an opaque 256-bit identifier. The temporary sign-in cookie is `__Host-registry-signin`. Both cookies carry `Secure`, `HttpOnly`, `SameSite=Lax` and `Path=/` in both diff --git a/crates/registry-session/src/config.rs b/crates/registry-session/src/config.rs index f6e76399b0..ecb17ebed3 100644 --- a/crates/registry-session/src/config.rs +++ b/crates/registry-session/src/config.rs @@ -972,6 +972,9 @@ pub struct RuntimeCheck { /// Whether a member that decides a kind's audiences holds an expression /// the check did not substitute, so the audiences it derived are stand-ins. pub deferred_audiences: bool, + /// The explicit production settings the file states, which `check` + /// reports beside its diagnostics. + pub explicit_settings: Vec, } /// The route a request path belongs to. @@ -1245,6 +1248,11 @@ pub(crate) fn read_runtime_file( let deferred_audiences = check.loaded.as_ref().is_some_and(|loaded| { deferred_audience_inputs(&loaded.config, &|pointer| check.defers(pointer)) }); + let explicit_settings = check + .loaded + .as_ref() + .map(|loaded| loaded.posture.explicit_settings().to_vec()) + .unwrap_or_default(); if refused { check.loaded = None; } @@ -1254,6 +1262,7 @@ pub(crate) fn read_runtime_file( diagnostics, unavailable, deferred_audiences, + explicit_settings, }, ) } diff --git a/crates/registry-session/src/gateway.rs b/crates/registry-session/src/gateway.rs index f56fa53fc1..50226f5f49 100644 --- a/crates/registry-session/src/gateway.rs +++ b/crates/registry-session/src/gateway.rs @@ -192,6 +192,14 @@ pub fn generate(config: &RuntimeConfig) -> Result, GatewayErr fn load_for_gateway( runtime_config: &Path, posture: DeclaredPosture, +) -> Result, GatewayError> { + load_gateway_config(runtime_config, posture, false) +} + +fn load_gateway_config( + runtime_config: &Path, + posture: DeclaredPosture, + checked_routes: bool, ) -> Result, GatewayError> { let (mut file, check) = read_runtime_file(runtime_config, false, posture); let Some(loaded) = file.loaded.take() else { @@ -214,6 +222,11 @@ fn load_for_gateway( }; require("/publicOrigin", file.defers("/publicOrigin")); require("/gateway", file.defers_within("/gateway")); + if checked_routes { + for pointer in ["/listener", "/checkListener", "/issuer", "/signIns"] { + require(pointer, file.defers_within(pointer)); + } + } for (list, count) in [ ("modules", loaded.config.modules.len()), ("pages", loaded.config.pages.len()), @@ -224,6 +237,15 @@ fn load_for_gateway( continue; } for index in 0..count { + if checked_routes { + let field = if list == "modules" { + "signIns" + } else { + "signIn" + }; + let binding = format!("/{list}/{index}/{field}"); + require(&binding, file.defers_within(&binding)); + } for field in ["id", "prefix", "upstream", "product"] { let pointer = format!("/{list}/{index}/{field}"); require( @@ -813,7 +835,11 @@ fn array<'a>(value: &'a Value, key: &str) -> &'a [Value] { } mod verify; -pub use verify::verify_assembled; +pub use verify::{ + verify_assembled, write_standalone, write_verified_route_inventory, StandaloneTls, +}; +#[cfg(feature = "schema")] +pub(crate) use verify::{ROUTE_INVENTORY_API_VERSION, ROUTE_INVENTORY_KIND}; #[cfg(test)] mod tests { diff --git a/crates/registry-session/src/gateway/verify.rs b/crates/registry-session/src/gateway/verify.rs index 096e7de25e..fea51f48fe 100644 --- a/crates/registry-session/src/gateway/verify.rs +++ b/crates/registry-session/src/gateway/verify.rs @@ -10,16 +10,27 @@ //! refused with a finding that names the member and says why. It does not try //! to model the rest of Envoy. -use std::{fs, io::Read, path::Path}; - +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::{Read, Write}, + net::{IpAddr, Ipv4Addr, SocketAddr}, + path::Path, +}; + +use registry_platform_config::{sha256_uri, ListenerNetworkExposure, TlsTermination}; use registry_platform_yaml::{Reader, Refusal, ScalarHook, ScalarSite, ScalarStyle}; -use serde_json::Value; +use serde_json::{json, Value}; use super::*; +use crate::config::ModuleProduct; use crate::wire::SOURCE_PROFILE_HEADER; /// The most bytes of an assembled configuration `--verify-assembled` reads. const MAXIMUM_ASSEMBLED_BYTES: u64 = 16 * 1024 * 1024; +pub(crate) const ROUTE_INVENTORY_API_VERSION: &str = + "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1"; +pub(crate) const ROUTE_INVENTORY_KIND: &str = "PlatformSessionRouteInventory"; const MANAGER_TYPE: &str = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"; @@ -106,6 +117,8 @@ struct Expected { routes: Vec, /// The generated local reply mappers, which come first and in order. mappers: Vec, + /// The two Session clusters, in generation order. + clusters: Vec, /// The host's own filters the generated routes switch off. host_filters: Vec, /// The host filters some generated route keeps on. @@ -171,7 +184,7 @@ impl Expected { ); } } - fragment("clusters.yaml")?; + let clusters = items(fragment("clusters.yaml")?); Ok(Self { authority: config .gateway_authority() @@ -179,6 +192,7 @@ impl Expected { filters: items(fragment("http-filters.yaml")?), routes: items(fragment("routes.yaml")?), mappers, + clusters, host_filters: config .gateway .iter() @@ -196,6 +210,390 @@ impl Expected { } } +/// Write a static Envoy configuration for a loopback deployment. The same +/// checked routes, filters and reply mappers are used for fragment integration. +pub fn write_standalone<'a>( + runtime_config: &Path, + output: &Path, + listen: SocketAddr, + upstreams: impl IntoIterator, + tls: Option>, + posture: DeclaredPosture, +) -> Result { + refuse_input_output_alias(output, runtime_config)?; + if let Some(tls) = &tls { + refuse_input_output_alias(output, tls.certificate)?; + refuse_input_output_alias(output, tls.key)?; + } + let loaded = load_gateway_config(runtime_config, posture, tls.is_some())?; + let mut expected = Expected::new(&loaded.config)?; + let gateway = loaded + .config + .gateway + .as_ref() + .ok_or(GatewayError::NoGatewayBlock)?; + if !expected.host_filters.is_empty() { + return Err(standalone_refusal( + "Remove gateway.hostFilters or integrate the generated fragments.", + )); + } + if !loopback_socket(listen) { + return Err(standalone_refusal( + "Set --listen to a numeric loopback address and nonzero port.", + )); + } + if !gateway + .service + .host + .as_str() + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + { + return Err(standalone_refusal( + "Set gateway.service.host to a numeric loopback address.", + )); + } + let addresses = standalone_upstreams(&standalone_clusters(&expected), upstreams)?; + if tls.is_some() { + let ingress = validate_checked_transport(&loaded.config, addresses.values().copied())?; + if ingress != listen { + return Err(standalone_refusal( + "Make --listen match the numeric HTTPS publicOrigin.", + )); + } + } + let document = standalone_document(&mut expected, listen, addresses, tls.as_ref())?; + let bytes = serde_json::to_vec_pretty(&document) + .map_err(|_| standalone_refusal("Could not serialize the configuration."))?; + let document = scan_assembly(output, &bytes)?; + verify_document(&expected, &document)?; + + write_output(output, &bytes)?; + Ok(loaded.posture) +} + +/// File paths as Envoy will see them. The generator reads neither file. +pub struct StandaloneTls<'a> { + pub certificate: &'a Path, + pub key: &'a Path, +} + +fn standalone_clusters(expected: &Expected) -> BTreeSet<&str> { + expected + .protected + .iter() + .map(String::as_str) + .filter(|name| !matches!(*name, PUBLIC_CLUSTER | CHECK_CLUSTER)) + .collect() +} + +fn standalone_document( + expected: &mut Expected, + listen: SocketAddr, + addresses: BTreeMap<&str, SocketAddr>, + tls: Option<&StandaloneTls<'_>>, +) -> Result { + let mut definitions = String::new(); + for (name, address) in addresses { + cluster( + &mut definitions, + name, + &address.ip().to_string(), + u32::from(address.port()), + ); + } + if !definitions.is_empty() { + let mut custom = parse_fragment(&GeneratedFile { + name: "standalone-clusters", + content: definitions, + })? + .as_array() + .cloned() + .ok_or_else(|| standalone_refusal("Could not assemble the upstream clusters."))?; + if tls.is_some() { + for cluster in &mut custom { + cluster["type"] = json!("STATIC"); + } + } + expected.clusters.extend(custom); + } + + let strip_port = expected + .authority + .rsplit_once(':') + .is_none_or(|(_, port)| port.parse::().is_err()); + let mut filters = expected.filters.clone(); + filters.push(json!({ + "name": "envoy.filters.http.router", + "typed_config": {"@type": ROUTER_TYPE}, + })); + let mut document = json!({ + "static_resources": { + "listeners": [{ + "name": "registry-session", + "address": {"socket_address": { + "address": listen.ip().to_string(), "port_value": listen.port(), + }}, + "filter_chains": [{"filters": [{ + "name": "envoy.filters.network.http_connection_manager", + "typed_config": { + "@type": MANAGER_TYPE, + "stat_prefix": "registry_session", + "strip_trailing_host_dot": true, + "strip_matching_host_port": strip_port, + "route_config": { + "name": "registry-session", + "virtual_hosts": [{ + "name": "registry-session", + "domains": [&expected.authority], + "routes": &expected.routes, + }], + }, + "local_reply_config": {"mappers": &expected.mappers}, + "http_filters": filters, + }, + }]}], + }], + "clusters": &expected.clusters, + }, + }); + if let Some(tls) = tls { + let certificate = checked_tls_path(tls.certificate)?; + let key = checked_tls_path(tls.key)?; + document["static_resources"]["listeners"][0]["filter_chains"][0]["transport_socket"] = json!({ + "name": "envoy.transport_sockets.tls", + "typed_config": { + "@type": "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext", + "common_tls_context": { + "alpn_protocols": ["h2", "http/1.1"], + "tls_params": {"tls_minimum_protocol_version": "TLSv1_2"}, + "tls_certificates": [{ + "certificate_chain": {"filename": certificate}, + "private_key": {"filename": key}, + }], + }, + }, + }); + } + Ok(document) +} + +fn checked_tls_path(path: &Path) -> Result<&str, GatewayError> { + path.to_str() + .filter(|value| path.is_absolute() && !value.chars().any(char::is_control)) + .ok_or_else(|| standalone_refusal("Use absolute UTF-8 filenames for gateway TLS material.")) +} + +fn refuse_input_output_alias(output: &Path, input: &Path) -> Result<(), GatewayError> { + let canonical = |path: &Path| { + path.canonicalize().ok().or_else(|| { + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()); + let directory = parent + .unwrap_or_else(|| Path::new(".")) + .canonicalize() + .ok()?; + Some(directory.join(path.file_name()?)) + }) + }; + if output == input || canonical(output).is_some_and(|output| canonical(input) == Some(output)) { + return Err(standalone_refusal( + "Write the gateway output to a file distinct from its input files.", + )); + } + Ok(()) +} + +fn validate_checked_transport( + config: &RuntimeConfig, + upstreams: impl IntoIterator, +) -> Result { + let gateway = config + .gateway + .as_ref() + .ok_or(GatewayError::NoGatewayBlock)?; + let origin = config.public_origin.to_url(); + let ingress = origin + .host_str() + .and_then(|host| host.parse::().ok()) + .zip(origin.port_or_known_default()) + .map(|(host, port)| SocketAddr::from((host, port))) + .filter(|socket| origin.scheme() == "https" && loopback_socket(*socket)) + .ok_or_else(|| { + standalone_refusal("Checked routes require a numeric IPv4 loopback HTTPS publicOrigin.") + })?; + let origin_authority = origin + .port() + .map_or_else(|| ingress.ip().to_string(), |_| ingress.to_string()); + if config.gateway_authority().as_deref() != Some(origin_authority.as_str()) + || config.listener.network_exposure != ListenerNetworkExposure::PrivateAddress + || !matches!( + config.listener.tls_termination, + TlsTermination::LoopbackPlaintext | TlsTermination::OperatorControlledUpstream + ) + || config + .issuer + .endpoints() + .iter() + .any(|(_, endpoint)| endpoint.to_url().scheme() != "https") + { + return Err(standalone_refusal("Checked routes require the public authority, private Session listeners and HTTPS issuer endpoints.")); + } + let host = gateway + .service + .host + .as_str() + .parse::() + .ok() + .filter(Ipv4Addr::is_loopback) + .ok_or_else(|| { + standalone_refusal("Checked routes require numeric IPv4 loopback Session listeners.") + })?; + let public = SocketAddr::from((host, gateway.service.public_port.get() as u16)); + let check = SocketAddr::from((host, gateway.service.check_port.get() as u16)); + if public != config.listener.bind.0 || check != config.check_listener.0 { + return Err(standalone_refusal( + "Match the gateway's Session sockets to the runtime listeners.", + )); + } + let mut sockets = BTreeSet::new(); + for socket in [ingress, public, check].into_iter().chain(upstreams) { + if !socket.is_ipv4() || !loopback_socket(socket) || !sockets.insert(socket) { + return Err(standalone_refusal("Use a distinct numeric IPv4 loopback socket for each gateway listener and upstream.")); + } + } + let routes = config + .modules + .iter() + .map(|module| module.upstream.as_ref()) + .chain(config.pages.iter().map(|page| page.upstream.as_ref())); + let mut clusters = BTreeSet::from([PUBLIC_CLUSTER, CHECK_CLUSTER]); + if !gateway.host_filters.is_empty() + || routes.into_iter().any(|upstream| { + upstream.is_none_or(|upstream| { + !upstream.keep_host_filters.is_empty() + || !clusters.insert(upstream.cluster.as_str()) + }) + }) + { + return Err(standalone_refusal( + "Checked routes require one exclusive cluster per route and no host filters.", + )); + } + Ok(ingress) +} + +fn verify_checked_transport<'a>( + config: &RuntimeConfig, + document: &'a Value, +) -> Result, GatewayError> { + let refusal = || { + standalone_refusal( + "Use the complete dedicated loopback HTTPS Envoy assembly for checked route export.", + ) + }; + let mut expected = Expected::new(config)?; + let resources = &document["static_resources"]; + let chain = &resources["listeners"][0]["filter_chains"][0]; + let certificates = + &chain["transport_socket"]["typed_config"]["common_tls_context"]["tls_certificates"][0]; + let certificate = certificates["certificate_chain"]["filename"] + .as_str() + .ok_or_else(refusal)?; + let key = certificates["private_key"]["filename"] + .as_str() + .ok_or_else(refusal)?; + let tls = StandaloneTls { + certificate: Path::new(certificate), + key: Path::new(key), + }; + let clusters = resources["clusters"].as_array().ok_or_else(refusal)?; + let addresses: BTreeMap<_, _> = standalone_clusters(&expected).into_iter().map(|name| { + let endpoint = clusters.iter().find(|cluster| cluster["name"] == name) + .and_then(|cluster| cluster.pointer("/load_assignment/endpoints/0/lb_endpoints/0/endpoint/address/socket_address")) + .ok_or_else(refusal)?; + let ip = endpoint["address"].as_str().and_then(|value| value.parse::().ok()).ok_or_else(refusal)?; + let port = endpoint["port_value"].as_u64().and_then(|port| u16::try_from(port).ok()).ok_or_else(refusal)?; + Ok((name.to_owned(), SocketAddr::from((ip, port)))) + }).collect::>()?; + let ingress = validate_checked_transport(config, addresses.values().copied())?; + let by_name = addresses + .iter() + .map(|(name, socket)| (name.as_str(), *socket)) + .collect(); + let wanted = standalone_document(&mut expected, ingress, by_name, Some(&tls))?; + if document != &wanted { + return Err(refusal()); + } + verify_document(&expected, document)?; + Ok(tls) +} + +fn write_output(output: &Path, bytes: &[u8]) -> Result<(), GatewayError> { + let parent = output + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + let mut staged = + tempfile::NamedTempFile::new_in(parent).map_err(|error| io_error(output, &error))?; + staged + .write_all(bytes) + .and_then(|()| staged.write_all(b"\n")) + .map_err(|error| io_error(output, &error))?; + staged + .persist(output) + .map_err(|error| io_error(output, &error.error))?; + Ok(()) +} + +fn loopback_socket(address: SocketAddr) -> bool { + address.ip().is_loopback() && address.port() != 0 +} + +fn standalone_refusal(finding: impl Into) -> GatewayError { + GatewayError::Refused(vec![finding.into()]) +} + +fn standalone_upstreams<'a>( + required: &BTreeSet<&str>, + upstreams: impl IntoIterator, +) -> Result, GatewayError> { + let mut bindings = BTreeMap::new(); + for binding in upstreams { + let (name, socket) = binding + .split_once('=') + .ok_or_else(|| standalone_refusal("Pass each --upstream as CLUSTER=ADDRESS."))?; + if !required.contains(name) { + return Err(standalone_refusal( + "Name a configured module or page cluster in --upstream.", + )); + } + let address = socket + .parse() + .ok() + .filter(|address| loopback_socket(*address)) + .ok_or_else(|| { + standalone_refusal(format!( + "Set --upstream for {name} to a numeric loopback address and nonzero port." + )) + })?; + if bindings.insert(name, address).is_some() { + return Err(standalone_refusal(format!( + "Cluster {name} is supplied more than once." + ))); + } + } + for &name in required { + if !bindings.contains_key(name) { + return Err(standalone_refusal(format!( + "Pass --upstream for the required cluster {name}." + ))); + } + } + Ok(bindings) +} + /// Check an assembled Envoy configuration offline against what the runtime /// file generates now. /// @@ -218,6 +616,148 @@ pub fn verify_assembled( Ok(loaded.posture) } +/// Project the checked gateway routes without upstream addresses or credentials. +/// The selected module supplies the browser client binding. The product still +/// decides what a route can call and who can call it. +pub fn write_verified_route_inventory( + runtime_config: &Path, + assembled: &Path, + output: &Path, + selection: &str, + posture: DeclaredPosture, +) -> Result { + let loaded = load_gateway_config(runtime_config, posture, true)?; + let config = &loaded.config; + let assembly_bytes = read_assembly_bytes(assembled).map_err(|_| { + standalone_refusal("Supply a readable, valid Envoy assembly for checked route export.") + })?; + let json_refusal = + || standalone_refusal("Supply the generated standalone Envoy configuration as JSON."); + let document = scan_assembly(assembled, &assembly_bytes).map_err(|_| json_refusal())?; + if serde_json::from_slice::(&assembly_bytes).map_err(|_| json_refusal())? != document { + return Err(json_refusal()); + } + let tls = verify_checked_transport(config, &document)?; + refuse_input_output_alias(output, runtime_config)?; + refuse_input_output_alias(output, assembled)?; + refuse_input_output_alias(output, tls.certificate)?; + refuse_input_output_alias(output, tls.key)?; + + let module = config + .modules + .iter() + .find(|module| module.id.as_str() == selection) + .filter(|module| module.product == Some(ModuleProduct::Breg)) + .ok_or_else(|| standalone_refusal("Select one declared BReg product module."))?; + let rewrite = module + .upstream + .as_ref() + .and_then(|upstream| upstream.prefix_rewrite.as_ref()) + .map(|prefix| prefix.as_str()); + let overlap = + |other: &str| lies_under(&module.prefix, other) || lies_under(other, &module.prefix); + if module.prefix.len() > 256 + || !module.prefix.ends_with('/') + || !module + .prefix + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"/._:-".contains(&byte)) + { + return Err(standalone_refusal( + "Use letters, digits or /._:- and a trailing slash in the selected BReg prefix.", + )); + } + if rewrite != Some("/") + || config + .modules + .iter() + .any(|other| other.id != module.id && overlap(&other.prefix)) + || config.pages.iter().any(|page| overlap(&page.prefix)) + { + return Err(standalone_refusal( + "Select a disjoint BReg module prefix that rewrites to the product root.", + )); + } + let route_prefixes = config + .modules + .iter() + .map(|module| &module.prefix) + .chain(config.pages.iter().map(|page| &page.prefix)); + if route_prefixes.into_iter().any(|prefix| { + !prefix + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"/._:~-".contains(&byte)) + }) { + return Err(standalone_refusal( + "Use checked route prefixes made of letters, digits, or /._:~-.", + )); + } + if config.pages.iter().any(|page| { + config.modules.iter().any(|module| { + lies_under(&page.prefix, &module.prefix) || lies_under(&module.prefix, &page.prefix) + }) + }) { + return Err(standalone_refusal( + "Use page prefixes disjoint from all module prefixes in a checked inventory.", + )); + } + let sign_ins = config + .sign_ins + .iter() + .map(|entry| entry.id.as_str()) + .collect::>(); + if !sign_ins.iter().any(|id| module.admits(id)) + || sign_ins.len() > 64 + || config.pages.len() > 64 + || config.modules.len() > 64 + { + return Err(standalone_refusal( + "Checked routes require an admitted sign-in and at most 64 sign-ins, modules and pages.", + )); + } + let modules: Vec<_> = config + .modules + .iter() + .map(|module| { + let admitted: Vec<_> = sign_ins.iter().filter(|id| module.admits(id)).collect(); + let mut route = + json!({"id": module.id.as_str(), "prefix": module.prefix, "signIns": admitted}); + if let Some(product) = module.product { + route["product"] = json!(product.as_str()); + } + if let Some(rewrite) = module + .upstream + .as_ref() + .and_then(|upstream| upstream.prefix_rewrite.as_ref()) + { + route["prefixRewrite"] = json!(rewrite.as_str()); + } + route + }) + .collect(); + let pages: Vec<_> = config + .pages + .iter() + .map(|page| json!({"prefix": page.prefix, "signIn": page.sign_in.as_str()})) + .collect(); + let projection = serde_json::to_vec(&json!({"modules": modules, "pages": pages})) + .map_err(|_| standalone_refusal("Could not serialize the sign-in projection."))?; + let inventory = json!({ + "apiVersion": ROUTE_INVENTORY_API_VERSION, + "kind": ROUTE_INVENTORY_KIND, + "publicOrigin": config.public_origin.as_str().trim_end_matches('/'), + "gatewayDigest": sha256_uri(&assembly_bytes), + "signInDigest": sha256_uri(&projection), + "selectedModule": selection, + "modules": modules, + "pages": pages, + }); + let bytes = serde_json::to_vec_pretty(&inventory) + .map_err(|_| standalone_refusal("Could not serialize the verified route inventory."))?; + write_output(output, &bytes)?; + Ok(loaded.posture) +} + fn verify_loaded(config: &RuntimeConfig, assembled: &Path) -> Result<(), GatewayError> { let expected = Expected::new(config)?; let document = read_assembly(assembled)?; @@ -225,6 +765,10 @@ fn verify_loaded(config: &RuntimeConfig, assembled: &Path) -> Result<(), Gateway } fn read_assembly(assembled: &Path) -> Result { + scan_assembly(assembled, &read_assembly_bytes(assembled)?) +} + +fn read_assembly_bytes(assembled: &Path) -> Result, GatewayError> { let file = fs::File::open(assembled).map_err(|error| io_error(assembled, &error))?; let metadata = file .metadata() @@ -238,6 +782,10 @@ fn read_assembly(assembled: &Path) -> Result { file.take(MAXIMUM_ASSEMBLED_BYTES + 1) .read_to_end(&mut bytes) .map_err(|error| io_error(assembled, &error))?; + Ok(bytes) +} + +fn scan_assembly(assembled: &Path, bytes: &[u8]) -> Result { if bytes.len() as u64 > MAXIMUM_ASSEMBLED_BYTES { return Err(GatewayError::Assembled(vec![ "the assembled configuration is larger than 16 MiB".to_owned(), @@ -246,7 +794,7 @@ fn read_assembly(assembled: &Path) -> Result { let mut reading = EnvoyReading; let document = Reader::new(assembled.display().to_string()) .with_hook(&mut reading) - .scan(&bytes) + .scan(bytes) .map_err(GatewayError::AssembledSyntax)? .ok_or_else(|| { GatewayError::Assembled(vec!["the assembled configuration is empty".to_owned()]) diff --git a/crates/registry-session/src/lib.rs b/crates/registry-session/src/lib.rs index 182ae27c8e..80c70798f8 100644 --- a/crates/registry-session/src/lib.rs +++ b/crates/registry-session/src/lib.rs @@ -25,7 +25,7 @@ mod signin; pub mod store; pub mod wire; -use std::path::PathBuf; +use std::{net::SocketAddr, path::PathBuf}; use clap::{value_parser, Arg, ArgAction, ArgGroup, Command}; use registry_platform_posture::POSTURE_FLAG; @@ -106,10 +106,10 @@ pub fn command() -> Command { .subcommand_required(true) .subcommand( Command::new("envoy") - .about("Write or compare the Envoy configuration fragments") + .about("Generate or verify the Envoy configuration") .group( ArgGroup::new("mode") - .args(["out", "check", "verify-assembled"]) + .args(["out", "check", "verify-assembled", "standalone-out"]) .required(true) .multiple(false), ) @@ -136,6 +136,63 @@ pub fn command() -> Command { runtime file generates", ) .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("route-inventory-out") + .long("route-inventory-out") + .value_name("FILE") + .help("Write browser paths for the selected Base Registry Engine route from a verified loopback HTTPS assembly") + .requires_all(["verify-assembled", "checked-route"]) + .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("checked-route") + .long("checked-route") + .value_name("ID") + .help("Select the Base Registry Engine module for the browser route inventory") + .requires("route-inventory-out"), + ) + .arg( + Arg::new("standalone-out") + .long("standalone-out") + .value_name("FILE") + .help("Write one complete Envoy JSON configuration using loopback listeners and upstreams") + .requires("listen") + .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("listen") + .long("listen") + .value_name("ADDRESS") + .help("Numeric loopback socket address for Envoy") + .requires("standalone-out") + .conflicts_with_all(["out", "check", "verify-assembled"]) + .value_parser(value_parser!(SocketAddr)), + ) + .arg( + Arg::new("upstream") + .long("upstream") + .value_name("CLUSTER=ADDRESS") + .help("Numeric loopback socket for one configured module or page cluster. Repeat for each cluster") + .requires("standalone-out") + .conflicts_with_all(["out", "check", "verify-assembled"]) + .action(ArgAction::Append), + ) + .arg( + Arg::new("tls-certificate") + .long("tls-certificate") + .value_name("FILE") + .help("Absolute filename of the certificate chain for dedicated loopback HTTPS") + .requires_all(["standalone-out", "tls-key"]) + .value_parser(value_parser!(PathBuf)), + ) + .arg( + Arg::new("tls-key") + .long("tls-key") + .value_name("FILE") + .help("Absolute filename of the Envoy TLS private key") + .requires("tls-certificate") + .value_parser(value_parser!(PathBuf)), ), ), ) @@ -157,12 +214,26 @@ mod tests { } #[test] - fn a_gateway_mode_is_exactly_one_of_out_check_and_verify_assembled() { + fn a_gateway_mode_is_exactly_one_of_the_four_outputs_or_checks() { let envoy = ["--runtime-config", "/r.yaml", "gateway", "envoy"]; let with = |extra: &[&str]| parses(&[&envoy[..], extra].concat()); assert!(with(&["--out", "/d"])); assert!(with(&["--check", "/d"])); assert!(with(&["--verify-assembled", "/e.yaml"])); + assert!(with(&[ + "--standalone-out", + "/e.json", + "--listen", + "127.0.0.1:8080" + ])); + assert!(!with(&["--standalone-out", "/e.json"])); + assert!(!with(&["--out", "/d", "--listen", "127.0.0.1:8080"])); + assert!(!with(&[ + "--check", + "/d", + "--upstream", + "api=127.0.0.1:8100" + ])); assert!(!with(&[])); assert!(!with(&["--out", "/d", "--check", "/d"])); assert!(!with(&["--out", "/d", "--verify-assembled", "/e.yaml"])); diff --git a/crates/registry-session/src/main.rs b/crates/registry-session/src/main.rs index eea80bdfe9..abc8633e46 100644 --- a/crates/registry-session/src/main.rs +++ b/crates/registry-session/src/main.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +use std::net::SocketAddr; use std::path::PathBuf; use std::process::ExitCode; @@ -95,7 +96,32 @@ async fn main() -> ExitCode { return ExitCode::from(2); }; let result = if let Some(assembled) = arguments.get_one::("verify-assembled") { - gateway::verify_assembled(path, assembled, posture) + match arguments.get_one::("route-inventory-out") { + Some(out) => gateway::write_verified_route_inventory( + path, + assembled, + out, + arguments + .get_one::("checked-route") + .expect("inventory requires a module"), + posture, + ), + None => gateway::verify_assembled(path, assembled, posture), + } + } else if let Some(out) = arguments.get_one::("standalone-out") { + let listen = *arguments + .get_one::("listen") + .expect("standalone output requires --listen"); + let upstreams = arguments + .get_many::("upstream") + .into_iter() + .flatten() + .map(String::as_str); + let tls = arguments + .get_one::("tls-certificate") + .zip(arguments.get_one::("tls-key")) + .map(|(certificate, key)| gateway::StandaloneTls { certificate, key }); + gateway::write_standalone(path, out, listen, upstreams, tls, posture) } else { let mode = match ( arguments.get_one::("out"), diff --git a/crates/registry-session/src/offline.rs b/crates/registry-session/src/offline.rs index 7ff0e006bc..f17411e011 100644 --- a/crates/registry-session/src/offline.rs +++ b/crates/registry-session/src/offline.rs @@ -64,13 +64,16 @@ struct CtlReport { errors: usize, warnings: usize, diagnostics: serde_json::Value, + /// Each explicit production setting the file states: a fact for review, + /// not a diagnostic. + explicit_production_settings: Vec, } /// Run `registry-session check` and report every finding (CFG-DIAG-4): exit 0 when /// nothing was refused, 1 when something was or a warning was reported under /// `--deny-warnings`, and 3 when the file could not be read. pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn Write) -> u8 { - let (mut diagnostics, mut unavailable) = + let (mut diagnostics, mut unavailable, settings) = check_runtime_file(request.runtime, request.environment, request.posture); if let (Some(receipt), false) = (request.identity_receipt, diagnostics.iter().any(is_error)) { let (found, unreadable) = receipt_diagnostics( @@ -107,6 +110,15 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn errors: report.error_count(), warnings: report.warning_count(), diagnostics: report.to_json_value(), + explicit_production_settings: settings + .iter() + .map(|found| { + registry_platform_config::ExplicitSettingLine::from_found( + found, + Some(&request.runtime.display().to_string()), + ) + }) + .collect(), }; let written = serde_json::to_writer_pretty(&mut *stdout, &document) .map_err(std::io::Error::other) @@ -116,6 +128,11 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn } } OutputFormat::Human if exit == 0 => { + for found in &settings { + if writeln!(stderr, "{}", found.notice()).is_err() { + return OPERATIONAL_FAILURE_EXIT; + } + } if stdout.write_all(report.render_human().as_bytes()).is_err() { return OPERATIONAL_FAILURE_EXIT; } @@ -136,12 +153,17 @@ pub fn run(request: &CheckRequest<'_>, stdout: &mut dyn Write, stderr: &mut dyn /// Check the runtime file at `path` as given: the loader needs an absolute, /// lexically normal path, and every diagnostic names the file as given. -/// Returns the findings and whether the file could not be read at all. +/// Returns the findings, whether the file could not be read at all, and the +/// explicit production settings it states. fn check_runtime_file( path: &Path, environment: bool, posture: DeclaredPosture, -) -> (Vec, bool) { +) -> ( + Vec, + bool, + Vec, +) { let given = path.display().to_string(); let Some(absolute) = absolute_lexical(path) else { let mut diagnostic = Diagnostic::error( @@ -155,7 +177,7 @@ fn check_runtime_file( line: None, column: None, }); - return (vec![diagnostic], true); + return (vec![diagnostic], true, Vec::new()); }; let checked = crate::config::check_runtime(&absolute, environment, posture); let absolute = absolute.display().to_string(); @@ -176,7 +198,7 @@ fn check_runtime_file( diagnostic }) .collect(); - (diagnostics, checked.unavailable) + (diagnostics, checked.unavailable, checked.explicit_settings) } /// `path` made absolute against the working directory, with `.` and `..` diff --git a/crates/registry-session/src/schema.rs b/crates/registry-session/src/schema.rs index 5a76b259a4..c74649b04f 100644 --- a/crates/registry-session/src/schema.rs +++ b/crates/registry-session/src/schema.rs @@ -7,19 +7,27 @@ use std::{borrow::Cow, collections::BTreeMap}; +use registry_platform_yaml::{Digest, LocalId, Url}; +use schemars::generate::SchemaSettings; use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator}; use serde_json::{json, Value}; use crate::config::{ - Authority, ClaimName, ClusterName, FilterName, HostName, ModuleAudience, ResourceUri, - RewritePrefix, RuntimeConfig, ScopeToken, RUNTIME_API_VERSION, RUNTIME_KIND, + Authority, ClaimName, ClusterName, FilterName, HostName, ModuleAudience, ModuleProduct, + ResourceUri, RewritePrefix, RuntimeConfig, ScopeToken, RUNTIME_API_VERSION, RUNTIME_KIND, }; +use crate::gateway::{ROUTE_INVENTORY_API_VERSION, ROUTE_INVENTORY_KIND}; /// The `$id` of the runtime schema. pub const RUNTIME_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/session-runtime/session-runtime.v1alpha1.schema.json"; /// The file name of the committed runtime schema. pub const RUNTIME_SCHEMA_FILE: &str = "session-runtime.schema.json"; +/// The `$id` of the checked browser route inventory schema. +pub const ROUTE_INVENTORY_SCHEMA_ID: &str = + "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json"; +/// The file name of the committed checked route inventory schema. +pub const ROUTE_INVENTORY_SCHEMA_FILE: &str = "session-route-inventory.v1alpha1.schema.json"; /// Every generated schema, by file name, as the bytes to commit. pub fn schema_documents() -> Result, serde_json::Error> { @@ -43,7 +51,66 @@ pub fn schema_documents() -> Result, serde_json:: ]); let mut rendered = serde_json::to_string_pretty(&runtime)?; rendered.push('\n'); - Ok([(RUNTIME_SCHEMA_FILE, rendered)].into()) + let mut inventory = serde_json::to_string_pretty(&route_inventory_schema())?; + inventory.push('\n'); + Ok([ + (RUNTIME_SCHEMA_FILE, rendered), + (ROUTE_INVENTORY_SCHEMA_FILE, inventory), + ] + .into()) +} + +fn route_inventory_schema() -> Value { + let mut generator = SchemaSettings::draft2020_12().into_generator(); + let id = generator.subschema_for::(); + let digest = generator.subschema_for::(); + let product = generator.subschema_for::(); + let rewrite = generator.subschema_for::(); + let mut origin = json!(generator.subschema_for::()); + origin["pattern"] = json!("^https://127(?:\\.[0-9]{1,3}){3}(?::[0-9]{1,5})?$"); + json!({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": ROUTE_INVENTORY_SCHEMA_ID, + "$defs": generator.take_definitions(true), + "title": "Checked Registry Session route inventory", + "description": "Every configured module and page in a verified Envoy assembly, with one selected Base Registry Engine browser binding. Routes use the longest matching prefix at a path segment boundary.", + "type": "object", + "additionalProperties": false, + "required": ["apiVersion", "kind", "publicOrigin", "gatewayDigest", "signInDigest", "selectedModule", "modules", "pages"], + "properties": { + "apiVersion": {"type": "string", "const": ROUTE_INVENTORY_API_VERSION}, + "kind": {"type": "string", "const": ROUTE_INVENTORY_KIND}, + "publicOrigin": origin, + "gatewayDigest": digest, + "signInDigest": digest, + "selectedModule": id, + "modules": { + "type": "array", "minItems": 1, "maxItems": 64, "uniqueItems": true, + "items": { + "type": "object", "additionalProperties": false, + "required": ["id", "prefix", "signIns"], + "properties": { + "id": id, + "product": product, + "prefix": {"type": "string", "maxLength": 256, "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$"}, + "prefixRewrite": rewrite, + "signIns": {"type": "array", "maxItems": 64, "uniqueItems": true, "items": id} + } + } + }, + "pages": { + "type": "array", "maxItems": 64, "uniqueItems": true, + "items": { + "type": "object", "additionalProperties": false, + "required": ["prefix", "signIn"], + "properties": { + "prefix": {"type": "string", "maxLength": 256, "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$"}, + "signIn": id + } + } + } + } + }) } /// File audit requires an absolute path. Stdout accepts no file-only setting. diff --git a/crates/registry-session/tests/binary.rs b/crates/registry-session/tests/binary.rs index 66a6436f59..693cc17ba5 100644 --- a/crates/registry-session/tests/binary.rs +++ b/crates/registry-session/tests/binary.rs @@ -117,6 +117,43 @@ async fn the_offline_check_passes_a_good_file_and_reports_json() { assert_eq!(report["kind"], "PlatformSessionCtlReport"); } +#[tokio::test] +async fn the_offline_check_reports_the_explicit_production_settings() { + let harness = Harness::start().await; + let runtime = runtime_file(&harness); + let (code, stdout, stderr) = run(&runtime, &["--format", "json"]); + assert_eq!(code, 0, "{stderr}"); + let report: serde_json::Value = serde_json::from_str(&stdout).expect("json report"); + assert_eq!(report["explicitProductionSettings"], json!([])); + + let text = std::fs::read_to_string(&runtime).expect("runtime file"); + let stated = text.replacen( + "secretProviders:\n file:\n", + "secretProviders:\n file:\n mountPolicy: compose-native\n", + 1, + ); + assert_ne!(stated, text, "the member is written"); + std::fs::write(&runtime, stated).expect("rewrite the runtime file"); + let (code, stdout, stderr) = run(&runtime, &["--format", "json"]); + assert_eq!(code, 0, "{stderr}"); + let report: serde_json::Value = serde_json::from_str(&stdout).expect("json report"); + let settings = report["explicitProductionSettings"].as_array().unwrap(); + assert!( + settings.iter().any(|setting| setting["code"] + == "platform.posture.compose-native-secret-mount" + && setting["pointer"] == "/secretProviders/file/mountPolicy"), + "{report}" + ); + let (code, _, stderr) = run(&runtime, &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains( + "Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy." + ), + "{stderr}" + ); +} + #[tokio::test] async fn a_receipt_that_matches_passes_and_a_typo_fails_naming_the_kind() { let harness = Harness::start().await; @@ -233,6 +270,417 @@ async fn the_check_reports_a_refused_file_without_serving() { const GATEWAY_FIXTURE: &str = include_str!("gateway/runtime.yaml"); +#[test] +fn gateway_writes_a_deterministic_checked_standalone_configuration() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write(&runtime, standalone_runtime()).expect("runtime"); + let config = root.path().join("envoy.json"); + + generate_standalone(&runtime, &config); + let first = std::fs::read(&config).expect("read Envoy configuration"); + generate_standalone(&runtime, &config); + assert_eq!( + std::fs::read(&config).expect("read regenerated configuration"), + first + ); + + let verified = runtime_command(&runtime) + .args(["gateway", "envoy", "--verify-assembled"]) + .arg(&config) + .output() + .expect("check complete Envoy configuration"); + assert!( + verified.status.success(), + "{}", + String::from_utf8_lossy(&verified.stderr) + ); + + let document: serde_json::Value = serde_json::from_slice(&first).expect("JSON configuration"); + assert_eq!( + document.pointer("/static_resources/listeners/0/address/socket_address/address"), + Some(&serde_json::json!("127.0.0.1")) + ); + assert_eq!( + document + .pointer("/static_resources/clusters") + .and_then(serde_json::Value::as_array) + .map(Vec::len), + Some(4) + ); +} + +#[test] +fn gateway_inventory_requires_the_exact_verified_assembly() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + let runtime_source = standalone_runtime() + .replace("https://app.example", "https://127.0.0.1:8080") + .replace( + "session:\n", + " reviewer:\n clientId: reviewer-app\n clientSecretRef: secret:file/reviewer-secret\n scopes: [registry:read]\nsession:\n", + ) + .replace( + "pages:\n", + " - id: functions\n product: breg\n prefix: /api/functions/\n audience: person\n upstream: {cluster: functions, prefixRewrite: /functions/}\npages:\n", + ); + std::fs::write(&runtime, &runtime_source).expect("runtime"); + let assembly = root.path().join("envoy.json"); + let routes = root.path().join("routes.json"); + let certificate = root.path().join("cert.pem"); + let key = root.path().join("key.pem"); + std::fs::write(&key, "synthetic key placeholder").expect("key placeholder"); + let export = |output: &std::path::Path| { + run_command( + runtime_command(&runtime) + .args(["gateway", "envoy", "--verify-assembled"]) + .arg(&assembly) + .arg("--route-inventory-out") + .arg(output) + .args(["--checked-route", "breg"]), + ) + }; + let verify = || export(&routes); + let assemble = |tls| { + let mut command = runtime_command(&runtime); + command + .args(["gateway", "envoy", "--standalone-out"]) + .arg(&assembly) + .args([ + "--listen", + "127.0.0.1:8080", + "--upstream", + "registry=127.0.0.1:8100", + "--upstream", + "pages=127.0.0.1:8200", + "--upstream", + "functions=127.0.0.1:8300", + ]); + if tls { + command + .arg("--tls-certificate") + .arg(&certificate) + .arg("--tls-key") + .arg(&key); + } + run_command(&mut command) + }; + assert_eq!(assemble(false).0, 0); + assert_eq!(verify().0, 1, "ordinary plaintext assembly must not export"); + assert!(!routes.exists()); + let (exit, _, stderr) = assemble(true); + assert_eq!(exit, 0, "{stderr}"); + let assembled: serde_json::Value = + serde_json::from_slice(&std::fs::read(&assembly).expect("assembly")).expect("Envoy JSON"); + assert_eq!( + assembled.pointer(concat!( + "/static_resources/listeners/0/filter_chains/0/transport_socket/typed_config", + "/common_tls_context/tls_params/tls_minimum_protocol_version" + )), + Some(&json!("TLSv1_2")) + ); + let (exit, _, stderr) = verify(); + assert_eq!(exit, 0, "{stderr}"); + let first = std::fs::read(&routes).expect("route inventory"); + let inventory: serde_json::Value = serde_json::from_slice(&first).expect("JSON inventory"); + assert_eq!(inventory["kind"], "PlatformSessionRouteInventory"); + assert_eq!(inventory["publicOrigin"], "https://127.0.0.1:8080"); + assert_eq!(inventory["selectedModule"], "breg"); + let digest = |file: &std::path::Path| { + let bytes = std::fs::read(file).expect("assembly bytes"); + registry_platform_config::sha256_uri(&bytes) + }; + assert_eq!(inventory["gatewayDigest"], digest(&assembly)); + #[cfg(feature = "schema")] + { + use registry_session::schema::{schema_documents, ROUTE_INVENTORY_SCHEMA_FILE}; + let schemas = schema_documents().expect("Session schemas"); + let schema = serde_json::from_str(&schemas[ROUTE_INVENTORY_SCHEMA_FILE]) + .expect("inventory schema is JSON"); + let validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .expect("inventory schema compiles"); + assert!( + validator.is_valid(&inventory), + "native inventory violates its schema" + ); + } + assert_eq!( + inventory["modules"], + json!([ + {"id": "breg", "product": "breg", "prefix": "/api/registry/", + "prefixRewrite": "/", "signIns": ["citizen", "reviewer"]}, + {"id": "functions", "product": "breg", "prefix": "/api/functions/", + "prefixRewrite": "/functions/", "signIns": ["citizen", "reviewer"]} + ]) + ); + assert_eq!( + inventory["pages"], + json!([{"prefix": "/apply/", "signIn": "citizen"}]) + ); + let output = String::from_utf8_lossy(&first); + for private in [ + ":8100", + ":8121", + "secret:", + "https://id.example", + "clientId", + "key.pem", + ] { + assert!(!output.contains(private), "{output}"); + } + + let (exit, _, stderr) = verify(); + assert_eq!(exit, 0, "{stderr}"); + assert_eq!(std::fs::read(&routes).expect("regenerated routes"), first); + + let changed_sign_in = runtime_source.replace(" signIn: citizen", " signIn: reviewer"); + assert_ne!(changed_sign_in, runtime_source); + std::fs::write(&runtime, changed_sign_in).expect("changed sign-in"); + assert_eq!(verify().0, 0); + let changed: serde_json::Value = + serde_json::from_slice(&std::fs::read(&routes).expect("updated inventory")).unwrap(); + assert_eq!(changed["gatewayDigest"], inventory["gatewayDigest"]); + assert_ne!(changed["signInDigest"], inventory["signInDigest"]); + assert_eq!(changed["pages"][0]["signIn"], "reviewer"); + + let restricted_function = runtime_source.replace( + " prefix: /api/functions/\n audience: person", + " prefix: /api/functions/\n audience: person\n signIns: [reviewer]", + ); + assert_ne!(restricted_function, runtime_source); + std::fs::write(&runtime, restricted_function).expect("changed function admission"); + let (exit, _, stderr) = verify(); + assert_eq!(exit, 0, "{stderr}"); + let changed: serde_json::Value = + serde_json::from_slice(&std::fs::read(&routes).expect("changed function inventory")) + .unwrap(); + assert_eq!(changed["gatewayDigest"], inventory["gatewayDigest"]); + assert_eq!(changed["pages"], inventory["pages"]); + assert_eq!(changed["modules"][1]["signIns"], json!(["reviewer"])); + assert_ne!(changed["signInDigest"], inventory["signInDigest"]); + + std::fs::write(&runtime, &runtime_source).expect("restore literal test fixture"); + assert_eq!(verify().0, 0); + assert_eq!(std::fs::read(&routes).expect("restored inventory"), first); + + for (field, deferred) in [ + ( + "module sign-ins", + runtime_source.replace( + " audience: person\n", + " audience: person\n signIns: [citizen, reviewer, '${MODULE_SIGN_IN}']\n", + ), + ), + ( + "page sign-in", + runtime_source.replace(" signIn: citizen", " signIn: '${PAGE_SIGN_IN}'"), + ), + ] { + assert_ne!(deferred, runtime_source); + std::fs::write(&runtime, deferred).expect("deferred runtime"); + let (exit, _, error) = verify(); + assert_eq!(exit, 1, "refuse deferred {field}"); + let pointer = if field == "module sign-ins" { + "/modules/0/signIns" + } else { + "/pages/0/signIn" + }; + assert!(error.contains(pointer), "{error}"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + } + std::fs::write(&runtime, &runtime_source).expect("restore literal test fixture"); + + assert_eq!(export(&key).0, 1, "refuse to overwrite the gateway TLS key"); + assert_eq!( + std::fs::read_to_string(&key).expect("original key placeholder"), + "synthetic key placeholder" + ); + assert_eq!( + export(&certificate).0, + 1, + "refuse to create output at the declared certificate filename" + ); + let child = root.path().join("child"); + std::fs::create_dir(&child).expect("nested directory"); + assert_eq!( + export(&child.join("../cert.pem")).0, + 1, + "refuse an alternate spelling of the declared certificate filename" + ); + assert!(!certificate.exists()); + + let contents = std::fs::read_to_string(&assembly).expect("Envoy configuration"); + std::fs::write(&assembly, format!("{contents}\n")).expect("reformat assembly"); + assert_eq!(verify().0, 0, "whitespace remains valid JSON"); + let reformatted = std::fs::read(&routes).expect("new inventory digest"); + let changed: serde_json::Value = serde_json::from_slice(&reformatted).expect("JSON inventory"); + assert_eq!(changed["gatewayDigest"], digest(&assembly)); + assert_ne!(changed["gatewayDigest"], inventory["gatewayDigest"]); + std::fs::write(&assembly, &contents).expect("restore original assembly bytes"); + assert_eq!(verify().0, 0); + + std::fs::write( + &assembly, + contents.replacen("\"static_resources\"", "static_resources", 1), + ) + .expect("convert assembly to flow YAML"); + assert_eq!(verify().0, 1, "the checked exporter requires JSON"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + + assert!(contents.contains("/api/registry/")); + std::fs::write(&assembly, contents.replace("/api/registry/", "/api/other/")) + .expect("mutate assembled route"); + let (exit, _, _) = verify(); + assert_eq!(exit, 1); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + + let mut remote: serde_json::Value = serde_json::from_str(&contents).expect("assembly JSON"); + let clusters = remote["static_resources"]["clusters"] + .as_array_mut() + .expect("clusters"); + let registry = clusters + .iter_mut() + .find(|cluster| cluster["name"] == "registry") + .expect("BReg cluster"); + registry["load_assignment"]["endpoints"][0]["lb_endpoints"][0]["endpoint"]["address"] + ["socket_address"]["address"] = json!("192.0.2.1"); + std::fs::write(&assembly, remote.to_string()).expect("mutate upstream address"); + assert_eq!(verify().0, 1); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + + for (prefix, changed) in [ + ("page", runtime_source.replace("/apply/", "/apply;/")), + ( + "module", + runtime_source.replace("/api/functions/", "/api/functions;/"), + ), + ] { + assert_ne!(changed, runtime_source); + std::fs::write(&runtime, changed).expect("runtime with a broader route prefix"); + let (exit, _, stderr) = assemble(true); + assert_eq!(exit, 0, "{stderr}"); + assert_eq!(verify().0, 1, "refuse unsafe {prefix} path"); + assert_eq!(std::fs::read(&routes).expect("retained inventory"), first); + } +} + +#[test] +#[ignore = "requires Docker and the pinned Envoy image"] +fn envoy_validates_the_generated_standalone_configuration() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write(&runtime, standalone_runtime()).expect("runtime"); + let config = root.path().join("envoy.json"); + generate_standalone(&runtime, &config); + + let image = "envoyproxy/envoy:v1.39.6@sha256:1fde8efee875e4e4f6a39a90fe49d9338e1caacce5762034ef9fb4bbb9ad6aed"; + let mount = format!( + "type=bind,source={},target=/envoy.json,readonly", + config.display() + ); + let output = Command::new("docker") + .args([ + "run", + "--rm", + "--pull=never", + "--network=none", + "--mount", + &mount, + "--entrypoint", + "/usr/local/bin/envoy", + image, + "--mode", + "validate", + "--config-path", + "/envoy.json", + ]) + .output() + .expect("run the pinned Envoy validator"); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn generate_standalone(runtime: &std::path::Path, config: &std::path::Path) { + let output = runtime_command(runtime) + .args(["gateway", "envoy", "--standalone-out"]) + .arg(config) + .args([ + "--listen", + "127.0.0.1:8080", + "--upstream", + "registry=127.0.0.1:8100", + "--upstream", + "pages=[::1]:8200", + ]) + .output() + .expect("write complete Envoy configuration"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn standalone_generation_refuses_missing_or_undeclared_clusters_and_public_binds() { + let root = tempfile::tempdir().expect("directory"); + let runtime = root.path().join("runtime.yaml"); + std::fs::write(&runtime, standalone_runtime()).expect("runtime"); + let config = root.path().join("envoy.json"); + + for (listen, upstreams, expected) in [ + ("127.0.0.1:8080", vec!["registry=127.0.0.1:8100"], "pages"), + ( + "127.0.0.1:8080", + vec!["registry=127.0.0.1:8100", "bogus=127.0.0.1:8200"], + "configured module or page cluster", + ), + ("0.0.0.0:8080", vec![], "loopback"), + ( + "127.0.0.1:8080", + vec!["registry=127.0.0.1:8100", "registry=127.0.0.1:8101"], + "more than once", + ), + ] { + let mut command = runtime_command(&runtime); + command + .args(["gateway", "envoy", "--standalone-out"]) + .arg(&config) + .args(["--listen", listen]); + for upstream in upstreams { + command.args(["--upstream", upstream]); + } + let output = command.output().expect("run standalone generator"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + assert!(stderr.contains(expected), "{stderr}"); + assert!(!config.exists()); + } +} + +fn standalone_runtime() -> String { + include_str!("../../../products/platform/examples/session/runtime.yaml") + .replace("10.0.0.5", "127.0.0.1") + .replace( + "modules:\n", + "gateway:\n service: {host: 127.0.0.1, publicPort: 8120, checkPort: 8121}\nmodules:\n", + ) + .replace( + " audience: person\n", + " audience: person\n upstream: {cluster: registry, prefixRewrite: /}\n", + ) + .replace( + " signIn: citizen\n", + " signIn: citizen\n upstream: {cluster: pages}\n", + ) +} + /// Run `gateway envoy` on `runtime_text`, with the sentinel secrets in the /// process environment and in the file provider's directory. Returns the exit /// code, everything the command printed, and the content of every file it diff --git a/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs b/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs index f4ec322e2c..7e69792eec 100644 --- a/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs +++ b/crates/registry-thunderid-tooling/examples/journey-fixture/grant.rs @@ -5,7 +5,7 @@ use std::io::{Read, Write}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; -use registry_platform_config::{SecretProvidersConfig, SecretReference}; +use registry_platform_config::{SecretReference, StrictSecretProvidersConfig}; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::PeerPolicy; use registry_thunderid_tooling::{ @@ -31,7 +31,7 @@ struct Connection { token_endpoint: String, client_assertion_audience: String, bootstrap_resource: String, - secret_providers: SecretProvidersConfig, + secret_providers: StrictSecretProvidersConfig, clients: BTreeMap, } diff --git a/crates/registry-thunderid-tooling/src/task_connection.rs b/crates/registry-thunderid-tooling/src/task_connection.rs index 800e808cf8..be11bff5f7 100644 --- a/crates/registry-thunderid-tooling/src/task_connection.rs +++ b/crates/registry-thunderid-tooling/src/task_connection.rs @@ -9,7 +9,9 @@ use std::collections::BTreeMap; -use registry_platform_config::{ConfigBlockErrorKind, SecretProvidersConfig, SecretReference}; +use registry_platform_config::{ + ConfigBlockErrorKind, SecretReference, StrictSecretProvidersConfig, +}; use registry_platform_yaml::{ escape_pointer_segment, ApiVersion, Decoded, Diagnostic, Document, EnvelopeRule, Expect, ExternalId, FormatSpec, Reader, RemovedKey, Report, Severity, UniqueList, Url, @@ -78,7 +80,7 @@ pub(crate) struct TaskConnection { /// assertion: an absolute URI without a fragment or user information. pub(crate) bootstrap_resource: ExternalId, /// The providers that resolve each client's `assertionKeyRef`. - pub(crate) secret_providers: SecretProvidersConfig, + pub(crate) secret_providers: StrictSecretProvidersConfig, /// The registered clients, by client id: 1 to 32. A client id is 1 to /// 64 lowercase letters, digits, or `-`, since it also names the header /// file a grant is written to. @@ -454,6 +456,22 @@ clients: ); } + #[test] + fn a_task_connection_refuses_the_compose_mount_policy() { + let text = VALID.replace( + " root: /home/operator/.task-keys\n", + " root: /home/operator/.task-keys\n mountPolicy: compose-native\n", + ); + assert_ne!(text, VALID, "the member is written"); + assert_eq!( + codes(&text), + [pair( + "config.unknown-key", + "/secretProviders/file/mountPolicy" + )] + ); + } + #[test] fn endpoints_are_https_or_loopback_http_without_a_query() { for (endpoint, accepted) in [ diff --git a/deploy/examples/business-registration/.dockerignore b/deploy/examples/business-registration/.dockerignore new file mode 100644 index 0000000000..dc6492ac2c --- /dev/null +++ b/deploy/examples/business-registration/.dockerignore @@ -0,0 +1,5 @@ +* +!Dockerfile +!package.json +!package-lock.json +!host.mjs diff --git a/deploy/examples/business-registration/Dockerfile b/deploy/examples/business-registration/Dockerfile new file mode 100644 index 0000000000..a38bf67221 --- /dev/null +++ b/deploy/examples/business-registration/Dockerfile @@ -0,0 +1,7 @@ +FROM node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund +COPY host.mjs ./ +USER node +ENTRYPOINT ["node", "/app/host.mjs"] diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md new file mode 100644 index 0000000000..09e4627685 --- /dev/null +++ b/deploy/examples/business-registration/README.md @@ -0,0 +1,344 @@ +# Business registration on the Compose reference host + +Run the business-registration preview's compiled function and static page with +Registry Session, Envoy, ThunderID, BReg and PostgreSQL. The application opens +at `https://127.0.0.1:8443/apply/`. Use a disposable project and synthetic +registrars. The example uses production posture and loopback host bindings. +Product, Session and database connections use verified TLS. Two issuer hops on +internal Docker networks are plain HTTP, as described in +[Plain HTTP issuer hops](#plain-http-issuer-hops). + +The browser receives an opaque Session cookie. Envoy checks it and supplies +the registrar's access token on the private function and registry routes. +The function uses that token for the existing BReg Action. BReg applies its +own access profile, issuer, scope and row rules. The Node host has read-only +bundle files and no database or issuer credentials. + +## Plain HTTP issuer hops + +The edge terminates issuer TLS at `127.0.0.1:9443`. Behind it, two hops carry +issuer traffic as plain HTTP: + +- The edge sends issuer requests to `identity-gateway:8080` on the + `issuer-front` network. +- The identity gateway sends them to ThunderID on port 8090 on the + `identity-backend` network. ThunderID also listens on the + `identity-database` network, which it shares with PostgreSQL. + +These hops carry registrar passwords from the sign-in form, the Session client +secret, authorization codes, and access, ID and refresh tokens. The reference +accepts them because each network is internal, has only those members, and +every container drops all capabilities. The generated front gateway addresses +ThunderID by its service name, `thunderid:8090`, so the gateway cannot share +ThunderID's network namespace without putting plain ThunderID on the edge's +network. Treat any process that can join these networks as able to read issuer +traffic. A deployment across hosts needs TLS on both hops. + +Other reach is wider than the function needs: + +- The function host shares BReg's network namespace, so it can reach + `postgres:5432`. `pg_hba.conf` admits any role over TLS, including the + `postgres` superuser, from any address on the database network. +- The `ingress` network is not internal, so the Session and gateway namespace + has outbound internet access. +- The Node host accepts any well-formed bearer token on its private function + route. Any host process running as `REFERENCE_UID` can connect to the relay + sockets directly. BReg still verifies every token, so such a caller gains no + registry authority. + +## Prepare the deployment inputs + +Use Linux amd64 with Docker Engine, the Compose v2 plugin, `openssl`, `curl`, +`jq` and root access through `sudo` for the ownership step. The host test also +needs Node.js 24 with npm, and the two-person browser check needs Playwright. +Set `RECIPE` to the absolute path of this directory and prepare a fresh private +directory for `REFERENCE_CONFIG`. + +Use Registry Stack v0.51.0 or later. From v0.51.0, numbered releases ship +`registry-session` as a standalone asset beside the `rstack` installer. Stage +`breg`, `bregctl` and `registry-session` from the same release in +`REFERENCE_ARTIFACTS`, and verify each against the release manifest. + +Set these inputs in your shell and in a Compose environment file. Use absolute +paths. Set `REFERENCE_UID` and `REFERENCE_GID` if the nonroot owner of these +inputs differs from 1000. Both Envoy relays use this same UID. Run one instance +per host: the host ports 8443 and 9443 are fixed. + +| Variable | Value | +| --- | --- | +| `REFERENCE_CONFIG` | Private directory with the layout below | +| `REFERENCE_ARTIFACTS` | Directory with the verified executables | +| `BUSINESS_BUNDLE` | Build output of the business-registration preview | +| `BUSINESS_BUNDLE_SHA256` | Runtime file digest of the reviewed preview build | + +Build the preview bundle by starting the preview with `rstack dev`. Set +`PREVIEW` to the `products/platform/examples/service-previews/business-registration` +directory of the release source and `BUSINESS_BUNDLE` to a new empty directory. +The run writes its compiled preview into an `application-preview` directory +under its state directory. Copy the files before you stop the run. + +```bash +RSTACK_DEV_STATE_DIR=$(mktemp -d) +export RSTACK_DEV_STATE_DIR +(cd "$PREVIEW" && rstack dev start . --ttl 30m) | tee "$RSTACK_DEV_STATE_DIR/run.txt" +run=$(awk '$1 == "Run" {print $2}' "$RSTACK_DEV_STATE_DIR/run.txt") +built=$(find "$RSTACK_DEV_STATE_DIR" -type d -path "*$run*" -name application-preview) +static=$(jq -r .staticOutput "$built/manifest.json") +install -d "$BUSINESS_BUNDLE/functions" "$BUSINESS_BUNDLE/$static" +install -m 0644 "$built/manifest.json" "$BUSINESS_BUNDLE/" +install -m 0644 "$built/functions/register-business.mjs" "$BUSINESS_BUNDLE/functions/" +install -m 0644 "$built/$static/"{index.html,app.js,service.css} "$BUSINESS_BUNDLE/$static/" +rstack dev stop --clean "$run" +``` + +The recipe uses the bundle's `manifest.json`, `functions/register-business.mjs`, and the three files in +the manifest's `staticOutput` directory, `index.html`, `app.js` and +`service.css`. The page loads its assets by relative URL, so the same page +runs at `/` under `rstack dev` and at `/apply/` here. The digest covers each of +these five files and its relative path. Derive it once from the reviewed build, +then include that value in the instance's input file. + +```bash +bundle_host=$(docker build --quiet "$RECIPE") +docker run --rm --network none \ + --mount "type=bind,source=$BUSINESS_BUNDLE,target=/run/bundle,readonly" \ + "$bundle_host" --digest /run/bundle +``` + +Name the sealed BReg package from that preview project in both BReg inputs. +Follow the [BReg test and package steps](../../../docs/site/src/content/docs/operate/breg.mdx) +with a separate schema-test database. The reference issuer is not running yet, +so give the test runtime a static JWKS (`jwksSource.documentRef`) for a +synthetic signing key and sign the schema-test tokens with that key. Use the +same package and recorded digest +for activation and serving. Set `BREG_PACKAGE_DIGEST` in your shell from the +package receipt. + +| Path under `REFERENCE_CONFIG` | Contents | +| --- | --- | +| `app-tls/app.crt`, `app-tls/app.key` | TLS pair with an IP SAN of `127.0.0.1` | +| `issuer-tls/issuer.crt`, `issuer-tls/issuer.key` | TLS pair for `identity.reference.test` | +| `trust/https-ca.pem`, `trust/postgres-ca.pem` | Trust roots for the HTTPS and PostgreSQL certificates | +| `postgres/server.crt`, `postgres/server.key`, `postgres/bootstrap-password`, `postgres/thunderid-password` | TLS pair for DNS name `postgres`, database admin password and ThunderID database password | +| `postgres/schema/` | Four schema files from the pinned ThunderID image, staged below | +| `session/secrets/` | Owner-only `registrar-client` and `audit-key` | +| `breg/runtime/` | [Runtime configuration](breg-runtime.yaml) as `runtime.yaml`, sealed `package/`, and owner-only `secrets/` with the serving database URL, database CA, cursor key and audit key | +| `breg/admin/` | Same runtime file and package, separately staged for the explicit BReg admin commands. Also provide `admin-database-url` and the migration database URL in `secrets/`. | +| `thunderid/bootstrap.yaml` | A copy of [thunderid.yaml](thunderid.yaml), used once with writable backing stores | +| `thunderid/deployment.yaml` | The same ThunderID base plus the generated store settings, used by the issuer after setup | +| `thunderid/bootstrap-secrets/` | `DB_CONFIG_PASSWORD` and `ADMIN_PASSWORD` for the one-shot setup | +| `thunderid/secrets/` | `DB_CONFIG_PASSWORD`, `REGISTRAR_CLIENT_SECRET`, `REGISTRAR_PASSWORD`, and `SECOND_REGISTRAR_PASSWORD` for serving | +| `thunderid/resources/`, `thunderid/front-gateway/`, `thunderid/identity-receipt.json` | Output of identity generation | +| `gateway/envoy.json` | Reviewed complete Envoy configuration from the matching Session CLI | +| `gateway-checked/`, `relay/`, `breg/audit/`, `session/audit/` | Empty private directories owned by the instance UID | + +Make the three TLS pairs from one disposable CA. Keep the CA key in a private +directory outside `REFERENCE_CONFIG`, set as `REFERENCE_CA`. + +```bash +umask 077 +mkdir -p "$REFERENCE_CA" "$REFERENCE_CONFIG"/{app-tls,issuer-tls,postgres,trust} +ca="$REFERENCE_CA/reference-ca" +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 30 \ + -subj "/CN=Business registration reference CA" \ + -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign,cRLSign \ + -keyout "$ca.key" -out "$ca.pem" +issue() { # issue DIRECTORY NAME SUBJECT_ALT_NAME + openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=$2" \ + -keyout "$1/$2.key" -out "$REFERENCE_CA/$2.csr" + openssl x509 -req -in "$REFERENCE_CA/$2.csr" -CA "$ca.pem" -CAkey "$ca.key" -days 30 \ + -extfile <(printf 'subjectAltName=%s\nextendedKeyUsage=serverAuth\nbasicConstraints=critical,CA:FALSE\n' "$3") \ + -out "$1/$2.crt" +} +issue "$REFERENCE_CONFIG/app-tls" app IP:127.0.0.1 +issue "$REFERENCE_CONFIG/issuer-tls" issuer DNS:identity.reference.test +issue "$REFERENCE_CONFIG/postgres" server DNS:postgres +install -m 0644 "$ca.pem" "$REFERENCE_CONFIG/trust/https-ca.pem" +install -m 0644 "$ca.pem" "$REFERENCE_CONFIG/trust/postgres-ca.pem" +chmod 0755 "$REFERENCE_CONFIG/trust" +``` + +The Session client secret equals `REGISTRAR_CLIENT_SECRET`. Both ThunderID +`DB_CONFIG_PASSWORD` files carry the value in `postgres/thunderid-password`. +Use distinct random values for admin, both registrar passwords, database and +audit credentials. +BReg URLs target `postgres:5432`; runtime and migration use different roles and +passwords and point at the same registry database. BReg's CA file carries +`postgres-ca.pem`. Configure the local browser to resolve +`identity.reference.test` to `127.0.0.1` and trust the HTTPS CA. + +Generate the issuer inputs with the matching `rstack identity generate thunderid` +command, [identity-deployment.yaml](identity-deployment.yaml) and the registrar +role in [service.yaml](service.yaml). Use the preview's BReg project and a +host-side copy of the BReg runtime file whose package and secret-provider roots +point at the staged admin inputs. Check the runtime as a production runtime and +pin the expected issuer. The private resource files carry references to the +secret names above. + +```bash +identity_work=$(mktemp -d) +sed -e "s|/run/breg/secrets|$REFERENCE_CONFIG/breg/admin/secrets|" \ + -e "s|/run/breg/package|$REFERENCE_CONFIG/breg/admin/package|" \ + "$REFERENCE_CONFIG/breg/admin/runtime.yaml" >"$identity_work/breg-runtime.yaml" +rstack identity generate thunderid --deployment "$RECIPE/identity-deployment.yaml" \ + --breg-project "$PREVIEW/project" --breg-runtime-config "$identity_work/breg-runtime.yaml" \ + --breg-production --expected-issuer https://identity.reference.test:9443 \ + --output "$identity_work/generated" +install -d -m 0700 "$REFERENCE_CONFIG/thunderid/resources" "$REFERENCE_CONFIG/thunderid/front-gateway" +install -m 0600 "$identity_work/generated/resources/resources.yaml" "$REFERENCE_CONFIG/thunderid/resources/" +install -m 0600 "$identity_work/generated/front-gateway/envoy.yaml" "$REFERENCE_CONFIG/thunderid/front-gateway/" +install -m 0600 "$identity_work/generated/identity-receipt.json" "$REFERENCE_CONFIG/thunderid/" +``` + +Merge the generated ThunderID store settings into the serving deployment +file, retaining the supplied `server`, `jwt`, `crypto` and `database` blocks. +The generated issuer, application registration, subject claims and registrar +scope must agree with the BReg and Session files. + +Use a matching Session CLI that supports standalone TLS assembly and checked +route export. Generate the complete Envoy file from [session.yaml](session.yaml). +The gateway itself terminates app TLS at `127.0.0.1:8443`. Use +`/run/tls/app.crt` and `/run/tls/app.key` as its TLS paths and these three +distinct private first hops. + +| Session route | Upstream | Rewrite | +| --- | --- | --- | +| `/registry/businesses/` | `registry=127.0.0.1:8100` | `/` | +| `/api/functions/` | `functions=127.0.0.1:8300` | `/functions/` | +| `/apply/` | `pages=127.0.0.1:8200` | `/` | + +```bash +session=("$REFERENCE_ARTIFACTS/registry-session" --runtime-config "$RECIPE/session.yaml") +"${session[@]}" gateway envoy --posture production \ + --standalone-out "$REFERENCE_CONFIG/gateway/envoy.json" --listen 127.0.0.1:8443 \ + --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 \ + --upstream functions=127.0.0.1:8300 \ + --tls-certificate /run/tls/app.crt --tls-key /run/tls/app.key +"${session[@]}" gateway envoy --posture production \ + --verify-assembled "$REFERENCE_CONFIG/gateway/envoy.json" \ + --route-inventory-out "$REFERENCE_CONFIG/gateway/route-inventory.json" --checked-route businesses +``` + +Only the `businesses` module supplies the browser's product-client route +inventory. At startup, Compose runs the strict export for `businesses` against +a staged copy of the supplied Envoy file. It installs those exact bytes after +the export succeeds. The startup inventory is temporary. The application and +BReg share the upstream namespace. Session's check listener is in the +separate gateway namespace. The two Envoy relays connect these namespaces over +three private owner-only Unix sockets. The host app port passes TLS through to +the Session-checked gateway. + +### Set ownership and modes + +Each container reads its inputs under its own UID. Compose mounts each path +directly, so the modes of the parent directories do not matter to the +containers. + +| Paths under `REFERENCE_CONFIG` | Owner | Mode | Read by | +| --- | --- | --- | --- | +| `postgres/` and everything in it | 999:999, needs root | directories 0700, files 0600 | PostgreSQL, which refuses a key that its user does not own | +| `thunderid/bootstrap.yaml`, `thunderid/deployment.yaml`, `thunderid/resources/`, `thunderid/secrets/`, `thunderid/bootstrap-secrets/` | 10001:10001, needs root | directories 0700, files 0600 | ThunderID setup and the serving issuer | +| `trust/` | `REFERENCE_UID` | directory 0755, files 0644 | Every service, including ThunderID through `PGSSLROOTCERT` | +| Everything else | `REFERENCE_UID`:`REFERENCE_GID` | directories 0700, keys and secrets 0600 | Envoy, Session, BReg, the gateway check and the Node host | + +Apply the root-owned rows after the schema files are staged, in the next +section. + +## Start with empty state + +Set `REFERENCE_ENV` to the absolute path of the Compose environment file. +Extract the database scripts before starting +PostgreSQL. The initialization script creates only ThunderID's four databases +and applies the matching schemas as the ThunderID role. + +```bash +compose=(docker compose --project-name business-reference \ + --env-file "$REFERENCE_ENV" --file "$RECIPE/compose.yaml") + +mkdir -p "$REFERENCE_CONFIG/postgres/schema" +for schema in config:configdb entity:entitydb runtime_transient:runtime_transient runtime_persistent:runtime_persistent; do + "${compose[@]}" run -T --rm --no-deps --entrypoint cat thunderid-setup \ + "dbscripts/${schema#*:}/postgres.sql" > "$REFERENCE_CONFIG/postgres/schema/${schema%%:*}.sql" +done + +sudo chown -R 999:999 "$REFERENCE_CONFIG/postgres" +sudo chmod -R u=rwX,go= "$REFERENCE_CONFIG/postgres" +thunderid_inputs=("$REFERENCE_CONFIG"/thunderid/{bootstrap.yaml,deployment.yaml,resources,secrets,bootstrap-secrets}) +sudo chown -R 10001:10001 "${thunderid_inputs[@]}" +sudo chmod -R u=rwX,go= "${thunderid_inputs[@]}" + +"${compose[@]}" up --detach --wait postgres +"${compose[@]}" run -T --rm thunderid-setup + +"${compose[@]}" run -T --rm breg-admin provision --posture production \ + --runtime-config /run/breg/runtime.yaml --admin-url-file /run/breg/secrets/admin-database-url +"${compose[@]}" run -T --rm breg-admin apply --posture production --initial \ + --runtime-config /run/breg/runtime.yaml --package /run/breg/package \ + --expected-digest "$BREG_PACKAGE_DIGEST" + +"${compose[@]}" up --wait --wait-timeout 60 --build +"${compose[@]}" ps +``` + +The ThunderID setup job creates the built-in password flow first. The serving +issuer then loads the registrar app and two synthetic users from the generated +resources. +Before BReg starts, a one-shot checks the issuer's HTTPS discovery document and +signing keys from BReg's network namespace. +The setup containers are for fresh state. PostgreSQL data and ThunderID signing +and encryption material live in project-owned volumes. `docker compose stop` +preserves those volumes. Session state is in memory and a Session restart +requires signing in again. + +After setup, remove the bootstrap administrator password, or move it offline: +`sudo rm "$REFERENCE_CONFIG/thunderid/bootstrap-secrets/ADMIN_PASSWORD"`. + +## Check the routes + +Run `bash "$RECIPE/tests/smoke.sh" "$REFERENCE_CONFIG/trust/https-ca.pem"`. +The probe checks TLS, the issuer discovery document and administrative route +refusals, the sign-in redirect, and Session and origin refusals. Then open +`https://127.0.0.1:8443/apply/`, sign in as the disposable registrar and +register a synthetic business. The page should show its Record ID from BReg. +Verify the Record through the same BReg route and registrar session. + +For the two-person browser check, use a Playwright installation with Chromium +and set `PLAYWRIGHT_MODULE` to the absolute path of its module entry point. Set +`REFERENCE_TEST_CHROMIUM` if you use a separately installed Chromium executable. +Set `REFERENCE_TEST_PASSWORD_DIR` to a private directory containing owner-only +copies of the two synthetic registrar password files. The check pins the +fixture certificates and resolves the issuer to loopback inside Chromium. + +```bash +node "$RECIPE/tests/browser.mjs" \ + "$PLAYWRIGHT_MODULE" "$REFERENCE_CONFIG" "$REFERENCE_TEST_PASSWORD_DIR" "$BUSINESS_BUNDLE" +``` + +The test signs in two distinct registrars for the central office in separate +browser contexts with one BReg audience. Each uses the frozen page to register +a business and reads back its exact BReg Record. The test signs out the first +registrar through a top-level form and verifies that the old session cookie +is refused, the protected page asks for sign-in again, and the second registrar +can still read its Record. It checks application requests for browser-sent +Authorization headers throughout. + +## Remove the instance + +Stop the containers and remove the project's volumes, networks and the +locally built application image. Then remove the bundle digest image. + +```bash +"${compose[@]}" --profile setup down --volumes --remove-orphans --rmi local +docker image rm "$bundle_host" +``` + +The containers write into the private bind directories: audit JSONL files +under `breg/audit/` and `session/audit/`, relay sockets under `relay/`, the +checked `gateway-checked/envoy.json`, and the staged `postgres/schema/` files. +Keep the audit files if you need them, then delete `REFERENCE_CONFIG` with root, +because some files belong to UIDs 999 and 10001. Also delete `REFERENCE_CA`, +`BUSINESS_BUNDLE`, the identity work directory and the preview run's +`RSTACK_DEV_STATE_DIR`. + +Release-candidate smoke wiring, published Session and Coordinator images, +and the `rstack dev` route-parity gate are v0.52 work. diff --git a/deploy/examples/business-registration/breg-runtime.yaml b/deploy/examples/business-registration/breg-runtime.yaml new file mode 100644 index 0000000000..8717e1b804 --- /dev/null +++ b/deploy/examples/business-registration/breg-runtime.yaml @@ -0,0 +1,43 @@ +apiVersion: id.registrystack.org/formats/breg/runtime/v1alpha1 +kind: BRegRuntimeConfig +listener: + bind: 127.0.0.1:8100 + publicOrigin: https://127.0.0.1:8443/registry/businesses +identity: + environment: reference + instanceId: business-registration + databaseId: business-registration +secretProviders: + file: + root: /run/breg/secrets +database: + transport: verified-tls + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/database-ca + pool: + maximumConnections: 4 + roles: + runtime: breg_runtime + migration: breg_migration +package: + root: /run/breg/package +authentication: + oidc: + issuers: + thunderid: + issuer: https://identity.reference.test:9443 + audience: urn:example:business-register + allowedAlgorithm: RS256 + scopeClaim: scope + scopeSeparator: " " + allowedClients: [business-registrar] + maximumTokenLifetimeSeconds: 3600 + leewayMilliseconds: 30000 + authorityClaims: + principal: sub +audit: + hashKeyRef: secret:file/audit-key + path: /var/lib/breg/audit.jsonl +cursor: + secretRef: secret:file/cursor-key diff --git a/deploy/examples/business-registration/check-gateway.sh b/deploy/examples/business-registration/check-gateway.sh new file mode 100644 index 0000000000..acd8742040 --- /dev/null +++ b/deploy/examples/business-registration/check-gateway.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +reference=$2 +input=$3 +output=$4 +session=("$1" --runtime-config "$reference/session.yaml") +"${session[@]}" check --posture production --deny-warnings --identity-receipt "$reference/identity-receipt.json" + +staging=$(mktemp -d "$output/.check.XXXXXX") +candidate="$staging/envoy.json" +inventory="$staging/route-inventory.json" +trap 'rm -f -- "$candidate" "$inventory"; rmdir -- "$staging"' EXIT +cp -- "$input" "$candidate" +"${session[@]}" gateway envoy --posture production --verify-assembled "$candidate" \ + --route-inventory-out "$inventory" --checked-route businesses +if [[ ! -s "$inventory" ]]; then + printf 'Session did not produce the checked route inventory.\n' >&2 + exit 1 +fi +mv -fT -- "$candidate" "$output/envoy.json" diff --git a/deploy/examples/business-registration/compose.yaml b/deploy/examples/business-registration/compose.yaml new file mode 100644 index 0000000000..777591157f --- /dev/null +++ b/deploy/examples/business-registration/compose.yaml @@ -0,0 +1,238 @@ +x-native: &native + image: ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8 + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + +x-envoy: &envoy + image: envoyproxy/envoy:v1.39.6@sha256:1fde8efee875e4e4f6a39a90fe49d9338e1caacce5762034ef9fb4bbb9ad6aed + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + entrypoint: [envoy, --disable-hot-restart] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + +x-thunderid: &thunderid + image: ghcr.io/thunder-id/thunderid:1.0.1@sha256:d3c0613ff447a551fd440768a15bdfb6668948e80809cbb50f82d6752f22ab3e + entrypoint: [bash, /run/reference/thunderid.sh] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + tmpfs: [/tmp] + environment: + PGSSLROOTCERT: /run/trust/postgres-ca.pem + depends_on: + postgres: + condition: service_healthy + +services: + edge: + <<: *envoy + command: [-c, /run/reference/edge.yaml] + ports: + - "127.0.0.1:8443:8080" + - "127.0.0.1:9443:9443" + volumes: + - ./edge.yaml:/run/reference/edge.yaml:ro + - ${REFERENCE_CONFIG:?Set REFERENCE_CONFIG}/issuer-tls:/run/tls:ro + - ${REFERENCE_CONFIG}/relay:/run/relay:ro + networks: + ingress: + issuer: + aliases: [identity.reference.test] + issuer-front: + + upstreams: + <<: *envoy + command: [-c, /run/reference/upstreams.yaml] + volumes: + - ./upstreams.yaml:/run/reference/upstreams.yaml:ro + - ${REFERENCE_CONFIG}/relay:/run/relay + networks: [issuer, database] + + gateway-check: + <<: *native + network_mode: none + entrypoint: [bash, /run/reference/check-gateway.sh] + command: [/opt/native/registry-session, /run/reference, /run/gateway-input/envoy.json, /run/gateway] + volumes: + - ./check-gateway.sh:/run/reference/check-gateway.sh:ro + - ./session.yaml:/run/reference/session.yaml:ro + - ${REFERENCE_ARTIFACTS:?Set REFERENCE_ARTIFACTS}/registry-session:/opt/native/registry-session:ro + - ${REFERENCE_CONFIG}/gateway:/run/gateway-input:ro + - ${REFERENCE_CONFIG}/gateway-checked:/run/gateway + - ${REFERENCE_CONFIG}/thunderid/identity-receipt.json:/run/reference/identity-receipt.json:ro + + gateway: + <<: *envoy + network_mode: service:edge + command: [-c, /run/gateway/envoy.json] + volumes: + - ${REFERENCE_CONFIG}/gateway-checked:/run/gateway:ro + - ${REFERENCE_CONFIG}/app-tls:/run/tls:ro + depends_on: + gateway-check: + condition: service_completed_successfully + + session: + <<: *native + network_mode: service:edge + entrypoint: [/opt/native/registry-session] + command: [--runtime-config, /run/reference/session.yaml, --posture, production] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ./session.yaml:/run/reference/session.yaml:ro + - ${REFERENCE_ARTIFACTS}/registry-session:/opt/native/registry-session:ro + - ${REFERENCE_CONFIG}/session/secrets:/run/session-secrets:ro + - ${REFERENCE_CONFIG}/session/audit:/var/lib/session + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + + application: + build: . + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + network_mode: service:upstreams + read_only: true + init: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + environment: + BUSINESS_BUNDLE: /run/bundle + BUSINESS_BUNDLE_SHA256: ${BUSINESS_BUNDLE_SHA256:?Set BUSINESS_BUNDLE_SHA256} + volumes: + - ${BUSINESS_BUNDLE:?Set BUSINESS_BUNDLE}:/run/bundle:ro + + issuer-ready: + image: node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + network_mode: service:upstreams + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + command: [node, /run/reference/issuer-ready.mjs] + environment: + NODE_EXTRA_CA_CERTS: /run/trust/https-ca.pem + volumes: + - ./issuer-ready.mjs:/run/reference/issuer-ready.mjs:ro + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + edge: + condition: service_started + identity-gateway: + condition: service_started + thunderid: + condition: service_started + + breg: + <<: *native + network_mode: service:upstreams + entrypoint: [/opt/native/breg] + command: [--runtime-config, /run/breg/runtime.yaml, --posture, production] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ${REFERENCE_ARTIFACTS}/breg:/opt/native/breg:ro + - ${REFERENCE_CONFIG}/breg/runtime:/run/breg:ro + - ${REFERENCE_CONFIG}/breg/audit:/var/lib/breg + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + postgres: + condition: service_healthy + issuer-ready: + condition: service_completed_successfully + + breg-admin: + <<: *native + profiles: [setup] + networks: [database] + entrypoint: [/opt/native/bregctl] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ${REFERENCE_ARTIFACTS}/bregctl:/opt/native/bregctl:ro + - ${REFERENCE_CONFIG}/breg/admin:/run/breg:ro + - ${REFERENCE_CONFIG}/breg/audit:/var/lib/breg + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + postgres: + condition: service_healthy + + identity-gateway: + <<: *envoy + command: [-c, /run/identity/envoy.yaml] + volumes: + - ${REFERENCE_CONFIG}/thunderid/front-gateway:/run/identity:ro + networks: [issuer-front, identity-backend] + + thunderid: + <<: *thunderid + command: [serve] + networks: [identity-backend, identity-database] + volumes: + - &issuer-launch ./thunderid.sh:/run/reference/thunderid.sh:ro + - ${REFERENCE_CONFIG}/thunderid/deployment.yaml:/opt/thunderid/deployment.yaml:ro + - ${REFERENCE_CONFIG}/thunderid/resources:/opt/thunderid/config/resources:ro + - ${REFERENCE_CONFIG}/thunderid/secrets:/run/identity-secrets:ro + - &issuer-trust ${REFERENCE_CONFIG}/trust:/run/trust:ro + # Only the one-shot setup writes the issuer's signing and encryption material. + - issuer-certs:/opt/thunderid/config/certs:ro + - issuer-secrets:/opt/thunderid/config/secrets:ro + + thunderid-setup: + <<: *thunderid + command: [setup] + profiles: [setup] + networks: [identity-database] + volumes: + - *issuer-launch + - ${REFERENCE_CONFIG}/thunderid/bootstrap.yaml:/opt/thunderid/deployment.yaml:ro + - ${REFERENCE_CONFIG}/thunderid/bootstrap-secrets:/run/identity-secrets:ro + - *issuer-trust + - issuer-certs:/opt/thunderid/config/certs + - issuer-secrets:/opt/thunderid/config/secrets + + postgres: + image: postgres:17.11@sha256:ff87138949ad9a46f32ff23bd6852b52ce024a13dffe9b4087be98292cdd3b4f + security_opt: [no-new-privileges:true] + environment: + POSTGRES_PASSWORD_FILE: /run/postgres/bootstrap-password + command: + - postgres + - -c + - ssl=on + - -c + - ssl_cert_file=/run/postgres/server.crt + - -c + - ssl_key_file=/run/postgres/server.key + - -c + - hba_file=/run/reference/pg_hba.conf + volumes: + - postgres-data:/var/lib/postgresql/data + - ${REFERENCE_CONFIG}/postgres:/run/postgres:ro + - ./pg_hba.conf:/run/reference/pg_hba.conf:ro + - ./init-postgres.sh:/docker-entrypoint-initdb.d/10-identity.sh:ro + healthcheck: + test: [CMD, pg_isready, -h, 127.0.0.1, -U, postgres] + interval: 2s + timeout: 2s + retries: 30 + networks: [database, identity-database] + +networks: + ingress: + issuer: + internal: true + issuer-front: + internal: true + identity-backend: + internal: true + database: + internal: true + identity-database: + internal: true + +volumes: + postgres-data: + issuer-certs: + issuer-secrets: diff --git a/deploy/examples/business-registration/edge.yaml b/deploy/examples/business-registration/edge.yaml new file mode 100644 index 0000000000..9e29da5cb1 --- /dev/null +++ b/deploy/examples/business-registration/edge.yaml @@ -0,0 +1,128 @@ +static_resources: + listeners: + - name: app_tcp + address: + socket_address: {address: 0.0.0.0, port_value: 8080} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: app_tcp + cluster: app_tls + - name: issuer_https + address: + socket_address: {address: 0.0.0.0, port_value: 9443} + filter_chains: + - transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext + common_tls_context: + tls_params: {tls_minimum_protocol_version: TLSv1_2} + tls_certificates: + - certificate_chain: {filename: /run/tls/issuer.crt} + private_key: {filename: /run/tls/issuer.key} + filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: issuer_https + use_remote_address: true + normalize_path: true + merge_slashes: true + path_with_escaped_slashes_action: REJECT_REQUEST + route_config: + name: issuer + virtual_hosts: + - name: issuer + domains: ["identity.reference.test:9443"] + routes: + - match: {prefix: /} + route: {cluster: issuer_front} + http_filters: + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + # Checked Envoy reaches these three private, distinct first hops. + - name: to_registry + address: + socket_address: {address: 127.0.0.1, port_value: 8100} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: to_registry + cluster: registry_socket + - name: to_pages + address: + socket_address: {address: 127.0.0.1, port_value: 8200} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: to_pages + cluster: pages_socket + - name: to_functions + address: + socket_address: {address: 127.0.0.1, port_value: 8300} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: to_functions + cluster: functions_socket + clusters: + - name: app_tls + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: app_tls + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8443} + - name: issuer_front + type: STRICT_DNS + connect_timeout: 2s + load_assignment: + cluster_name: issuer_front + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: identity-gateway, port_value: 8080} + - name: registry_socket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: registry_socket + endpoints: + - lb_endpoints: + - endpoint: + address: + pipe: {path: /run/relay/registry.sock} + - name: pages_socket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: pages_socket + endpoints: + - lb_endpoints: + - endpoint: + address: + pipe: {path: /run/relay/pages.sock} + - name: functions_socket + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: functions_socket + endpoints: + - lb_endpoints: + - endpoint: + address: + pipe: {path: /run/relay/functions.sock} diff --git a/deploy/examples/business-registration/host.mjs b/deploy/examples/business-registration/host.mjs new file mode 100644 index 0000000000..069c4f6330 --- /dev/null +++ b/deploy/examples/business-registration/host.mjs @@ -0,0 +1,138 @@ +import { createHash } from 'node:crypto' +import { readFile, realpath } from 'node:fs/promises' +import { isAbsolute, join, relative, sep } from 'node:path' +import { pathToFileURL } from 'node:url' +import { serve } from 'srvx/node' + +const functionName = 'register-business' +const functionPath = '/functions/' + functionName +const pages = new Map([ + ['/index.html', 'text/html; charset=utf-8'], + ['/app.js', 'text/javascript; charset=utf-8'], + ['/service.css', 'text/css; charset=utf-8'], +]) + +async function readBundleFile(root, path) { + const resolved = await realpath(join(root, path)) + const location = relative(root, resolved) + if (location === '..' || location.startsWith('..' + sep) || isAbsolute(location)) { + throw new Error('A runtime file leaves the bundle.') + } + return readFile(resolved) +} + +async function readBundle(directory) { + if (!isAbsolute(directory ?? '')) throw new Error('Use an absolute preview bundle directory.') + const root = await realpath(directory) + const manifestBytes = await readBundleFile(root, 'manifest.json') + const manifest = JSON.parse(manifestBytes) + if (manifest.product?.id !== 'businesses' || manifest.product.profile !== 'business-registrar' + || !Array.isArray(manifest.functions) || manifest.functions.length !== 1 || manifest.functions[0] !== functionName + || typeof manifest.staticOutput !== 'string' || !manifest.staticOutput || isAbsolute(manifest.staticOutput)) { + throw new Error('Use the business-registration preview bundle.') + } + const modulePath = 'functions/' + functionName + '.mjs' + const files = new Map([['manifest.json', manifestBytes]]) + for (const path of [modulePath, ...Array.from(pages.keys(), name => join(manifest.staticOutput, name))]) { + files.set(path, await readBundleFile(root, path)) + } + const hashes = Array.from(files, ([path, bytes]) => [path, createHash('sha256').update(bytes).digest('hex')]) + const digest = createHash('sha256').update(JSON.stringify(hashes)).digest('hex') + return { + digest, + module: files.get(modulePath), + assets: new Map(Array.from(pages.keys(), path => [path, files.get(join(manifest.staticOutput, path))])), + } +} + +export async function bundleDigest(directory) { + return (await readBundle(directory)).digest +} + +async function requestFunction(request, handle) { + const url = new URL(request.url) + if (url.pathname !== functionPath || url.search) return new Response(null, { status: 404 }) + if (request.method !== 'POST') return new Response(null, { status: 405, headers: { allow: 'POST' } }) + // The checked Envoy route supplies the caller's bearer over private loopback. + if (!/^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '')) { + return new Response(null, { status: 401, headers: { 'cache-control': 'no-store' } }) + } + // Read through srvx's limit before the function can catch a body read error. + const body = await request.arrayBuffer() + return handle(new Request(request.url, { method: request.method, headers: request.headers, body })) +} + +function requestPage(request, assets) { + const pathname = new URL(request.url).pathname + const path = pathname === '/' ? '/index.html' : pathname + const bytes = assets.get(path) + if (!bytes) return new Response(null, { status: 404 }) + if (request.method !== 'GET' && request.method !== 'HEAD') { + return new Response(null, { status: 405, headers: { allow: 'GET, HEAD' } }) + } + return new Response(request.method === 'GET' ? bytes : null, { + headers: { + 'content-type': pages.get(path), + 'x-content-type-options': 'nosniff', + // The same policy the rstack dev preview gateway sends with the page. + 'content-security-policy': "default-src 'self'; base-uri 'none'; frame-ancestors 'none'", + }, + }) +} + +export async function startHost(directory, expectedDigest, { functionsPort = 8300, pagesPort = 8200 } = {}) { + const bundle = await readBundle(directory) + if (bundle.digest !== expectedDigest) throw new Error('The preview bundle digest differs from the deployment pin.') + // Import the bytes that were checked. The compiler emits a self-contained ESM module. + const { default: createHandler } = await import('data:text/javascript;base64,' + bundle.module.toString('base64')) + const handle = await createHandler({ products: { businesses: { baseUrl: 'http://127.0.0.1:8100' } } }) + if (typeof handle !== 'function') throw new TypeError('The compiled registration module must create a handler.') + + const options = { hostname: '127.0.0.1', silent: true, gracefulShutdown: false } + const functions = serve({ + ...options, + port: functionsPort, + maxRequestBodySize: 32_768, + fetch: request => requestFunction(request, handle), + error(error) { + if (error?.code === 'ERR_BODY_TOO_LARGE') return new Response(null, { status: 413 }) + console.error('The registration function could not complete its request.') + return new Response(null, { status: 500 }) + }, + }) + const staticPages = serve({ ...options, port: pagesPort, fetch: request => requestPage(request, bundle.assets) }) + try { + await Promise.all([functions.ready(), staticPages.ready()]) + } catch (error) { + await Promise.allSettled([functions.close(true), staticPages.close(true)]) + throw error + } + return { + functionsOrigin: new URL(functions.url).origin, + pagesOrigin: new URL(staticPages.url).origin, + close: () => Promise.all([functions.close(true), staticPages.close(true)]), + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (process.argv[2] === '--digest') { + console.log(await bundleDigest(process.argv[3])) + } else { + try { + const host = await startHost(process.env.BUSINESS_BUNDLE, process.env.BUSINESS_BUNDLE_SHA256) + const stop = () => host.close().catch(() => { + console.error('The reference host could not close its listeners.') + process.exitCode = 1 + }) + process.once('SIGINT', stop) + process.once('SIGTERM', stop) + } catch (error) { + const message = error.message === 'The preview bundle digest differs from the deployment pin.' + ? error.message + : 'The reference host could not load its checked bundle or start its private listeners.' + // The error code (for example ENOENT or EADDRINUSE) names the cause without file contents. + console.error(error?.code ? `${message} (${error.code})` : message) + process.exitCode = 1 + } + } +} diff --git a/deploy/examples/business-registration/identity-deployment.yaml b/deploy/examples/business-registration/identity-deployment.yaml new file mode 100644 index 0000000000..45e8c8c243 --- /dev/null +++ b/deploy/examples/business-registration/identity-deployment.yaml @@ -0,0 +1,30 @@ +apiVersion: id.registrystack.org/formats/platform/identity-deployment/v1 +kind: PlatformIdentityDeployment +organizationUnit: + handle: business-registration + name: Business registration +personAudience: urn:example:business-register +sessionApps: + - id: business-registrar + clientSecretRef: secret:env/REGISTRAR_CLIENT_SECRET + origin: https://127.0.0.1:8443 + redirectUris: [https://127.0.0.1:8443/session/callback] + postLogoutRedirectUris: [https://127.0.0.1:8443/session/signed-out] + products: [breg] + tokenAttributes: [registry_actor_kind, registry_office] + roles: [registrar] +users: + - id: reference-registrar + username: reference-registrar + email: reference-registrar@example.invalid + passwordRef: secret:env/REGISTRAR_PASSWORD + claims: + registry_office: central + roles: [registrar] + - id: reference-registrar-two + username: reference-registrar-two + email: reference-registrar-two@example.invalid + passwordRef: secret:env/SECOND_REGISTRAR_PASSWORD + claims: + registry_office: central + roles: [registrar] diff --git a/deploy/examples/business-registration/init-postgres.sh b/deploy/examples/business-registration/init-postgres.sh new file mode 100755 index 0000000000..97420da574 --- /dev/null +++ b/deploy/examples/business-registration/init-postgres.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +THUNDERID_DB_PASSWORD=$(&2 + exit 1 +fi +export THUNDERID_DB_PASSWORD +psql --username postgres --dbname postgres --set ON_ERROR_STOP=1 <<'SQL' +SET log_min_error_statement = panic; +\getenv thunderid_password THUNDERID_DB_PASSWORD +CREATE ROLE thunderid LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD :'thunderid_password'; +CREATE DATABASE thunderid_config OWNER thunderid; +CREATE DATABASE thunderid_runtime_transient OWNER thunderid; +CREATE DATABASE thunderid_entity OWNER thunderid; +CREATE DATABASE thunderid_runtime_persistent OWNER thunderid; +REVOKE CONNECT ON DATABASE thunderid_config, thunderid_runtime_transient, thunderid_entity, thunderid_runtime_persistent FROM PUBLIC; +SQL +unset THUNDERID_DB_PASSWORD + +for database in config entity runtime_transient runtime_persistent; do + psql --username postgres --dbname "thunderid_$database" --set ON_ERROR_STOP=1 \ + --command 'SET ROLE thunderid' --file "/run/postgres/schema/$database.sql" +done diff --git a/deploy/examples/business-registration/issuer-ready.mjs b/deploy/examples/business-registration/issuer-ready.mjs new file mode 100644 index 0000000000..46c931385b --- /dev/null +++ b/deploy/examples/business-registration/issuer-ready.mjs @@ -0,0 +1,34 @@ +import { setTimeout as pause } from 'node:timers/promises' + +const issuer = 'https://identity.reference.test:9443' +const jwksUrl = issuer + '/oauth2/jwks' + +async function get(url) { + const response = await fetch(url, { signal: AbortSignal.timeout(1500), redirect: 'error' }) + if (!response.ok) throw new Error('HTTP ' + response.status) + return response.json() +} + +async function waitForIssuer() { + const deadline = Date.now() + 30_000 + let failure + do { + try { + const discovery = await get(issuer + '/.well-known/openid-configuration') + if (discovery.issuer === issuer && discovery.jwks_uri === jwksUrl) { + const { keys } = await get(jwksUrl) + if (Array.isArray(keys) && keys.length > 0) return true + failure = 'signing keys missing' + } else { + failure = 'unexpected discovery metadata' + } + } catch (error) { + failure = error.cause?.code ?? error.name + } + await pause(500) + } while (Date.now() < deadline) + console.error('The reference issuer did not become ready: ' + failure) + return false +} + +if (!(await waitForIssuer())) process.exitCode = 1 diff --git a/deploy/examples/business-registration/package-lock.json b/deploy/examples/business-registration/package-lock.json new file mode 100644 index 0000000000..d2a97cca06 --- /dev/null +++ b/deploy/examples/business-registration/package-lock.json @@ -0,0 +1,28 @@ +{ + "name": "registry-business-registration-reference", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "registry-business-registration-reference", + "dependencies": { + "srvx": "1.0.8" + }, + "engines": { + "node": ">=24 <25" + } + }, + "node_modules/srvx": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/srvx/-/srvx-1.0.8.tgz", + "integrity": "sha512-ngFS/J6St4PJfHRHGjr78xkPPtbyXtdMOLNE4x/XZunEK3OhV7aGUWMHf9WTUEy6wm1U0W4okkd82ZFFWRVQTw==", + "license": "MIT", + "bin": { + "srvx": "bin/srvx.mjs" + }, + "engines": { + "node": ">=20.16.0" + } + } + } +} diff --git a/deploy/examples/business-registration/package.json b/deploy/examples/business-registration/package.json new file mode 100644 index 0000000000..5816515a72 --- /dev/null +++ b/deploy/examples/business-registration/package.json @@ -0,0 +1,7 @@ +{ + "name": "registry-business-registration-reference", + "private": true, + "engines": { "node": ">=24 <25" }, + "dependencies": { "srvx": "1.0.8" }, + "scripts": { "test": "node --test tests/host.test.mjs" } +} diff --git a/deploy/examples/business-registration/pg_hba.conf b/deploy/examples/business-registration/pg_hba.conf new file mode 100644 index 0000000000..1a2304cecb --- /dev/null +++ b/deploy/examples/business-registration/pg_hba.conf @@ -0,0 +1,3 @@ +local all all peer +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::/0 scram-sha-256 diff --git a/deploy/examples/business-registration/service.yaml b/deploy/examples/business-registration/service.yaml new file mode 100644 index 0000000000..ae754caf1b --- /dev/null +++ b/deploy/examples/business-registration/service.yaml @@ -0,0 +1,9 @@ +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +# Identity generation reads these roles beside identity-deployment.yaml. They +# match the business-registration preview's own service.yaml. +roles: + registrar: + actorKind: human + claims: [registry_office] + accessProfiles: {breg: [business-registrar]} diff --git a/deploy/examples/business-registration/session.yaml b/deploy/examples/business-registration/session.yaml new file mode 100644 index 0000000000..8e9d433af8 --- /dev/null +++ b/deploy/examples/business-registration/session.yaml @@ -0,0 +1,54 @@ +apiVersion: id.registrystack.org/formats/platform/session-runtime/v1alpha1 +kind: PlatformSessionRuntimeConfig +listener: + bind: 127.0.0.1:8120 + tlsTermination: operator-controlled-upstream +checkListener: 127.0.0.1:8121 +publicOrigin: https://127.0.0.1:8443 +secretProviders: + file: + root: /run/session-secrets +issuer: + id: https://identity.reference.test:9443 + authorization: https://identity.reference.test:9443/oauth2/authorize + endSession: https://identity.reference.test:9443/oauth2/logout + token: https://identity.reference.test:9443/oauth2/token + revocation: https://identity.reference.test:9443/oauth2/revoke + jwks: https://identity.reference.test:9443/oauth2/jwks +personAudience: urn:example:business-register +gateway: + service: + host: 127.0.0.1 + publicPort: 8120 + checkPort: 8121 +modules: + - id: businesses + product: breg + prefix: /registry/businesses/ + audience: person + signIns: [registrar] + upstream: + cluster: registry + prefixRewrite: / + - id: functions + product: breg + prefix: /api/functions/ + audience: person + signIns: [registrar] + upstream: + cluster: functions + prefixRewrite: /functions/ +pages: + - prefix: /apply/ + signIn: registrar + upstream: + cluster: pages + prefixRewrite: / +signIns: + registrar: + clientId: business-registrar + clientSecretRef: secret:file/registrar-client + scopes: [registry:business:register] +audit: + hashKeyRef: secret:file/audit-key + path: /var/lib/session/audit.jsonl diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs new file mode 100644 index 0000000000..e2a7a5a043 --- /dev/null +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -0,0 +1,207 @@ +import assert from 'node:assert/strict' +import { createHash, randomUUID, X509Certificate } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { isAbsolute, join } from 'node:path' +import { pathToFileURL } from 'node:url' + +const [playwright, config, passwords, bundle] = process.argv.slice(2) +if (![playwright, config, passwords, bundle].every(path => path && isAbsolute(path))) { + throw new Error('Pass absolute paths to the Playwright module, reference inputs, test passwords, and frozen bundle.') +} + +const origin = 'https://127.0.0.1:8443' +const issuer = 'https://identity.reference.test:9443' +const apply = origin + '/apply/' +const cookieName = '__Host-registry-session' +const accessProfile = 'business-registrar' +const registrars = [ + { username: 'reference-registrar', password: 'REGISTRAR_PASSWORD' }, + { username: 'reference-registrar-two', password: 'SECOND_REGISTRAR_PASSWORD' }, +] +const identity = JSON.parse(await readFile(join(config, 'thunderid', 'identity-receipt.json'), 'utf8')) +const pins = await Promise.all(['app', 'issuer'].map(async name => { + const certificate = new X509Certificate(await readFile(join(config, name + '-tls', name + '.crt'))) + return createHash('sha256').update(certificate.publicKey.export({ type: 'spki', format: 'der' })).digest('base64') +})) +const { chromium } = await import(pathToFileURL(playwright)) +const browser = await chromium.launch({ + executablePath: process.env.REFERENCE_TEST_CHROMIUM, + args: [ + '--host-resolver-rules=MAP identity.reference.test 127.0.0.1', + '--no-proxy-server', + '--ignore-certificate-errors-spki-list=' + pins.join(','), + ], +}) +const authorizationHeaders = [] + +async function startRegistrar(person) { + const context = await browser.newContext() + const page = await context.newPage() + page.setDefaultTimeout(15_000) + page.on('request', request => { + if (new URL(request.url()).origin === origin) authorizationHeaders.push(request.headerValue('authorization')) + }) + await page.goto(apply) + await page.waitForURL(url => url.origin === issuer) + await page.getByRole('textbox', { name: /username/i }).fill(person.username) + await page.locator('input[type=password]').fill((await readFile(join(passwords, person.password), 'utf8')).trim()) + await page.getByRole('button', { name: /sign in/i }).click() + await page.waitForURL(apply) + const { signIn, claims } = await sessionIdentity(page) + assert.equal(signIn, 'registrar') + assert.ok(typeof claims?.sub === 'string' && claims.sub.length > 0) + assert.equal(claims.sub, identity.users[person.username].sub) + return { context, page, subject: claims.sub } +} + +async function sessionIdentity(page) { + return page.evaluate(async () => { + const response = await fetch('/session/me') + return response.ok ? response.json() : {} + }) +} + +async function checkAssets(page) { + const manifest = JSON.parse(await readFile(join(bundle, 'manifest.json'), 'utf8')) + const assets = {} + for (const [file, suffix] of [['index.html', ''], ['app.js', 'app.js'], ['service.css', 'service.css']]) { + const expected = createHash('sha256').update(await readFile(join(bundle, manifest.staticOutput, file))).digest('hex') + const actual = await page.evaluate(async path => { + const response = await fetch(path) + const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', await response.arrayBuffer())) + return { status: response.status, digest: Array.from(hash, byte => byte.toString(16).padStart(2, '0')).join('') } + }, '/apply/' + suffix) + assert.equal(actual.status, 200) + assert.equal(actual.digest, expected) + assets[file] = actual.digest + } + return assets +} + +async function register(page, name) { + const legalName = 'Synthetic business for ' + name + const registrationNumber = 'LOGOUT-' + randomUUID().slice(0, 8) + await page.locator('#legal-name').fill(legalName) + await page.locator('#registration-number').fill(registrationNumber) + const response = page.waitForResponse(item => + item.url() === origin + '/api/functions/register-business' && item.request().method() === 'POST') + await page.getByRole('button', { name: 'Register business', exact: true }).click() + const submitted = await response + assert.equal(submitted.status(), 200) + const { recordId } = await submitted.json() + assert.match(recordId, /^[0-9a-f-]{36}$/i) + await page.getByRole('heading', { name: 'Business registered' }).waitFor() + assert.equal(await page.locator('#record-id').textContent(), recordId) + return { recordId, legalName, registrationNumber, registeringOffice: 'central' } +} + +function recordPath(recordId) { + return '/registry/businesses/v1/records/businesses/' + encodeURIComponent(recordId) +} + +async function readRecord(page, recordId) { + return page.evaluate(async ({ path, profile }) => { + const response = await fetch(path, { + cache: 'no-store', + headers: { 'Registry-Client': 'page', 'Registry-Access-Profile': profile }, + }) + return { status: response.status, body: await response.json() } + }, { path: recordPath(recordId), profile: accessProfile }) +} + +async function navigateToRecord(page, recordId) { + // The signed-out document's CSP forbids fetch. Navigate with the same page binding instead. + await page.setExtraHTTPHeaders({ + 'Registry-Client': 'page', + 'Registry-Access-Profile': accessProfile, + 'Cache-Control': 'no-cache', + }) + try { + return await page.goto(origin + recordPath(recordId)) + } finally { + await page.setExtraHTTPHeaders({}) + } +} + +async function assertOwnRecord(page, expected) { + const { status, body } = await readRecord(page, expected.recordId) + assert.equal(status, 200) + const { recordId, domainData } = body.data + const { legalName, registrationNumber, registeringOffice } = domainData + assert.deepEqual({ recordId, legalName, registrationNumber, registeringOffice }, expected) +} + +async function signOut(page) { + stage = 'submit the first registrar sign-out form' + const response = page.waitForResponse(item => + item.url() === origin + '/session/sign-out' && item.request().method() === 'POST') + // The frozen page is unchanged. Submit a top-level form as a service's own page would. + await page.evaluate(() => { + const form = document.createElement('form') + form.method = 'post' + form.action = '/session/sign-out' + const button = document.createElement('button') + button.textContent = 'Sign out for acceptance test' + form.append(button) + document.body.append(form) + }) + await page.getByRole('button', { name: 'Sign out for acceptance test' }).click() + assert.equal((await response).status(), 303) + stage = 'return from the issuer to the signed-out page' + await page.waitForURL(origin + '/session/signed-out') +} + +let stage = 'sign in two registrars' +let report +try { + const first = await startRegistrar(registrars[0]) + const second = await startRegistrar(registrars[1]) + assert.notEqual(first.subject, second.subject) + stage = 'verify assets and register both businesses' + const assetSha256 = await checkAssets(first.page) + const firstRecord = await register(first.page, registrars[0].username) + const secondRecord = await register(second.page, registrars[1].username) + assert.notEqual(firstRecord.recordId, secondRecord.recordId) + + stage = 'verify both exact BReg readbacks' + await assertOwnRecord(first.page, firstRecord) + await assertOwnRecord(second.page, secondRecord) + + stage = 'sign out the first registrar and refuse its old session' + const cookie = (await first.context.cookies(origin)).find(item => item.name === cookieName) + assert.ok(cookie?.secure && cookie.httpOnly) + await signOut(first.page) + stage = 'refuse the first registrar without a session cookie' + assert.ok(!(await first.context.cookies(origin)).some(item => item.name === cookieName)) + assert.equal((await navigateToRecord(first.page, firstRecord.recordId)).status(), 401) + stage = 'refuse the first registrar with the stale cookie' + await first.context.addCookies([cookie]) + const stale = await navigateToRecord(first.page, firstRecord.recordId) + const sentCookie = await stale.request().headerValue('cookie') + assert.ok(sentCookie?.split(';').some(item => item.trim() === cookie.name + '=' + cookie.value)) + assert.equal(stale.status(), 401) + assert.equal(await stale.headerValue('registry-session-answer'), '1') + assert.equal((await stale.json()).code, 'session.expired') + stage = 'require a new issuer sign-in for the protected page' + await first.page.goto(apply) + await first.page.waitForURL(url => url.origin === issuer) + await first.page.getByRole('textbox', { name: /username/i }).waitFor() + + stage = 'verify that the second registrar is still signed in' + assert.equal((await sessionIdentity(second.page)).claims?.sub, second.subject) + await assertOwnRecord(second.page, secondRecord) + assert.ok((await Promise.all(authorizationHeaders)).every(value => value === null)) + report = { + distinctSubjects: true, separateContexts: true, assetSha256, formSubmissions: [200, 200], + owningRecordReads: [200, 200], + first: { signOut: 303, recordAfterSignOut: 401, staleCookieSent: true, staleCookie: 401, signInRequired: true }, + second: { sameSubjectAfterFirstSignOut: true, owningRead: 200 }, + noBrowserAuthorizationHeader: true, + } +} catch (error) { + console.error('Reference browser test stopped at ' + stage + ' (' + error.name + ').') + process.exitCode = 1 +} finally { + await browser.close() +} +if (report) console.log(JSON.stringify(report, null, 2)) diff --git a/deploy/examples/business-registration/tests/host.test.mjs b/deploy/examples/business-registration/tests/host.test.mjs new file mode 100644 index 0000000000..4accdddacc --- /dev/null +++ b/deploy/examples/business-registration/tests/host.test.mjs @@ -0,0 +1,73 @@ +import assert from 'node:assert/strict' +import { mkdtemp, mkdir, writeFile, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { bundleDigest, startHost } from '../host.mjs' + +async function fixture(t) { + const root = await mkdtemp(join(tmpdir(), 'reference-host-test-')) + t.after(() => rm(root, { recursive: true })) + await mkdir(join(root, 'functions')) + await mkdir(join(root, 'project/web/dist'), { recursive: true }) + const manifest = { + product: { id: 'businesses', profile: 'business-registrar' }, + functions: ['register-business'], + staticOutput: 'project/web/dist', + } + await writeFile(join(root, 'manifest.json'), JSON.stringify(manifest)) + await writeFile(join(root, 'functions/register-business.mjs'), ` + export default ({ products }) => request => { + if (products.businesses.baseUrl !== 'http://127.0.0.1:8100') throw new Error('Wrong upstream') + return Response.json({ caller: request.headers.get('authorization') === 'Bearer synthetic.caller.token' }) + } + `) + for (const name of ['index.html', 'app.js', 'service.css']) { + await writeFile(join(root, 'project/web/dist', name), name) + } + return root +} + +test('loads the checked bundle and serves only the declared function and page assets', async t => { + const root = await fixture(t) + const host = await startHost(root, await bundleDigest(root), { functionsPort: 0, pagesPort: 0 }) + t.after(host.close) + const route = host.functionsOrigin + '/functions/register-business' + const headers = { authorization: 'Bearer synthetic.caller.token' } + + assert.equal((await fetch(route, { method: 'POST' })).status, 401) + assert.equal((await fetch(route, { method: 'POST', headers: { authorization: 'Bearer a, Bearer b' } })).status, 401) + assert.equal((await fetch(route, { headers })).status, 405) + assert.equal((await fetch(route + '?unexpected=true', { method: 'POST', headers })).status, 404) + assert.deepEqual(await (await fetch(route, { method: 'POST', headers })).json(), { caller: true }) + assert.equal((await fetch(route, { method: 'POST', headers, body: 'x'.repeat(32_769) })).status, 413) + + const page = await fetch(host.pagesOrigin) + assert.equal((await page.text()), 'index.html') + assert.equal(page.headers.get('content-type'), 'text/html; charset=utf-8') + assert.equal(page.headers.get('x-content-type-options'), 'nosniff') + assert.equal( + page.headers.get('content-security-policy'), + "default-src 'self'; base-uri 'none'; frame-ancestors 'none'", + ) + assert.equal((await fetch(host.pagesOrigin + '/app.js', { method: 'HEAD' })).status, 200) + assert.equal((await fetch(host.pagesOrigin + '/app.js', { method: 'POST' })).status, 405) + for (const path of ['/manifest.json', '/functions/register-business.mjs', '/project/web/dist/index.html']) { + assert.equal((await fetch(host.pagesOrigin + path)).status, 404) + } +}) + +test('refuses changed bundles before importing function code', async t => { + const root = await fixture(t) + const expected = await bundleDigest(root) + await writeFile(join(root, 'functions/register-business.mjs'), 'throw new Error("never import this")') + await assert.rejects(startHost(root, expected), /bundle digest differs/) +}) + +test('refuses files that resolve outside the bundle', async t => { + const root = await fixture(t) + const file = join(root, 'project/web/dist/app.js') + await rm(file) + await symlink('/etc/hosts', file) + await assert.rejects(bundleDigest(root), /leaves the bundle/) +}) diff --git a/deploy/examples/business-registration/tests/smoke.sh b/deploy/examples/business-registration/tests/smoke.sh new file mode 100755 index 0000000000..e23a23bc9c --- /dev/null +++ b/deploy/examples/business-registration/tests/smoke.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +ca=${1:?Pass the HTTPS CA file for the disposable reference stack.} +app=https://127.0.0.1:8443 +issuer=https://identity.reference.test:9443 +http=(curl --silent --show-error --noproxy '*' --cacert "$ca" --max-time 10) +identity=("${http[@]}" --resolve identity.reference.test:9443:127.0.0.1) + +expect_status() { + local expected=$1 status + shift + status=$("$@" --output /dev/null --write-out '%{http_code}') + if [[ "$status" != "$expected" ]]; then + printf 'Expected HTTP %s, received %s.\n' "$expected" "$status" >&2 + exit 1 + fi +} + +"${identity[@]}" --fail "$issuer/.well-known/openid-configuration" | + jq -e --arg issuer "$issuer" '.issuer == $issuer' >/dev/null +expect_status 404 "${identity[@]}" "$issuer/applications" +expect_status 403 "${identity[@]}" -H 'X-HTTP-Method-Override: GET' "$issuer/.well-known/openid-configuration" +expect_status 302 "${http[@]}" "$app/apply/" +expect_status 401 "${http[@]}" -H 'Registry-Client: page' "$app/registry/businesses/v1/records/businesses" +function_call=("${http[@]}" -X POST -H 'Registry-Client: page' -H "Origin: $app" + -H 'Authorization: Bearer synthetic.browser.value' "$app/api/functions/register-business") +expect_status 401 "${function_call[@]}" +"${function_call[@]}" | jq -e '.code == "session.expired"' >/dev/null +expect_status 403 "${http[@]}" -X POST -H 'Registry-Client: page' -H "Origin: $issuer" \ + "$app/api/functions/register-business" +expect_status 404 "${http[@]}" "$app/check/businesses" +printf 'HTTPS issuer, private routes, signed-in page redirect and session refusals passed.\n' diff --git a/deploy/examples/business-registration/tests/test_compose.py b/deploy/examples/business-registration/tests/test_compose.py new file mode 100644 index 0000000000..e27d87d98a --- /dev/null +++ b/deploy/examples/business-registration/tests/test_compose.py @@ -0,0 +1,103 @@ +"""Check the reference's published listeners and private service boundaries.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import unittest + + +EXAMPLE = Path(__file__).resolve().parents[1] +DOCKER = shutil.which("docker") + + +@unittest.skipUnless(DOCKER, "Docker Compose is needed to render the reference") +class ComposeReference(unittest.TestCase): + @classmethod + def setUpClass(cls): + if subprocess.run([DOCKER, "compose", "version"], capture_output=True).returncode: + raise unittest.SkipTest("The Docker Compose plugin is unavailable") + env = dict(os.environ, REFERENCE_CONFIG="/reference/config", REFERENCE_ARTIFACTS="/reference/bin", + BUSINESS_BUNDLE="/reference/bundle", BUSINESS_BUNDLE_SHA256="0" * 64) + rendered = subprocess.run( + [DOCKER, "compose", "-f", str(EXAMPLE / "compose.yaml"), "--profile", "setup", + "config", "--format", "json"], env=env, check=True, capture_output=True, text=True, + ) + cls.compose = json.loads(rendered.stdout) + cls.services = cls.compose["services"] + + def test_only_the_loopback_edge_publishes_ports(self): + bindings = {name: service["ports"] for name, service in self.services.items() if service.get("ports")} + self.assertEqual(list(bindings), ["edge"]) + self.assertEqual( + {(row["host_ip"], row["published"], row["target"]) for row in bindings["edge"]}, + {("127.0.0.1", "8443", 8080), ("127.0.0.1", "9443", 9443)}, + ) + + def test_credential_endpoints_and_plaintext_hops_are_separate(self): + self.assertEqual(self.services["gateway"]["network_mode"], "service:edge") + self.assertEqual(self.services["session"]["network_mode"], "service:edge") + self.assertEqual(self.services["application"]["network_mode"], "service:upstreams") + self.assertEqual(self.services["breg"]["network_mode"], "service:upstreams") + backend = set(self.services["thunderid"]["networks"]) + self.assertTrue(backend.isdisjoint(self.services["upstreams"]["networks"])) + self.assertTrue(backend.isdisjoint(self.services["edge"]["networks"])) + self.assertTrue(set(self.services["identity-gateway"]["networks"]).isdisjoint( + self.services["upstreams"]["networks"] + )) + self.assertEqual(set(self.services["postgres"]["networks"]), {"database", "identity-database"}) + self.assertEqual(set(self.compose["volumes"]), {"issuer-certs", "issuer-secrets", "postgres-data"}) + + def test_checked_snapshot_and_bundle_are_read_only_in_consumers(self): + gateway = self.services["gateway"] + self.assertEqual(gateway["depends_on"]["gateway-check"]["condition"], "service_completed_successfully") + self.assertEqual(gateway["command"], ["-c", "/run/gateway/envoy.json"]) + self.assertEqual(self.services["gateway-check"]["command"][-2:], [ + "/run/gateway-input/envoy.json", "/run/gateway", + ]) + self.assertEqual(self.services["gateway-check"]["network_mode"], "none") + checked = next(mount for mount in gateway["volumes"] if mount["target"] == "/run/gateway") + self.assertEqual(checked["source"], "/reference/config/gateway-checked") + self.assertTrue(checked["read_only"]) + app = self.services["application"] + self.assertEqual([mount["target"] for mount in app["volumes"]], ["/run/bundle"]) + self.assertTrue(app["volumes"][0]["read_only"]) + self.assertEqual(app["environment"]["BUSINESS_BUNDLE_SHA256"], "0" * 64) + + def test_one_shots_keep_bootstrap_authority_out_of_serving_mounts(self): + for name in ("breg-admin", "thunderid-setup"): + self.assertEqual(self.services[name]["profiles"], ["setup"]) + boot = self.services["thunderid-setup"]["volumes"] + serve = self.services["thunderid"]["volumes"] + self.assertTrue(any("bootstrap-secrets" in mount["source"] for mount in boot)) + self.assertFalse(any("bootstrap-secrets" in mount["source"] for mount in serve)) + self.assertFalse(any("/config/resources" in mount["target"] for mount in boot)) + self.assertFalse(any("/breg/admin" in mount["source"] for mount in self.services["breg"]["volumes"])) + + def test_only_issuer_setup_writes_signing_material(self): + def issuer_volumes(name): + return {mount["source"]: mount.get("read_only", False) + for mount in self.services[name]["volumes"] if mount["type"] == "volume"} + self.assertEqual(issuer_volumes("thunderid"), {"issuer-certs": True, "issuer-secrets": True}) + self.assertEqual(issuer_volumes("thunderid-setup"), {"issuer-certs": False, "issuer-secrets": False}) + + def test_every_service_refuses_new_privileges(self): + for name, service in self.services.items(): + self.assertIn("no-new-privileges:true", service.get("security_opt", []), name) + + def test_breg_waits_for_the_issuer_from_its_own_namespace(self): + readiness = self.services["issuer-ready"] + self.assertEqual(readiness["network_mode"], self.services["breg"]["network_mode"]) + self.assertEqual( + self.services["breg"]["depends_on"]["issuer-ready"]["condition"], "service_completed_successfully" + ) + self.assertTrue(all(mount["read_only"] for mount in readiness["volumes"])) + + def test_browser_registrars_have_separate_passwords_for_the_supported_office(self): + users = (EXAMPLE / "identity-deployment.yaml").read_text().split("\nusers:\n", 1)[1] + first, second = users.split(" - id: reference-registrar-two\n") + self.assertIn("secret:env/REGISTRAR_PASSWORD", first) + self.assertIn("registry_office: central", first) + self.assertIn("secret:env/SECOND_REGISTRAR_PASSWORD", second) + self.assertIn("registry_office: central", second) diff --git a/deploy/examples/business-registration/tests/test_gateway_check.py b/deploy/examples/business-registration/tests/test_gateway_check.py new file mode 100644 index 0000000000..5744eb134e --- /dev/null +++ b/deploy/examples/business-registration/tests/test_gateway_check.py @@ -0,0 +1,81 @@ +"""Exercise the gateway one-shot with a stand-in for the Session CLI.""" + +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory +import unittest + + +EXAMPLE = Path(__file__).resolve().parents[1] + + +class GatewayCheck(unittest.TestCase): + def setUp(self): + self.root = Path(self.enterContext(TemporaryDirectory())) + self.input = self.root / "envoy.json" + self.input.write_bytes(b'{"candidate":true}\n') + self.output = self.root / "checked" + self.output.mkdir() + self.installed = self.output / "envoy.json" + self.installed.write_bytes(b'{"previous":true}\n') + self.session = self.root / "registry-session" + self.session.write_text("""#!/usr/bin/env python3 +import os +from pathlib import Path +import sys + +root = Path(__file__).parent +runtime = root / "session.yaml" +identity = root / "identity-receipt.json" +assert sys.argv[1:3] == ["--runtime-config", str(runtime)] +args = sys.argv[3:] +if args[0] == "check": + assert args == [ + "check", "--posture", "production", "--deny-warnings", "--identity-receipt", str(identity), + ] + sys.exit(0) + +assert args[:5] == ["gateway", "envoy", "--posture", "production", "--verify-assembled"] +assert args[6] == "--route-inventory-out" +assert args[8:] == ["--checked-route", "businesses"] +staged, inventory = Path(args[5]), Path(args[7]) +source = root / "envoy.json" +assert staged != source and staged.read_bytes() == source.read_bytes() +assert staged.parent == inventory.parent and not inventory.exists() +outcome = os.environ["EXPORT_OUTCOME"] +if outcome == "refused": + sys.exit(1) +if outcome == "accepted": + inventory.write_text("{}") + source.write_text("changed after staging") +""") + self.session.chmod(0o700) + + def run_check(self, outcome): + return subprocess.run( + ["bash", str(EXAMPLE / "check-gateway.sh"), str(self.session), + str(self.root), str(self.input), str(self.output)], + capture_output=True, text=True, env=dict(os.environ, EXPORT_OUTCOME=outcome), + ) + + def test_installs_exact_bytes_checked_by_strict_export(self): + original = self.input.read_bytes() + result = self.run_check("accepted") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotEqual(self.input.read_bytes(), original) + self.assertEqual(self.installed.read_bytes(), original) + self.assertEqual(list(self.output.iterdir()), [self.installed]) + + def test_retains_installed_bytes_when_strict_export_refuses(self): + result = self.run_check("refused") + self.assertEqual(result.returncode, 1, result.stderr) + self.assertEqual(self.installed.read_bytes(), b'{"previous":true}\n') + self.assertEqual(list(self.output.iterdir()), [self.installed]) + + def test_requires_export_output_before_installing(self): + result = self.run_check("no-inventory") + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("route inventory", result.stderr) + self.assertEqual(self.installed.read_bytes(), b'{"previous":true}\n') + self.assertEqual(list(self.output.iterdir()), [self.installed]) diff --git a/deploy/examples/business-registration/tests/test_host_node.py b/deploy/examples/business-registration/tests/test_host_node.py new file mode 100644 index 0000000000..2130488aa2 --- /dev/null +++ b/deploy/examples/business-registration/tests/test_host_node.py @@ -0,0 +1,35 @@ +"""Run the Node reference host's own tests from the deployment suite.""" + +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +EXAMPLE = Path(__file__).resolve().parents[1] +NODE = shutil.which("node") +NPM = shutil.which("npm") + + +@unittest.skipUnless(NODE and NPM, "Node.js and npm are needed to test the reference host") +class ReferenceHost(unittest.TestCase): + def test_host_node_suite_passes(self): + # Install the locked dependencies in a scratch copy so the recipe stays unchanged. + with tempfile.TemporaryDirectory(prefix="reference-host-") as scratch: + work = Path(scratch) + for name in ("package.json", "package-lock.json", "host.mjs"): + shutil.copy2(EXAMPLE / name, work / name) + shutil.copytree(EXAMPLE / "tests", work / "tests") + for command in ( + [NPM, "ci", "--ignore-scripts", "--no-audit", "--no-fund"], + [NPM, "test"], + ): + result = subprocess.run(command, cwd=work, capture_output=True, text=True) + self.assertEqual( + result.returncode, 0, f"{' '.join(command[1:])} failed:\n{result.stdout}\n{result.stderr}" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/examples/business-registration/tests/test_page_assets.py b/deploy/examples/business-registration/tests/test_page_assets.py new file mode 100644 index 0000000000..07882eb1f9 --- /dev/null +++ b/deploy/examples/business-registration/tests/test_page_assets.py @@ -0,0 +1,34 @@ +"""Check that the preview page this recipe serves under /apply/ loads its own assets.""" + +from html.parser import HTMLParser +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[4] +PAGE = ROOT / "products/platform/examples/service-previews/business-registration/web/public/index.html" + + +class AssetReferences(HTMLParser): + def __init__(self): + super().__init__() + self.references = [] + + def handle_starttag(self, tag, attrs): + values = dict(attrs) + if tag == "link" and values.get("rel") == "stylesheet": + self.references.append(values["href"]) + elif tag == "script" and "src" in values: + self.references.append(values["src"]) + + +class PreviewPageAssets(unittest.TestCase): + def test_page_assets_resolve_under_any_page_route(self): + # rstack dev serves the page at / and the Session page route serves it at /apply/. + parser = AssetReferences() + parser.feed(PAGE.read_text(encoding="utf-8")) + self.assertEqual(sorted(parser.references), ["app.js", "service.css"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/examples/business-registration/thunderid.sh b/deploy/examples/business-registration/thunderid.sh new file mode 100644 index 0000000000..2383b04cea --- /dev/null +++ b/deploy/examples/business-registration/thunderid.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -euo pipefail + +read_secret() { + local name=$1 value + value=$(<"/run/identity-secrets/$name") + if [[ -z "$value" ]]; then + printf 'Missing ThunderID input %s.\n' "$name" >&2 + exit 1 + fi + printf -v "$name" '%s' "$value" + export "${name?}" +} + +read_secret DB_CONFIG_PASSWORD +export DB_RUNTIME_TRANSIENT_PASSWORD="$DB_CONFIG_PASSWORD" +export DB_ENTITY_PASSWORD="$DB_CONFIG_PASSWORD" +export DB_RUNTIME_PERSISTENT_PASSWORD="$DB_CONFIG_PASSWORD" + +case "${1:-}" in + serve) + read_secret REGISTRAR_CLIENT_SECRET + read_secret REGISTRAR_PASSWORD + read_secret SECOND_REGISTRAR_PASSWORD + exec ./start.sh + ;; + setup) + read_secret ADMIN_PASSWORD + # Suppress the upstream bootstrap's credential notices. + if ./setup.sh >/dev/null 2>&1; then + printf 'ThunderID bootstrap completed.\n' + else + status=$? + printf 'ThunderID bootstrap failed with status %s. Check the reviewed bootstrap inputs.\n' "$status" >&2 + exit "$status" + fi + ;; + *) + printf 'Choose ThunderID setup or serve.\n' >&2 + exit 2 + ;; +esac diff --git a/deploy/examples/business-registration/thunderid.yaml b/deploy/examples/business-registration/thunderid.yaml new file mode 100644 index 0000000000..f7edabe8ed --- /dev/null +++ b/deploy/examples/business-registration/thunderid.yaml @@ -0,0 +1,57 @@ +server: + hostname: 0.0.0.0 + port: 8090 + http_only: true + public_url: https://identity.reference.test:9443 + security: + direct_auth_secret: file://config/secrets/direct_auth_secret +jwt: + issuer: https://identity.reference.test:9443 + preferred_key_id: default-key +crypto: + encryption: + key: file://config/certs/crypto.key + keys: + - id: default-key + cert_file: config/certs/signing.cert + key_file: config/certs/signing.key + - id: ecdsa-key + cert_file: config/certs/ecdsa-signing.cert + key_file: config/certs/ecdsa-signing.key +database: + config: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_config + username: thunderid + password: "{{.DB_CONFIG_PASSWORD}}" + sslmode: verify-full + runtime_transient: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_runtime_transient + username: thunderid + password: "{{.DB_RUNTIME_TRANSIENT_PASSWORD}}" + sslmode: verify-full + entity: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_entity + username: thunderid + password: "{{.DB_ENTITY_PASSWORD}}" + sslmode: verify-full + runtime_persistent: + type: postgres + postgres: + hostname: postgres + port: 5432 + name: thunderid_runtime_persistent + username: thunderid + password: "{{.DB_RUNTIME_PERSISTENT_PASSWORD}}" + sslmode: verify-full diff --git a/deploy/examples/business-registration/upstreams.yaml b/deploy/examples/business-registration/upstreams.yaml new file mode 100644 index 0000000000..551b767931 --- /dev/null +++ b/deploy/examples/business-registration/upstreams.yaml @@ -0,0 +1,63 @@ +static_resources: + listeners: + - name: from_registry + address: + pipe: {path: /run/relay/registry.sock, mode: 384} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: from_registry + cluster: registry + - name: from_pages + address: + pipe: {path: /run/relay/pages.sock, mode: 384} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: from_pages + cluster: pages + - name: from_functions + address: + pipe: {path: /run/relay/functions.sock, mode: 384} + filter_chains: + - filters: + - name: envoy.filters.network.tcp_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy + stat_prefix: from_functions + cluster: functions + clusters: + - name: registry + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: registry + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8100} + - name: pages + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: pages + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8200} + - name: functions + type: STATIC + connect_timeout: 2s + load_assignment: + cluster_name: functions + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: {address: 127.0.0.1, port_value: 8300} diff --git a/docs/site/astro.config.mjs b/docs/site/astro.config.mjs index c877023df3..18e04bb609 100644 --- a/docs/site/astro.config.mjs +++ b/docs/site/astro.config.mjs @@ -802,6 +802,7 @@ export default defineConfig({ items: [ { label: 'Overview', slug: 'start/breg-quickstart' }, { label: 'Your first registry', slug: 'tutorials/first-breg' }, + { label: 'Preview a browser service', slug: 'tutorials/preview-a-breg-service' }, { label: 'How a registry works', slug: 'explanation/configuration-defined-registry' }, { label: 'Tutorials', diff --git a/docs/site/scripts/generate-breg-configuration.mjs b/docs/site/scripts/generate-breg-configuration.mjs index 98fbde9f21..d9d65763a0 100644 --- a/docs/site/scripts/generate-breg-configuration.mjs +++ b/docs/site/scripts/generate-breg-configuration.mjs @@ -47,8 +47,8 @@ const DEV_CONTRACTS = [ }, ].map(contract('tooling', undefined, 'products/platform/generated/dev')); -// Files `bregctl` reads beside a project: adopter tooling, published by the -// `tool-schema` example under products/breg/generated/tools. +// Adopter tooling files and saved reports, published by the `tool-schema` +// example under products/breg/generated/tools. const BREG_TOOL_CONTRACTS = [ { id: 'example-scenarios', @@ -86,6 +86,12 @@ const BREG_TOOL_CONTRACTS = [ file: 'tools/model-selection.v1alpha1.schema.json', reference: 'reference/bregctl-publicschema-wizard.mdx', }, + { + id: 'ctl-report', + title: 'Saved identity-facts-report.json', + file: 'tools/ctl-report.v1alpha1.schema.json', + reference: 'operate/advanced/generate-identity-configuration.mdx', + }, ].map(contract('tooling')); // The tool files listed in the order an adopter meets them; the generated diff --git a/docs/site/scripts/generate-breg-configuration.test.mjs b/docs/site/scripts/generate-breg-configuration.test.mjs index dcc80f4d31..2265349948 100644 --- a/docs/site/scripts/generate-breg-configuration.test.mjs +++ b/docs/site/scripts/generate-breg-configuration.test.mjs @@ -64,7 +64,7 @@ test('BReg covers every committed tool schema, in the order an adopter meets the ...await committed('products/platform/generated/dev'), ].sort(), TOOL_CONTRACTS.map((entry) => entry.file).sort()); assert.deepEqual(TOOL_CONTRACTS.map((entry) => entry.id), ['rstack-dev', 'rstack-service', 'rstack-journeys', 'example-scenarios', - 'journeys', 'schema-test-credentials', 'migration-descriptor', 'backup-binding', 'model-selection']); + 'journeys', 'schema-test-credentials', 'migration-descriptor', 'backup-binding', 'model-selection', 'ctl-report']); }); test('BReg tool and service references read the committed schemas they name', async () => { @@ -89,9 +89,15 @@ test('BReg tool and service references read the committed schemas they name', as const projectDev = fields('tools', 'rstack-dev'); assert.deepEqual(projectDev.get('kind').values, ['RStackDev']); - assert.ok(projectDev.has('products[].product')); + assert.ok(projectDev.has('products.breg.projects.*.path')); + assert.ok(projectDev.has('audiences.*')); assert.ok(fields('tools', 'rstack-journeys').has('journeys[].steps[].expect.status')); + const savedReport = fields('tools', 'ctl-report'); + assert.deepEqual(savedReport.get('kind').values, ['BRegCtlReport']); + assert.deepEqual(savedReport.get('command').values, ['generate']); + assert.deepEqual(savedReport.get('status').values, ['complete']); + const descriptor = fields('tools', 'migration-descriptor'); assert.deepEqual(descriptor.get('steps[].type').values, ['chunked-backfill', 'field-encryption-backfill', 'transactional-sql']); diff --git a/docs/site/scripts/generate-cli-reference.test.mjs b/docs/site/scripts/generate-cli-reference.test.mjs index 0d5aa2aabe..fb22e980b4 100644 --- a/docs/site/scripts/generate-cli-reference.test.mjs +++ b/docs/site/scripts/generate-cli-reference.test.mjs @@ -98,14 +98,14 @@ test('renders the committed catalogue while keeping the job host unreviewed and assert.doesNotMatch(pages.get('index.mdx'), /\(\.\/adapter-job\/\)/u); }); -test('keeps the session service unreviewed and source-build-only', async () => { +test('keeps the session service unreviewed with its numbered-release asset', async () => { const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)); const docsRoot = fileURLToPath(new URL('../', import.meta.url)); const catalog = validateCatalog(await loadCatalog(repoRoot)); assert.ok(catalog.binaries.some((binary) => binary.name === 'registry-session')); const metadata = YAML.parse(await readFile(join(docsRoot, 'src/data/cli-reference.yaml'), 'utf8')); assert.ok(metadata.unreviewed_binaries.includes('registry-session')); - assert.ok(metadata.source_build_only_binaries.includes('registry-session')); + assert.ok(!metadata.source_build_only_binaries.includes('registry-session')); const pages = renderCatalog(catalog, metadata); for (const name of [ 'registry-session.mdx', @@ -114,7 +114,7 @@ test('keeps the session service unreviewed and source-build-only', async () => { ]) { assert.match(pages.get(name), /status: draft\ndraft: true/u); assert.match(pages.get(name), /last_reviewed: "unreviewed"/u); - assert.match(pages.get(name), /It has no numbered-release asset/u); + assert.doesNotMatch(pages.get(name), /no numbered-release asset/u); } assert.doesNotMatch(pages.get('index.mdx'), /\(\.\/registry-session\/\)/u); }); diff --git a/docs/site/scripts/generate-coordinator-configuration.test.mjs b/docs/site/scripts/generate-coordinator-configuration.test.mjs index f60c6147a1..2ba4c6d542 100644 --- a/docs/site/scripts/generate-coordinator-configuration.test.mjs +++ b/docs/site/scripts/generate-coordinator-configuration.test.mjs @@ -31,9 +31,10 @@ test('Coordinator project and runtime references carry the keys authors and oper const keys = (id) => new Set(document.contracts.find((contract) => contract.id === id) .fields.map((field) => field.key_path)); const project = keys('project'); - for (const path of ['workflow.steps', 'workflow.start', 'operations.*.uses', 'functions.*.entrypoint']) { + for (const path of ['workflow.steps', 'workflow.start', 'operations.*.uses', 'transforms.*.entrypoint']) { assert.ok(project.has(path), path); } + assert.ok(!project.has('functions.*.entrypoint')); const runtime = keys('runtime'); for (const path of [ 'connections', diff --git a/docs/site/scripts/generate-evidence-configuration.mjs b/docs/site/scripts/generate-evidence-configuration.mjs index 4db0eba1ed..d373cd183c 100644 --- a/docs/site/scripts/generate-evidence-configuration.mjs +++ b/docs/site/scripts/generate-evidence-configuration.mjs @@ -111,6 +111,13 @@ export const CONTRACTS = [ status: 'tooling', reference: AUTHORING_REFERENCE, }, + { + id: 'store-provision', + file: 'crates/registry-evidencectl/schemas/authoring/store-provision.schema.json', + title: 'store-provision.yaml', + status: 'tooling', + reference: 'products/evidence/OPERATOR-CONTRACT.md', + }, { id: 'oid4vci-runtime', file: 'products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json', diff --git a/docs/site/scripts/generate-evidence-configuration.test.mjs b/docs/site/scripts/generate-evidence-configuration.test.mjs index 4534cd5b90..0b2a3d9a28 100644 --- a/docs/site/scripts/generate-evidence-configuration.test.mjs +++ b/docs/site/scripts/generate-evidence-configuration.test.mjs @@ -660,6 +660,8 @@ test('every published schema declares whether it is frozen or adopter tooling', assert.equal(byId.get('authoring-project').status, 'tooling'); assert.equal(byId.get('authoring-target').status, 'tooling'); assert.equal(byId.get('authoring-target-authority').status, 'tooling'); + assert.equal(byId.get('store-provision').status, 'tooling'); + assert.equal(byId.get('store-provision').reference, 'products/evidence/OPERATOR-CONTRACT.md'); assert.equal(byId.get('oid4vci-runtime').status, 'beta'); assert.equal(byId.get('oid4vp-runtime').status, 'beta'); }); diff --git a/docs/site/scripts/information-architecture.test.mjs b/docs/site/scripts/information-architecture.test.mjs index 1fd830d676..300164ab73 100644 --- a/docs/site/scripts/information-architecture.test.mjs +++ b/docs/site/scripts/information-architecture.test.mjs @@ -13,6 +13,7 @@ import { RETIRED_RELAY_ROUTES, } from '../src/lib/relay-retirement-redirects.mjs'; import { flattenSidebarGroups } from '../src/lib/sidebar.mjs'; +import { readJourney } from './tutorial-runner/page.mjs'; import { docsetPublishesBregOpenApi, docsetPublishesEvidenceOid4vciOpenApi, @@ -890,6 +891,7 @@ test('keeps the BReg guide and references in one adoption path', () => { assert.deepEqual(slugs, [ 'start/breg-quickstart', 'tutorials/first-breg', + 'tutorials/preview-a-breg-service', 'explanation/configuration-defined-registry', 'tutorials/change-a-registry-with-an-action', 'tutorials/extend-a-registry-with-a-module', @@ -943,6 +945,7 @@ test('keeps the BReg guide and references in one adoption path', () => { breg, [ "slug: 'tutorials/first-breg'", + "slug: 'tutorials/preview-a-breg-service'", "label: 'Tutorials'", "label: 'Author a registry'", "label: 'Deploy and operate'", @@ -952,6 +955,8 @@ test('keeps the BReg guide and references in one adoption path', () => { ], 'Base Registry Engine', ); + const overview = readFileSync(resolve(siteRoot, 'src/content/docs/start/breg-quickstart.mdx'), 'utf8'); + assert.match(overview, /\]\(\.\.\/\.\.\/tutorials\/preview-a-breg-service\/\)/u); // The homepage names the doors into the path, not every room: the overview, // the first tutorial, the deployment page, and the tutorial @@ -972,6 +977,17 @@ test('keeps the BReg guide and references in one adoption path', () => { } }); +test('reads the first BReg tutorial development files from the scaffold', () => { + const firstBreg = readFileSync(resolve(siteRoot, 'src/content/docs/tutorials/first-breg.mdx'), 'utf8'); + const { steps, errors } = readJourney(firstBreg); + assert.deepEqual(errors, []); + const devFiles = steps.filter(({ path }) => path === 'dev.yaml' || path === 'dev-journeys.yaml'); + assert.deepEqual(devFiles.map(({ kind, path }) => [kind, path]), [ + ['excerpt', 'dev.yaml'], + ['excerpt', 'dev-journeys.yaml'], + ]); +}); + // Both runtime products ask an adopter for infrastructure before they serve // anything: PostgreSQL, a token issuer, and a signing process for Base Registry // Engine; a Transit proxy, an identity provider, and durable audit storage for diff --git a/docs/site/src/content/docs/configure/adapter-jobs.mdx b/docs/site/src/content/docs/configure/adapter-jobs.mdx index 3b756ef826..2f32611da7 100644 --- a/docs/site/src/content/docs/configure/adapter-jobs.mdx +++ b/docs/site/src/content/docs/configure/adapter-jobs.mdx @@ -373,7 +373,7 @@ A metadata mismatch or operation refusal never selects another operation or dest {/* Evidence: crates/registry-adapter-connectors/src/coordinator_event.rs a_rotating_trigger_sends_the_current_signature_first */} {/* Evidence: crates/registry-adapter-job/src/runtime_destination.rs resolve_destination_keys */} -The job sends one event per item as a canonical JSON `HookEnvelope` in a Standard Webhooks POST to `/v1/events/{workflow}/{trigger}`. +The job sends one event per item as a canonical JSON `HookEnvelope` in a Standard Webhooks POST to `/v1/events/{workflowId}/{triggerId}`. The request carries `accept: application/json`, `content-type: application/json`, `webhook-id`, `webhook-timestamp`, and `webhook-signature`. The signature covers the envelope ID, the send time in Unix seconds, and the exact body bytes. The receiver accepts a `webhook-timestamp` up to 300 seconds before or after its own clock. diff --git a/docs/site/src/content/docs/configure/casework-directory.mdx b/docs/site/src/content/docs/configure/casework-directory.mdx index 04cabd5cd0..e1bd101070 100644 --- a/docs/site/src/content/docs/configure/casework-directory.mdx +++ b/docs/site/src/content/docs/configure/casework-directory.mdx @@ -36,15 +36,16 @@ Only an [access profile](../../reference/glossary/#access-profile) with the `adm ## Seed it for the development run -A new directory is empty. The run's journey, `dev-journeys.yaml`, seated the team with the same -bootstrap call a deployment uses, as the plan's `administrator` person: - -```yaml title="dev-journeys.yaml" test-excerpt="tutorial-work/casework/dev-journeys.yaml" -body: - teamId: decisions-team - staff: [{issuer: https://identity.standalone.example.test, subject: staff}] - supervisors: [] - queueId: decisions +A new directory is empty. In the tutorial, the plan's `administrator` seated the team +using the same bootstrap call a deployment uses. The body is in `directory-bootstrap.json`. + +```json title="directory-bootstrap.json" test-excerpt="tutorial-work/casework/directory-bootstrap.json" +{ + "teamId": "decisions-team", + "queueId": "decisions", + "staff": [{"issuer": "https://identity.casework.example.test", "subject": "staff"}], + "supervisors": [] +} ``` The body names one team and the one declared queue it serves. Its staff and supervisors are an @@ -95,7 +96,7 @@ A deployment's first administrator creates the first team with one call, naming } ``` -```sh test-skip="the run's journey already seeded its directory, so revision 0 is refused" +```sh test-skip="the tutorial already bootstrapped this directory, so revision 0 is refused" curl -sS --fail-with-body --header @"$(headers_for administrator)" \ --header 'Content-Type: application/json' \ --header 'If-Match: "0"' \ diff --git a/docs/site/src/content/docs/configure/casework.mdx b/docs/site/src/content/docs/configure/casework.mdx index 9142040947..435789efbb 100644 --- a/docs/site/src/content/docs/configure/casework.mdx +++ b/docs/site/src/content/docs/configure/casework.mdx @@ -27,8 +27,8 @@ still going. ## Read the project files -`casework.yaml` is the policy. `dev.yaml` and `dev-journeys.yaml`, which you wrote in the -tutorial, describe the local run for `rstack dev`. `fixtures/` holds the cases `test` proves, and +`casework.yaml` is the policy. The generated `dev.yaml` and `dev-journeys.yaml` describe the +local run for `rstack dev`. `fixtures/` holds the cases `test` proves, and `runtime.example.yaml` is a starting runtime configuration for a deployment. `.casework/schemas/` holds the JSON Schemas your editor reads through each file's first-line comment. Check the project as it stands: diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index e6d4593921..8e70c900a8 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -136,17 +136,18 @@ read-application: `type: input` reads the run's input, `type: step` an earlier call's output, and `type: literal` a fixed value. A `path` is a JSON Pointer into it. `type: fields` builds an object of up to 64 -members, and `type: function` computes the value with a Function, as `permission` and `notify` do. +members, and `type: transform` computes the value with a Transform, as `permission` and `notify` do. {/* Evidence: crates/registry-coordinator/src/cli.rs, render_explain; crates/registry-coordinator/src/authoring.rs, AuthoredStep, Mapping; crates/registry-coordinator/src/operations.rs, CATALOG. */} -## Functions +## Transforms -`notice-route` and `notice-request` are Rhai entrypoints in `functions.rhai`. `workflow.yaml` -declares each one's inputs and output by schema, here the read operation's output and the -Messaging operation's input: +Declare `notice-route` and `notice-request` under `transforms` in `workflow.yaml`. +Each [Transform](../../reference/glossary/#transform) names a Rhai entrypoint in `functions.rhai` +and declares its input and output schemas. +This Transform reads the BReg operation's output and produces the Messaging operation's input. ```yaml title="follow-up/workflow.yaml" test-excerpt="follow-up/workflow.yaml" notice-request: @@ -162,13 +163,17 @@ notice-request: operationInput: notices-submit-message ``` -A Function is pure: it has no clock, network, database, file, or credential. The host checks its +A Transform is pure: it has no clock, network, database, file, or credential. The host checks its inputs and output against those schemas and stops it at the limits `check --explain` prints. -`add_seconds` and `seconds_between` compute over instants a Function is given. +`add_seconds` and `seconds_between` compute over instants a Transform is given. {/* Evidence: crates/registry-coordinator/src/functions.rs; crates/registry-coordinator/src/definition.rs, FunctionLimits. */} +If you are upgrading an authored workflow, rename its `functions` section to `transforms`. +In each mapping, change `type: function` to `type: transform` and rename its `function` member +to `transform`. Then run `coordinatorctl check --project ./follow-up`. + ## Check a change `check` fits every mapping to the schemas it reads and feeds. Misspell the input member the read @@ -216,7 +221,7 @@ Valid runtime configuration ``` The `Definition:` digest is the workflow revision. It hashes what execution depends on: input, -steps, outcomes, and the operation and Function revisions used. Labels, descriptions (including `project.label` and `project.description`), and +steps, outcomes, and the operation and Transform revisions used. Labels, descriptions (including `project.label` and `project.description`), and `project.version` do not change it. Every run records the revision it was admitted under. {/* Evidence: crates/registry-coordinator/src/mapping_check.rs; @@ -250,7 +255,7 @@ The schema execution profile is pinned in every snapshot; unknown formats and re ### Build nested objects A `fields` mapping builds an object member by member. -Each member is a reference (`input`, `step`, or `literal`) or another `fields` mapping, so a workflow builds a structured operation input without a Function: +Each member is a reference (`input`, `step`, or `literal`) or another `fields` mapping, so a workflow builds a structured operation input without a Transform: ```yaml start: @@ -278,8 +283,8 @@ start: Nesting reaches a depth of 4, counting the outermost mapping as 1, and the whole mapping holds at most 64 members across all levels. A nested object counts as one member, and so does each of its own members. -A nested member holds only references and further `fields` mappings, never a Function: compute such a value in an earlier step and reference it. -`wait-until`, `choose`, and Function `inputs` still take references only. +A nested member holds only references and further `fields` mappings, never a Transform: compute such a value in an earlier step and reference it. +`wait-until`, `choose`, and Transform `inputs` still take references only. Compilation refuses a fifth level with `mapping.fields-depth` and a 65th member with `mapping.fields-count`, each at the member's path. The compiler checks every member against the operation input schema at that member's path, and the built object is validated again before preparation. @@ -311,7 +316,7 @@ size: Conditions run in order and stop at the first decisive one, so `present: true` before a numeric test guards an optional value. A missing or wrongly typed value in any other test fails the run with `choice-invalid`; it never routes silently to `unmatched`. -A compare holds no Function and no clock. +A compare holds no Transform and no clock. A compare treats the numbers `4` and `4.0` as equal, as JSON Schema does. Casework routing uses the same `equals` and `oneOf` names but compares JSON values exactly, so `4` and `4.0` differ there. @@ -377,12 +382,12 @@ Give the deadline route its own steps, such as a notice and a finish, disjoint f {/* Evidence: crates/registry-coordinator/src/authoring.rs service_deadline_seconds, on_deadline. */} -### Function helpers +### Transform helpers Each Rhai entrypoint takes one object of its declared named inputs and returns one typed value. -A Function declares `runtime`, `source`, `entrypoint`, `inputs`, and `output`. +A Transform declares `runtime`, `source`, `entrypoint`, `inputs`, and `output`. Explicit limits can only narrow the host's ceilings on operations, calls, expressions, strings, arrays, maps, and source size. -A Function cannot obtain credentials, read a clock, or reach a filesystem, network, or database, and it cannot construct workflow steps. +A Transform cannot obtain credentials, read a clock, or reach a filesystem, network, or database, and it cannot construct workflow steps. The profile's callable names are the interpreter's own calls, the arithmetic, logic, string, array, map, and iterator packages, and these helpers: @@ -396,14 +401,14 @@ The trigonometric, hyperbolic, exponential, and logarithmic functions are not av A result that holds NaN or an infinite number is refused with `function.execution`. A top-level `const` is not visible inside a function: read it as `global::NAME` or pass it as an input. -`check` reports a call to any other name as `coordinator.function.unknown-call` at its position in the Function source, unless the source defines that name. -Calls are matched by name only, so a wrong argument count still fails when the Function runs. -The check is an authoring aid, not a security boundary: the engine refuses any name it lacks when the Function runs. +`check` reports a call to any other name as `coordinator.transform.unknown-call` at its position in the Transform source, unless the source defines that name. +Calls are matched by name only, so a wrong argument count still fails when the Transform runs. +The check is an authoring aid, not a security boundary: the engine refuses any name it lacks when the Transform runs. It also reads a string literal given to `Fn`, `is_def_fn`, or an array method such as `map` as a function name, and skips a method call whose name the source also uses as a map key or property. -`coordinatorctl explain functions` prints the names, the interpreter ABI, and the limits. +`coordinatorctl explain transforms` prints the names, the interpreter ABI, and the limits. The ABI names the helper set, so a definition frozen under an earlier ABI is refused with `definition.abi` and the project is re-authored. -{/* Evidence: crates/registry-coordinator/tests/helper_functions.rs coordinator.function.unknown-call; +{/* Evidence: crates/registry-coordinator/tests/helper_functions.rs coordinator.transform.unknown-call; crates/registry-coordinator/src/functions.rs; crates/registry-coordinator/src/definition.rs definition.abi. */} @@ -479,7 +484,7 @@ A trigger accepts a logical source, an exact event type and data-schema identity The event source owns event meaning and disclosure, and product event names and payload meanings stay in the authored project. The receiving workflow uses the same finite execution engine and independently authorised downstream connections as an explicit start. -The receiver is `POST /v1/events/{workflow}/{trigger}`. +The receiver is `POST /v1/events/{workflowId}/{triggerId}`. It accepts the shared HookEnvelope signed with Standard Webhooks using the key configured for that workflow and trigger under `eventSources`. - The authenticated source URI, the event ID, and the trigger bind admission independently of the local source alias, and the canonical event bytes bind exact retries. @@ -522,8 +527,8 @@ await-review: `timeoutSeconds` is required and shorter than the run deadline. Casework submission exposes `result`, and the BReg Proposal operations expose `proposal`. The payment collection operations expose `collection` and the disbursement operations expose `disbursement`, as [Collect and disburse payments](#collect-and-disburse-payments) describes. -An external GET operation can declare a named `bounded-poll` completion with a typed pure `interpret` Function and `intervalSeconds`. -The Function receives the saved command and the latest validated response and returns `pending`, `complete` with a typed result, or a declared `refused` code. +An external GET operation can declare a named `bounded-poll` completion with a typed pure `interpret` Transform and `intervalSeconds`. +The Transform receives the saved command and the latest validated response and returns `pending`, `complete` with a typed result, or a declared `refused` code. The host owns transport, credentials, permitted destinations, scheduling, correlation, and the durable read budget, and the workflow graph stays acyclic. External polling is independent of Casework and BReg, and neither external operation offers an arbitrary HTTP method or a dynamic destination. @@ -738,7 +743,7 @@ A selector that needs a verified claim and no field values cannot be reached by | 401, 403, or 404 other than `lookup.unresolved` | A failure of the lookup through the ordinary error path, never `unresolved`. | BReg answers one value-free `lookup.unresolved` whether no record matched, two matched, the row is hidden from the profile, or a claim was missing, so neither Coordinator nor the workflow can tell those apart. -For that reason `check` refuses an `onDeclaredRefusal` that routes `unresolved` straight to a step that creates or changes a record, with `definition.unresolved-route`: `breg.invoke-action/v1`, `breg.start-proposal/v1`, `breg.submit-proposal/v1`, and `external.command/v1`, whose effect Coordinator cannot see. +For that reason `check` refuses an `onDeclaredRefusal` that routes `unresolved` straight to a step that creates or changes a record, with `definition.unresolved-route`: `breg.invoke-action/v1`, `breg.start-proposal/v1`, `breg.submit-proposal/v1`, `external.command/v1`, and `service.invoke-function/v1`, whose effect Coordinator cannot see. "Not found, so create" makes a duplicate when two records match or one is hidden. Route to a finish, another read, or a Casework review request, and change data from a later step once a person or that read has decided. Only the direct route is refused: a step that cannot write a record (a Casework review request, a message, a scheduling call, a proposal cancellation) is allowed, and so is a mutation later on the path. @@ -863,7 +868,7 @@ An `external.get/v1` alias can specialise its validated response and declare a b `external.command/v1` sends one POST to a provider the operator configured. Workflow data supplies only the JSON body; the runtime connection fixes the origin, the exact relative `commandPath`, and the credential, and redirects are never followed. A connection without `commandPath` stays read-only, and `check` refuses a command alias bound to it or to a connection of another type. -The alias names a required `interpret` Function and can specialise the provider's `{status, body}` response: +The alias names a required `interpret` Transform and can specialise the provider's `{status, body}` response: ```yaml types: @@ -887,7 +892,7 @@ types: properties: state: {type: string, const: uncertain} -functions: +transforms: bill-outcome: runtime: rhai source: functions.rhai @@ -905,14 +910,14 @@ operations: interpret: bill-outcome ``` -The Function reads the frozen command and the validated response, held to the alias's `responseSchema`, and returns `accepted` with a result, `refused` with a declared code, or `uncertain`. +The Transform reads the frozen command and the validated response, held to the alias's `responseSchema`, and returns `accepted` with a result, `refused` with a declared code, or `uncertain`. The step output is the accepted `result`, typed by the `bill` schema in this example. A declared code takes `onDeclaredRefusal` as `{refusalCode}`, and an interpreter that never returns `refused` has no refusal route. -Return `uncertain` for any answer the Function does not recognise, so the run holds instead of guessing. +Return `uncertain` for any answer the Transform does not recognise, so the run holds instead of guessing. An accepted result is the provider's answer as the project interprets it; Coordinator does not independently verify the provider's effect. -Only a response whose status Coordinator neither holds nor retries reaches the Function: a redirect, a 429, and any 5xx never do. -Fixtures reply to the step with `type: response` and a `{status, body}` value, which the same Function interprets, and the status must be one the Function sees at run time. +Only a response whose status Coordinator neither holds nor retries reaches the Transform: a redirect, a 429, and any 5xx never do. +Fixtures reply to the step with `type: response` and a `{status, body}` value, which the same Transform interprets, and the status must be one the Transform sees at run time. A `success` or `declared-refusal` reply to the step is refused. `coordinatorctl test` refuses a `response` reply with a redirect, 429, or 5xx status at `scenario.reply`, naming the `uncertain` or `retryable` reply that models it. @@ -937,6 +942,32 @@ The operation has no original-result receipt, so `reconcile` cannot settle it. crates/registry-coordinator/tests/external_command_project.rs scenario.reply; crates/registry-coordinator/tests/external_command_postgres.rs. */} +## Call a service function + +`service.invoke-function/v1` calls one service function. +The alias names it with `serviceFunction`. +The runtime connection binds the function host, the same function, and a credential for that host alone. +The call is an external command in every other respect: a pure Transform builds the JSON body, a required `interpret` Transform reads the `{status, body}` answer, and recovery, retries and fixtures follow [Call an external provider](#call-an-external-provider). + +```yaml +operations: + draft-notice: + uses: service.invoke-function/v1 + connection: notice-drafts + serviceFunction: draft-notice + responseSchema: {typeRef: draft-response} + interpret: draft-outcome +``` + +`check` refuses an alias without `serviceFunction`, a `serviceFunction` on any other operation, and an alias whose connection binds another function. +It checks the name against the runtime connection only, and `rstack dev` also refuses a name the service's `service.yaml` does not declare. +The function host credential is distinct from every product credential and audience the runtime file declares, so the call gives the function none of them. +Write any record change as its own step, such as a `breg.invoke-action/v1` call, under the run's BReg connection. +The reference page covers the [connection](../../reference/coordinator-configuration/#service-function-connections). + +{/* Evidence: crates/registry-coordinator/tests/service_function_project.rs; + crates/registry-coordinator/tests/service_function_postgres.rs. */} + ## Import record and template contracts Import a BReg record schema when you want fixtures to reject field names the record type does not serve. @@ -1069,7 +1100,7 @@ same for Python. Regenerate after any change that moves the revision. Give the operator the package directory, its package digest, and a `runtime.yaml` template with secret references and no secret values. For each connection, list the product, the access profile -or review policy it needs, and for Messaging the template and sender profile the Functions name. +or review policy it needs, and for Messaging the template and sender profile the Transforms name. The operator pins the package in `deployment.packages` by `root` and `expectedDigest`. One deployment serves up to sixteen workflows; each is applied, upgraded, and rolled back on its own, and a run keeps the definition it started with. diff --git a/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx b/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx index 2d8a448e88..8f760f3734 100644 --- a/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx +++ b/docs/site/src/content/docs/configure/enable-sd-jwt-vc.mdx @@ -130,7 +130,7 @@ Project: . Target: local-target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx index 73f19764f0..a43cddb0b3 100644 --- a/docs/site/src/content/docs/configure/evidence-oid4vci.mdx +++ b/docs/site/src/content/docs/configure/evidence-oid4vci.mdx @@ -160,6 +160,18 @@ schema gives it, and `check` also enforces the rules a schema cannot hold: evidence.oid4vci.secret-file-root; products/evidence/examples/oid4vci-runtime/runtime.yaml. */} +## Prepare a PostgreSQL store for qualification + +To prepare a database for the OID4VCI store, follow +[Provision a PostgreSQL store for qualification](../../products/registry-evidence/operator-contract/#provision-a-postgresql-store-for-qualification) +and set `store: oid4vci` in the provisioning file. Provisioning prepares the +database and logins for a separate migration. `evidence-oid4vci serve` uses the +bounded in-memory store. + +{/* Evidence: crates/registry-evidencectl/src/store_provision.rs; + crates/registry-evidence-oid4vci/src/lib.rs; + crates/registry-evidence-oid4vci/src/storage/postgres.rs, migrate(). */} + ## Check offline Check the file before the service reads it: 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 b9bd5b2f13..10e0691a2e 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 @@ -68,12 +68,66 @@ origin policy and provide no authentication of local processes. The separate function listener requires a private handoff from the gateway and returns 401 to an anonymous function request. +To show several identities at once, replace `actor` and `breg` with `actors`. Each actor is a +declared person with a BReg grant, and lists the BReg, Casework and Coordinator paths it may +reach, with a grant for each of those products. The run serves the same built page to each +actor on its own loopback gateway origin, with that actor's own credential and profile for each +product. The terminal prints one `Actor NAME URL` line for each actor, and the JSON report +lists the same origins under `previewActors`. The `application` URL is the first actor's, in +name order. One origin per actor is a development substitution for one origin with real +sign-in: the terminal prints it on a `Substitution` line, and the JSON report lists it under +`substitutions`. +Casework and the Coordinator are reachable only through `actors`, by their service product ID +under `/registry/`, and the Coordinator path takes no query. An actors preview reaches one +Casework project and one Coordinator project at most. +Every actor has a BReg grant, so every preview function is callable from every actor's origin, +and runs under that actor's own BReg credential. +One built page serves every actor, so it asks its own origin which actor it serves: +`GET /_rstack/actor` answers `{"actor": NAME}`. It carries no credential and selects nothing, +and it answers only the page: a request without `Registry-Client: page`, or with a foreign +`Origin` or a cross-site `Sec-Fetch-Site`, gets 403. +The generated client names no Proposal author in an actors preview, because each actor's +origin pins its own BReg profile. A register with Proposals therefore needs the single-actor +form, and the build refuses it in an actors preview. +A path may hold one `{recordId}`, `{record_id}`, `{taskId}` or `{runId}` segment, each +matching only a UUID, and one `{revision}` segment, matching only a Record revision number, for +any product. The name documents the path and does not restrict where it may appear. + +```yaml +preview: + page: / + functions: [assess-permit] + actors: + applicant: + breg: {post: [/v1/actions/submit-application]} + coordinator: {get: [/v1/workflows/permit-flow, "/v1/runs/{runId}"], post: [/v1/runs]} + officer: + casework: {get: [/v1/review-tasks], post: ["/v1/review-tasks/{taskId}/decisions"]} +``` + +A Coordinator `service-function` connection calls a preview function directly. The run +reserves the function listener's loopback port before products start and writes one +owner-only host key for the run, which the Coordinator presents as its bearer. The function +listener then hands the function a fixed placeholder bearer instead of the key, so the key +never leaves the listener and no product accepts what the function receives. +Only the generated server binding hides the caller's headers from the handler. A function +runs inside the function listener's process, at its trust level, so a function that does not +export the generated binding reads the raw request, which by then carries the placeholder. +The same function stays callable from the page through the gateway, with the page actor's +authority, so write a Coordinator-bound function for both callers. +One run key admits the gateway and the Coordinator to every preview function, not only the +one a connection binds. The reserved port is released a moment before the function listener +binds it, as the other reserved ports are, so another local process could take it in that +window and receive the key. + {/* Evidence: crates/registry-rstack/src/cli.rs; crates/registry-rstack-dev/src/preview.rs; 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/host.mjs, functionHostAuthorizer, coordinatorBearer; + clients/typescript/tests/generate-preview.test.ts; products/platform/examples/service-previews/README.md; products/platform/scripts/test-service-previews.mjs. */} @@ -376,13 +430,17 @@ Stop the run with `rstack dev stop "$RUN"`. To adapt a plan to your own project, change these parts and leave the structure alone: - `issuer` names the identity issuer the local test tokens claim. Use a name that is yours. -- `products` lists each product's project directory and token audience, in any order. Name any - nonempty subset of `breg`, `casework`, `evidence`, `messaging`, `scheduling`, - `documents`, `coordinator`, `adapter`, `render` and `discovery`. The run starts - BReg before Casework. An application needs BReg. +- `products` maps each product kind to its project directory, the same shape as `service.yaml`. + BReg, Coordinator and Evidence name their projects under `projects` + (`products.breg.projects.breg.path`); `casework`, `messaging`, `scheduling`, `documents`, + `adapter`, `render` and `discovery` take one `path`. Use one project of each kind. The run + starts BReg before Casework. An application needs BReg. A directory has one inventory: when + a sibling `service.yaml` declares `products`, leave them out of `dev.yaml`. +- `audiences` gives each project its token audience, keyed by its project ID (the member name + under `projects`, or the product kind for a single `path`). - `personAudience` is optional. It names one audience, an absolute URI, that products a person - calls from a page will share. Only BReg can be a member, by setting its `audience` to the same - value. It may be a member whether or not it checks task grants, because it is the one member + calls from a page will share. Only BReg can be a member, by setting its entry in `audiences` + to the same value. It may be a member whether or not it checks task grants, because it is the one member allowed to. Casework keeps its own audience, Messaging takes no person token, and Evidence cannot join yet, so `check` and `start` refuse each of them as a member. Declaring `personAudience` alone changes nothing at run time. Every other audience must stay distinct. @@ -471,7 +529,7 @@ fields. ## Use an issuer you run Set `issuer` to the exact token issuer and `externalJwksUri` to its public key endpoint. -Use numeric loopback HTTP with an explicit port for the issuer, key endpoint and external BReg connections. Keep each product's audience in its `products` entry. +Use numeric loopback HTTP with an explicit port for the issuer, key endpoint and external BReg connections. Keep each product's audience in `audiences`. Tokens from an issuer you run carry no development mark, so use an issuer that only this run trusts. BReg expects RS256 access tokens from an external issuer. @@ -482,7 +540,6 @@ When a BReg project declares the corresponding connection, the plan can bind ext - `externalBreg.reviewAuthority` names the Casework producer, token endpoint and private-key JWT credentials. - `externalBreg.taskGrant` pairs the exact assertion issuer and client with the Casework status connection. -- `externalBreg.hooks` binds declared destination IDs to signed outbound requests to a loopback event proxy. For BReg schema rehearsals, `externalBreg.schemaTestHeaders` maps each selected person to an owner-only bearer header obtained from the external issuer. @@ -493,6 +550,39 @@ Use `secret:file/NAME` for fixture keys and headers. Put each file under the pro For a Messaging throughput rehearsal, set `RSTACK_DEV_MESSAGING_MOCK_LATENCY_MS` before starting the run. The local mock gateway delays its responses by this many milliseconds. +## Use a BReg hook receiver you run + +Set `externalBreg.hooks` when you run a separate BReg hook receiver. You can use the development +runner's issuer for a plan that attaches only hooks. Bind every declared destination ID to its +numeric loopback origin, exact event path, and `secret:file/NAME` under `fixture/`. Give the +receiver the matching HMAC key. For a sibling container, publish the receiver port on the host's +loopback interface. + +Run `rstack dev check` before starting the project. Make an authorised change that emits the event +and check that the receiver verifies its signature and records the expected event. + +{/* Evidence: crates/registry-rstack-dev/src/plan.rs, a_fixed_external_hook_may_use_the_managed_development_issuer; + crates/registry-rstack-dev/src/products.rs, prepare_breg_hooks; + crates/registry-rstack-dev/src/external_breg.rs, Hook, hook_key. */} + +## Attach a Scheduling task grant fixture + +For a development run with an external issuer, use `externalScheduling.taskGrant` to bind one +named Scheduling caller to a Casework assertion authority. Put the caller's `assertionClient` +in one Scheduling entry under `people` and use the exact Casework `sourceIssuer` from its grant. +Put the issuer's JWKS endpoint in `externalJwksUri` on the same numeric loopback origin as `issuer`. + +Set `statusUrl` to the Casework loopback origin and `tokenEndpoint` to the external issuer's token +endpoint. Set `statusClient` to its separate status reader, `statusKeyRef` to its owner-only key +under `fixture/` and `statusResource` to the reader's Casework resource. If the run also attaches a +Base Registry Engine task grant, register a separate status client and key for each product. Run `rstack dev check` +before `rstack dev start`. Scheduling checks the grant's current status with Casework before +booking and refuses the operation if it cannot verify that status. + +{/* Evidence: crates/registry-rstack-dev/src/plan.rs, managed_scheduling_requires_the_exact_external_grant_binding; + crates/registry-rstack-dev/src/external_breg.rs, TaskGrant; + crates/registry-rstack-dev/src/products.rs, additional_config. */} + ## The managed PostgreSQL server The run starts PostgreSQL for BReg, Casework, Messaging, Scheduling, Documents, Coordinator and @@ -528,6 +618,20 @@ By default it must serve TLS, and the runner verifies the server certificate and For a local server on a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback addresses), you can use plaintext by passing `?sslmode=disable` in the administrator URL and leaving `RSTACK_DEV_DATABASE_CA` unset. Generated product runtime configurations then use `database.transport: loopback-plaintext`. +If the runner and PostgreSQL share a private development network, such as a Docker Compose network, you can select `?transport=private-network-plaintext` explicitly. +The connection is unencrypted and the PostgreSQL server is unauthenticated. +Use this transport for disposable, synthetic data on an operator-isolated development network. +Use verified TLS for shared, hosted or routed CI networks. +The runner checks that every resolved address is eligible for private network plaintext and connects to one of those addresses directly. +Generated product runtime configurations use `database.transport: private-network-plaintext` and the same address. +Leave `RSTACK_DEV_DATABASE_CA` unset for either plaintext transport. +On recovery, PostgreSQL reports its own cluster identifier. The check catches a wrong-cluster setup during recovery. + +With Compose, give PostgreSQL a health check and wait for it to pass before running `rstack dev start`. +For example, run `docker compose up -d --wait postgres` when the service is named `postgres`. +Keep PostgreSQL reachable until `rstack dev stop` finishes dropping the run's databases and roles. +Then bring down the Compose project. + The administrator role named in the URL needs `LOGIN CREATEROLE CREATEDB`. Superuser is not needed for a non-spatial run. The runner sets `createrole_self_grant` on its own sessions, so you do not configure it. @@ -541,8 +645,11 @@ The URL must be a `postgres://` or `postgresql://` URL with one TCP host, a user Percent-encode special characters in the password. The URL accepts these query parameters and refuses all others: -- `sslmode`: `require`, `verify-ca`, or `verify-full` for verified TLS (the default when omitted, verifying the certificate and host name whichever you choose), or `disable` for plaintext on a loopback host only. - Setting `RSTACK_DEV_DATABASE_CA` with `sslmode=disable` is refused. +- `sslmode` accepts `require`, `verify-ca`, and `verify-full`. Each verifies the certificate and host name, as does the default TLS mode. + `sslmode=disable` on its own selects loopback plaintext. +- `transport=private-network-plaintext` explicitly selects plaintext on a private development network. + Use this selector alone or with `sslmode=disable`. A TLS `sslmode` conflicts with it. + Leave `RSTACK_DEV_DATABASE_CA` unset for plaintext and pass the same URL for recovery. - `connect_timeout` and `application_name`. - `sslrootcert` is refused. Set `RSTACK_DEV_DATABASE_CA` instead. @@ -628,7 +735,7 @@ Supply person-specific claim values in the person's product-keyed `claims` mappi The run derives scopes and purposes from the product facts for the selected profiles. Each selected profile receives the test person's subject in its principal claim. The products enforce their ordinary permissions. -Every product keeps its own audience. `personAudience` records the audience that products a person calls from a page will share. Only BReg can take it, by setting its `audience` to the same value. +Every product keeps its own audience. `personAudience` records the audience that products a person calls from a page will share. Only BReg can take it, by setting its entry in `audiences` to the same value. Set `actor` on each step in the BReg project's `tests/journeys.yaml` to choose the test person by ID. When each step names its actor and the run uses its own issuer, the rehearsal obtains each bearer in memory. The run obtains the normal schema-test receipt before packaging. @@ -725,6 +832,17 @@ A journey can call the Messaging API as a test person and poll for the delivery crates/registry-rstack-dev/src/docker.rs org.registrystack.rstack.dev-run; products/messaging/examples/starter/dev.yaml. */} +### Document Store and Scheduling hook captures + +When a Document Store or Scheduling project declares URL observers, the run binds their destinations +to a loopback receiver. The receiver verifies the webhook signature with a separate key for each +destination. Read the captured synthetic events at `hookSinks..receivedUrl` in the start +report. Trigger the observer through the product's authorised operation, then match the event type +and identifier in the capture. + +{/* Evidence: crates/registry-rstack-dev/src/products.rs, bind_signed_hooks, signed_hook_reports; + crates/registry-rstack-dev/src/sinks.rs, start_signed_hooks, receive_signed_hook. */} + ### Authored journey file `dev.yaml` must set `journeyFile`, for example `journeyFile: dev-journeys.yaml`. @@ -847,6 +965,33 @@ A later `start` creates a fresh application run. Product data on managed Postgre crates/registry-rstack-dev/src/lib.rs application-root; crates/registry-rstack-dev/src/products.rs PreparedApplication. */} +### Choose a service function or a Coordinator flow + +Use a service function for work that finishes within one request. A service function is +server-side code that your application calls. In business registration, it can check the +submitted details and call the BReg Action that creates the Record. In medical licence renewal, +it can prepare a new expiry and call the BReg renewal Action with the condition the holder +reviewed. In each case, the write completes within the request. + +Use a Coordinator flow when work waits for a person or a date, or when reviewers need to +inspect the steps of a procedure. For example, a flow can request an officer's review, wait +for the decision, and then call the product that carries out the next step. Call a service +function for an individual step the flow cannot express. To call your code through the +current [external provider operation](../coordinator/#call-an-external-provider), implement +the external command contract and have your operator configure the provider. + +A service function holds no authority of its own. Send Record changes through the owning +product under the caller's authority. BReg checks that authority before it carries out the +Action. You can draw a Coordinator flow from its declared steps and inspect the record of +each run's steps. If you write the whole procedure as function code, you give up that drawing +and per-step record. + +{/* Evidence: crates/registry-coordinator/src/definition.rs, Step::WaitUntil, Step::WaitFor; + crates/registry-coordinator/src/cli.rs, render_explain; + crates/registry-coordinator/src/store.rs, RunInspection; + crates/registry-coordinator/src/operations.rs, external.command/v1; + crates/registry-breg/src/api/actions.rs, authorize_action_mode. */} + ### Browser issuer The browser issuer presents only the plan's synthetic test people. @@ -918,6 +1063,101 @@ The worker holds the reservation until cleanup. crates/registry-rstack-dev/src/lib.rs casework-bound; crates/registry-rstack/tests/dev_run.rs casework_run_issuer_mismatch_names_the_dev_yaml_pointer. */} +### Bind the Coordinator as a Casework review producer + +A development plan with the Coordinator and Casework may bind one Coordinator +`casework-review-producer` connection to one existing Casework trusted producer. +Use `issuer: run`. A plan with such a connection and no binding is refused. + +```yaml +bindings: + coordinatorReviewProducer: + connection: review + producer: coordinator + identity: coordinator-producer + completionDestination: coordinator-wake + runIssuerBinding: + producer: + expectedIssuer: https://issuer.example.test + expectedProfile: coordinator-producer + expectedSubject: coordinator-producer +``` + +`check` refuses, at the `dev.yaml` pointer, a binding that does not match exactly: + +- the Coordinator `runtime.yaml` must name `connection` with type `casework-review-producer`, + the same `producer`, the identity's Casework grant profile, and a `completion`; +- `casework.yaml` must trust `producer` with exactly the expected issuer, profile and subject, + the identity's subject and profile must match, and its Casework grant must include the + profile's required scopes; +- the producer's `completion` must name `completionDestination` and the connection's + `recipientBinding`. + +`check` reads each product's identity facts with the binding's completion destination +configured, as the run configures it. So when the binding is missing, or its +`completionDestination` differs from the producer's, Casework refuses the project first, at the +Casework project path, with `casework.runtime.unconfigured-review-completion-destination`. The +binding's own diagnostic at the `dev.yaml` pointer follows once Casework accepts the project. + +An `initiator` guard is refused, as is a producer the BReg review authority binding already +binds and a second `casework-review-producer` connection. The binding creates no producer, +person, profile, client, scope or grant: it registers the existing test person's `client` on +the run-local token endpoint with a per-run key. Like the BReg binding, the producer token carries +the identity's whole Casework grant, which may include scopes beyond the required ones. +`start` writes the run issuer into that one producer in a private copy of the Casework +project, as the BReg binding does. It gives the Coordinator connection the Casework origin, +the identity's Casework profile and a machine client on the run-local token endpoint, so its +token carries the identity's subject and Casework audience. It binds Casework's completion +destination to the Coordinator's review completion route. Both sides use one owner-only key +of random bytes written for the run, so Casework wakes the waiting run. The permit-review service +preview's browser journey runs this binding with the real Casework and Coordinator: the +Coordinator refuses, with 401, a completion that the run key did not sign, and the run keeps +waiting until Casework sends the officer's decision. +A live Coordinator run binds the connection's address, and the Casework origin changes with +each start. Let a waiting Coordinator run finish, or start with `--clean`, before you start again. + +{/* Evidence: crates/registry-rstack-dev/src/bindings.rs coordinatorReviewProducer, + the_coordinator_review_producer_renders_both_sides_with_one_run_key, + the_coordinator_obtains_a_producer_token_from_the_run_token_server; + crates/registry-rstack-dev/src/products.rs checked_coordinator_review_producer, + a_coordinator_review_producer_refuses_each_mismatch_at_its_pointer, + a_coordinator_casework_producer_without_its_binding_is_refused. */} + +### Give the Coordinator a BReg identity + +A development plan with the Coordinator and BReg may give one Coordinator `breg` connection +a machine identity on the run-local token endpoint: + +```yaml +bindings: + coordinatorBregClient: + connection: registry + identity: coordinator-service +``` + +The identity's BReg grant is the only source of the connection's profile and scopes, and the +Coordinator's token carries that whole grant. +Use a dedicated machine person: BReg attributes every Coordinator call to it, so `check` +refuses an identity that another binding, a preview actor or a journey step uses, and a plan +with `externalJwksUri`, whose products would not trust the run-local endpoint's tokens. +`start` replaces the connection's `baseUrl` with the run's BReg origin and its whole +`authorization` with the run-local client, so no authored scope, resource or task authority +remains. BReg's own access profile and Action rules decide every call. +`check` refuses, at `/bindings/coordinatorBregClient/connection`, a connection that is not a +`breg` connection, delegates to task authority, or names a profile other than the identity's +BReg grant profile, and `start` checks the runtime document it renders again. Like every +`rstack dev` binding, it exists only in development: `rstack dev check` and `start` refuse any +other declared posture before reading the plan. + +{/* Evidence: crates/registry-rstack-dev/src/bindings.rs coordinatorBregClient, + the_coordinator_breg_client_takes_profile_and_scopes_from_the_grant_only, + the_coordinator_obtains_a_breg_token_for_its_bound_identity, + crates/registry-rstack-dev/src/lib.rs require_development; + crates/registry-rstack/tests/dev_run.rs start_and_check_refuse_explicit_production_and_invalid_postures; + crates/registry-rstack-dev/src/products.rs checked_coordinator_breg_client, + a_coordinator_breg_client_refuses_each_mismatch_at_its_connection, + start_rechecks_the_bound_breg_connection_it_renders. */} + ### Explicit browser roles with separate human source credentials A paired BReg and Casework built application may declare `application.caseworkSourceCredentialRoles` as 1 through 32 distinct existing role identifiers. diff --git a/docs/site/src/content/docs/configure/scheduling.mdx b/docs/site/src/content/docs/configure/scheduling.mdx index cb4e5ae2ca..8b078a1c6e 100644 --- a/docs/site/src/content/docs/configure/scheduling.mdx +++ b/docs/site/src/content/docs/configure/scheduling.mdx @@ -36,36 +36,50 @@ openings: weekdays: [mon, tue, wed, thu, fri] startTime: "09:00" endTime: "12:30" - effectiveFrom: "2026-10-01" - effectiveUntil: "2026-12-31" + effectiveFrom: "" + effectiveUntil: "" ``` -Times are wall-clock times at the location, read in the time zone its location record names, so -the counter opens at 09:00 Bangkok time on weekdays. The opening ends on `effectiveUntil`; from -2027 this offering publishes no starts until you extend that date and deploy the change. +Times are local to the time zone in the location record. The counter opens at 09:00 Bangkok time +on weekdays. Read `effectiveFrom` and `effectiveUntil` +in your file for the dates `init` generated when you created the project. Both dates are +inclusive. To publish starts after `effectiveUntil`, set a new approved range and deploy the +change. A single opening can span at most 3,650 days between its first and last dates. + +{/* Evidence: crates/registry-schedulingctl/src/templates.rs, date_file(); + crates/registry-scheduling-core/src/policy.rs, PatternSpanTooLarge. */} ## Close a public holiday Every opening names a [holiday set](../../reference/glossary/#holiday-set), and a date in that set -closes the opening for the whole day. The starter's set closes nothing yet. Close Tuesday 13 -October 2026: - -```diff test-edit title="scheduling/scheduling.yaml" - office-holidays: - revision: 1 -+ dates: -+ - "2026-10-13" - label: Public holidays observed by the registry offices. -``` +closes the opening for the whole day. Use Python 3 to add the Tuesday after the counter fixture's +Monday `now` to `office-holidays.dates`. Add a booking case for 09:00 Bangkok time that day. +This keeps the holiday inside the fixture's booking horizon and leaves its Monday cases intact. -Prove it with a case at the end of the counter fixture. A booking at 09:00 that day must be -refused: - -```yaml title="scheduling/fixtures/counter-stations.yaml" test-append +```sh +python3 - <<'PY' +from datetime import datetime, timedelta +from pathlib import Path + +project = Path("scheduling") +fixture = project / "fixtures/counter-stations.yaml" +fixture_text = fixture.read_text(encoding="utf-8") +fixture_now = next(line.split(": ", 1)[1] for line in fixture_text.splitlines() + if line.startswith("now: ")) +holiday = datetime.strptime(fixture_now, "%Y-%m-%dT%H:%M:%SZ").date() + timedelta(days=1) + +policy = project / "scheduling.yaml" +policy_text = policy.read_text(encoding="utf-8") +holiday_set = " office-holidays:\n revision: 1\n" +before, after = policy_text.split(holiday_set, 1) +if after.startswith(" dates:") or "the-holiday-is-not-served" in fixture_text: + raise SystemExit("The starter already has holiday dates or has recorded the holiday case.") +policy.write_text(f'{before}{holiday_set} dates:\n - "{holiday}"\n{after}', encoding="utf-8") +fixture.write_text(fixture_text + f"""\ - name: the-holiday-is-not-served request: offering: registry-update-30 - start: 2026-10-13T02:00:00Z + start: {holiday}T02:00:00Z party: recipients: 1 attendees: 1 @@ -74,6 +88,8 @@ refused: expect: type: refused code: schedule.unpublished +""", encoding="utf-8") +PY ``` ```sh @@ -96,15 +112,16 @@ does not establish source reachability or deployment readiness. `schedule.unpublished` is the answer for any start the policy does not publish, whether the day is a holiday, a weekend, or outside the opening hours. -A closure that affects one location for part of a day is not policy. It is an exception record in -`records.yaml`, which the operator applies to a running deployment without a new package: +A closure that affects one location for part of a day is an exception record in `records.yaml`. +The operator applies it to a running deployment without a new package. Read the `hall-prep` +exception in your starter for the date of the New York clock change the fixture exercises. ```yaml title="scheduling/records.yaml" test-excerpt="scheduling/records.yaml" exceptions: - id: hall-prep location: new-york-hall kind: closure - date: "2026-11-01" + date: "" startTime: "00:15" endTime: "00:45" ``` @@ -256,8 +273,10 @@ schedulingctl explain ./arrival --format json } ``` -The window itself is a record in `./arrival/records.yaml`, with its start, end, and `units`. A -`subquotas` entry caps how many of those units one channel, `public` or `assisted`, may take. A +The window itself is a record in `./arrival/records.yaml`, with its start, end, and `units`. +The starter dates both windows on the same upcoming Saturday. After those windows pass, publish +new dated records for future bookings. +A `subquotas` entry caps how many of those units one channel, `public` or `assisted`, may take. A subquota is a ceiling, not a reservation: the other channel may still use units the first leaves free. A channel the policy declares but gives no subquota draws from the window's total alone, and a request naming an undeclared channel is refused. diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index e006f55066..8d4b57a09f 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -25,8 +25,8 @@ The service is a relying party, not an identity provider or token issuer. It uses authorisation-code sign-in with PKCE and obtains one token set per distinct audience. The provider must return JWT access tokens with a readable audience, a lifetime and refresh tokens. -Build `registry-session` from the workspace source with `cargo build --locked -p registry-session`. -It is held out of numbered releases. +Numbered releases from v0.51.0 publish `registry-session` for Linux amd64, Linux arm64 and macOS arm64, beside the release's `SHA256SUMS`. +`rstack` does not install it: download the asset for your platform, or build it from the workspace source with `cargo build --locked -p registry-session`. Use `registry-session --help` for its command tree. {/* Evidence: crates/registry-session/src/signin.rs authorization_location, complete; @@ -249,7 +249,70 @@ If a value uses an environment expression, add `--environment` with that variabl crates/registry-session/src/offline.rs run, receipt_diagnostics, receipt_findings; crates/registry-session/src/lib.rs command. */} -## 3. Generate and splice the gateway fragments +## 3. Generate the Envoy configuration + +### Standalone gateway on one host + +Use the standalone generator when Envoy, Session, and the module and page services share one +host. Set `gateway.service.host` to a numeric loopback address in the Session runtime file. +For a public HTTPS origin, terminate TLS in a reverse proxy on the same host and preserve the +public authority when forwarding to Envoy. Supply the socket for each distinct cluster named +by the configured modules and pages. + +```bash +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --standalone-out /etc/envoy/envoy.json --listen 127.0.0.1:8080 \ + --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --verify-assembled /etc/envoy/envoy.json +envoy --mode validate --config-path /etc/envoy/envoy.json +``` + +The generator verifies the complete configuration before replacing the output file. +The Envoy command validates the file against the installed Envoy binary. Registry Stack tests +it with Envoy 1.39.6. Use the fragment workflow when you need custom HTTP filters or upstreams +on other hosts. + +{/* Evidence: crates/registry-session/src/gateway/verify.rs, write_standalone; + crates/registry-session/tests/binary.rs, envoy_validates_the_generated_standalone_configuration. */} + +### Export the checked BReg browser route + +Use the dedicated loopback HTTPS assembly for checked route export. Set `publicOrigin` to +`https://127.0.0.1:8443` and give each configured upstream a distinct numeric IPv4 loopback +socket. Session's public and check binds must match the two sockets declared in `gateway.service`. +Keep the issuer endpoints on HTTPS. Configure the BReg route to rewrite its disjoint prefix to `/`. + +Provide absolute certificate and key filenames as Envoy will see them. The generator records +the paths. The browser verifies the live TLS certificate for the numeric origin. + +```bash +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --standalone-out /etc/envoy/envoy.json --listen 127.0.0.1:8443 \ + --upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 \ + --tls-certificate /run/tls/app.crt --tls-key /run/tls/app.key +registry-session --runtime-config /etc/registry-session/runtime.yaml gateway envoy \ + --verify-assembled /etc/envoy/envoy.json --route-inventory-out /tmp/session-routes.json \ + --checked-route breg +``` + +The export records every configured module and page with its sign-in bindings. It names the +selected BReg module for browser client generation. Routes use the longest matching prefix +at a path segment boundary. Write sign-in names literally and keep the route paths to +letters, digits and `/._:~-`. The selected BReg prefix omits `~` and ends with a slash. + +The `gatewayDigest` covers the exact Envoy JSON file bytes, including whitespace. The +`signInDigest` covers the compact JSON object containing `modules` and `pages`, with +object keys in lexicographic order and array order preserved. Both use SHA-256. After +a runtime change, re-export against the assembly and use the fresh inventory. +Deploy the checked assembly with its matching runtime file. +Envoy and Session check live requests, and the product authorizes the operation. + +{/* Evidence: crates/registry-session/src/gateway/verify.rs, validate_checked_transport, + verify_checked_transport, write_verified_route_inventory; + crates/registry-session/tests/binary.rs, gateway_inventory_requires_the_exact_verified_assembly. */} + +### Integrate with an existing gateway Generate into a directory you reserve for these files. The command writes or replaces the four fragments there: diff --git a/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx b/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx index ff7af52ba9..3c9fdd7b16 100644 --- a/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx +++ b/docs/site/src/content/docs/operate/advanced/generate-identity-configuration.mdx @@ -103,6 +103,22 @@ file, and renders the result. {/* Evidence: crates/registry-thunderid-tooling/src/identity_generate.rs, generate(), and key_file_refusal(); crates/registry-casework/src/config.rs authentication.oidc.humanIdentity and representedHuman. */} +## Check a saved BReg identity-facts report + +If you saved the JSON report from a completed `bregctl --format json generate identity-facts` +run, check its structure offline with the same Registry Stack version. + +```bash +rstack dev check --owner-report ./identity-facts-report.json \ + --owner-report-format breg-identity-facts-report +``` + +The check validates the report envelope, counts and artifact metadata. The identity generator +reads the `PlatformIdentityFacts` YAML file separately and checks its contents. + +{/* Evidence: crates/registry-rstack-dev/src/owner_report.rs, check_file; + crates/registry-bregctl/src/lib.rs, generate_identity_facts. */} + ## Prerequisites - A same-version binary for each product you select. If a binary is missing, the command names diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index f95a9c5639..11b173bb17 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -150,7 +150,7 @@ Retain the keys needed to read those snapshots and the custody metadata needed f Pin the package digest for exact bytes; use `workflowRevision` for execution semantics. -- The computed workflow revision hashes the input, graph, outcomes, used Operation and Function revisions, and host execution contracts. +- The computed workflow revision hashes the input, graph, outcomes, used Operation and Transform revisions, and host execution contracts. Presentation labels and descriptions do not change it. `check` prints it on its `Definition:` line, and start, status, list, and inspect report it as `workflowRevision`. Existing runs keep their admitted revision. @@ -902,7 +902,7 @@ The client resends an admission whose outcome is unknown only under its original An operator policy lists every owner's runs in those workflows. `limit` takes 1 to 100 and defaults to 20. Pass `nextCursor` as `cursor` with the same filters to continue; each page rechecks current caller and workflow permissions. -Keep the run ID a start returns for direct lookup with `GET /v1/runs/{run}`. +Keep the run ID a start returns for direct lookup with `GET /v1/runs/{runId}`. Filters, which combine: @@ -1057,7 +1057,7 @@ Before the final attempt, these external replies must carry at most one `Retry-A A date, duplicate field, malformed value, or longer wait stops the call with `external-unusable-retry-after`. Zero still follows the normal backoff schedule. -An `external.command/v1` call has no read-only receipt, so `reconcile` reports `reconciliation-unavailable`. +An `external.command/v1` or `service.invoke-function/v1` call has no read-only receipt, so `reconcile` reports `reconciliation-unavailable`. `retry-same` resends the frozen body with its original `Idempotency-Key`; before retrying, confirm with the provider that it still deduplicates that key. - Status 429 before the tenth attempt is a definite busy answer retried on the retry schedule; on the tenth attempt it ends the call with `external-rate-limited`. @@ -1067,7 +1067,7 @@ An `external.command/v1` call has no read-only receipt, so `reconcile` reports ` The run holds at once with the effect unknown, and `retry-same` resends the same command while the deadline is still in the future. A 429 the deadline ends still ends the run `expired`. - A command ignores a `Retry-After` it cannot use, such as a date, a duplicate field, a malformed value, or a wait over 86,400 seconds, and retries on the ordinary backoff instead. -- Any other server error, a redirect, a timeout, a lost acknowledgement, or a response the interpretation Function cannot settle holds the run as uncertain. +- Any other server error, a redirect, a timeout, a lost acknowledgement, or a response the interpretation Transform cannot settle holds the run as uncertain. - After an uncertain attempt, including a retried 503, a declared refusal or 429 keeps the run held. Check the provider's record and cancel the run if no further step is wanted. diff --git a/docs/site/src/content/docs/operate/deployment-posture.mdx b/docs/site/src/content/docs/operate/deployment-posture.mdx index 8ffae6cd6b..4527e1587a 100644 --- a/docs/site/src/content/docs/operate/deployment-posture.mdx +++ b/docs/site/src/content/docs/operate/deployment-posture.mdx @@ -86,8 +86,11 @@ Explicit production settings are valid in every posture. They represent deliberate operator choices that relax a stricter default, such as `accessTokenType: JWT`, a custom `scopeClaim`, issuer-level `actorKind` or `clientActorKinds`, loopback HTTP issuer URLs, `private-network-plaintext` observer hook destinations in -Document Store and Registry Scheduling, or -`anonymousHttps: operator-approved` in Registry Adapter. +Document Store and Registry Scheduling, +`anonymousHttps: operator-approved` in Registry Adapter, or +`secretProviders.file.mountPolicy: compose-native`, which accepts root-owned Docker Compose +secret mounts at mode `0444`. Registry Evidence and both wallet adapters do not accept that +member, so it is never an explicit production setting there. Explicit production settings never refuse and are never diagnostics or warnings: @@ -98,7 +101,7 @@ Explicit production settings never refuse and are never diagnostics or warnings: {/* Evidence: crates/registry-platform-config/src/posture.rs, DevelopmentClass, Gated, ExplicitClass, Stated, PostureReport, ready_member, log_startup, has_denied_warnings; - crates/registry-platform-config/src/blocks.rs, DatabaseTransport; + crates/registry-platform-config/src/blocks.rs, DatabaseTransport, COMPOSE_NATIVE_SECRET_MOUNT; crates/registry-platform-config/src/caller_issuers.rs, ExplicitProductionSetting; crates/registry-platform-config/src/destination.rs, private-network-plaintext; crates/registry-cli-report/tests/envelope.rs, explicitProductionSettings. */} diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index d552d9a266..e883c02eb0 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -216,7 +216,53 @@ breaks the join between records written before and after. ### Mount secret files with Docker Compose -Use the release image's default UID and GID `65532:65532` on a Linux Docker host. +Compose's native file secrets are the shortest route. Compose ignores the `uid`, `gid`, and +`mode` you declare for a file-backed secret, and on some hosts the container sees each file +owned by root at mode `0444`. The default secret rule refuses that shape. Accept it explicitly in +the runtime file: + +```yaml +secretProviders: + file: + root: /run/secrets + mountPolicy: compose-native +``` + +The setting admits only a regular file owned by root, with one hard link and mode exactly `0444`, +under the declared root. Every user in the container can read those files, so run Messaging alone +in its container under one runtime identity. Group or world write access, another owner, a +second link, and a path outside the root are still refused. A static JWKS or a CA bundle is a +public document and needs no setting. + +Compose mounts each secret at `/run/secrets/`. Declare each serving credential as a +Compose secret whose name matches its `secret:file/` reference: + +```yaml +services: + messaging: + read_only: true + secrets: + - smtp-password +secrets: + smtp-password: + file: ${MESSAGING_SMTP_PASSWORD_FILE:?set MESSAGING_SMTP_PASSWORD_FILE} +``` + +Declare `runtime-database-url`, `messaging-audit-key`, `smtp-username`, `sms-gateway-token`, and +`sms-gateway-callback-key` the same way. Keep the migration credential out of the serving service. + +`messagingctl check --production` prints +`Explicit production setting platform.posture.compose-native-secret-mount at /secretProviders/file/mountPolicy`, +and startup logs `explicit production setting in use` with the same code. Without the setting, +startup refuses the first secret file with `platform.secret-file.world-readable`. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT; + crates/registry-platform-config/src/secrets.rs, judge and resolve_public_document; + crates/registry-platform-config/src/posture.rs, log_startup. */} + +#### Use a hardened secret directory + +Omit `mountPolicy` to keep the stricter rule. Use the release image's default UID and GID `65532:65532` on a Linux Docker host. Have the secret custodian create a dedicated directory owned by root, group `65532`, mode `0750`. Use regular files owned by root, group `65532`, mode `0440`, with exactly one hard link each. On the host, grant group `65532` only to the secret custodian. Restrict ACLs to the diff --git a/docs/site/src/content/docs/operate/registry-render.mdx b/docs/site/src/content/docs/operate/registry-render.mdx index 8d06e83260..65a9abbcaf 100644 --- a/docs/site/src/content/docs/operate/registry-render.mdx +++ b/docs/site/src/content/docs/operate/registry-render.mdx @@ -461,6 +461,42 @@ document type the route takes as `seal`, so a client can tell them apart first. [configuration reference](../../reference/render-configuration/#seal-documents) lists the keys, problems, and response shapes. +### Verify a delivered PDF + +Save the exact PDF bytes. For a JSON response, base64-decode `pdfBase64` to get those bytes. +Keep the delivery record for the same response. Use `X-Registry-Signed-File-Digest` or +`signedFileDigest` to identify the complete file. Use `X-Registry-Document-Digest` or +`documentDigest` to identify its first revision. + +Obtain the trust roots and expected seal identity from your institution's trusted configuration. +For a shared issuing CA, confirm the signature's leaf certificate against the expected +fingerprint. Render's `certificateDigest` is the SHA-256 of that certificate in DER form. +A digest supplied with the PDF can confirm the file matches the delivery record. +The signature and independently established trust establish who sealed it. + +Set `SIGNED_FILE_DIGEST` and `DOCUMENT_DIGEST` to the labelled digests from the delivery record. +Run these commands from a Registry Stack source checkout with the received `signed.pdf` and +your institution's `seal-root.pem`: + +```bash +printf '%s %s\n' "${SIGNED_FILE_DIGEST#sha256:}" signed.pdf | sha256sum --check --strict +uv run --script products/render/scripts/validate-seal.py \ + --pdf signed.pdf --trust-root seal-root.pem --document-digest "$DOCUMENT_DIGEST" +``` + +Accept the file only if both commands succeed and the verified seal matches your policy. +The validator reports `"ok": true` and the verified level. For B-T, include the approved timestamp +trust root with another `--trust-root` if needed and require the reported level `B-T`. +The validator checks full-file signature coverage and works offline with soft-fail revocation. +Use your institution's revocation policy when it calls for fresh revocation evidence. +If a digest or signature check fails, obtain the original signed file and its delivery record again. +If trust or identity fails, confirm the expected signer and trust roots with the issuing institution. + +{/* Evidence: crates/registry-render/src/server.rs, respond_sealed; + crates/registry-render/src/seal.rs, Seal::certificate_digest; + products/render/scripts/validate-seal.py, validate; + products/render/scripts/test_signed_delivery.py, verify_delivery. */} + ### Use a test seal in development Issue a test certificate from your own test authority and set `assuranceProfile: local` in the runtime file. diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index 6ac31ea9d1..dde5ad4ca3 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -153,6 +153,34 @@ databaseAccess: false networkAccess: false ``` +### Use Keycloak for catalogue reads + +Follow the [Keycloak issuer recipe](../advanced/connect-an-oidc-issuer/#keycloak) +for the entry under `authentication.oidc.issuers`. Set `audience` to your +Scheduling API client ID in Keycloak. Give the calling client's service account +a role on that API client so Keycloak includes it in the access token's +audience. Attach `scheduling:read` as a default client scope to the calling +client, or use the scope you configured in `readsScope`. + +After Scheduling is ready, obtain a client-credentials access token and call +`GET /v1/locations`. Expect HTTP `200`. If you receive +`authentication.refused`, check the issuer URL, token type, audience and +`allowedClients`. If you receive `profile.not-authorized`, check that the +token contains the read scope in the configured `scopeClaim`. + +A hold or appointment requires a token carrying a [Scheduling task +grant](../../reference/scheduling-task-grants/). A catalogue token without the +grant receives HTTP `403` with `operation.not-authorized` on a hold request. +To book with Keycloak, provision and verify a grant flow that binds the token +to the exact Scheduling resource and action. The catalogue setup above issues +the identity used for the read. + +{/* Evidence: products/platform/journeys/own-provider.sh, write_keycloak_recipe, + keycloak_default_scope, step_token, call_request; + products/platform/journeys/keycloak/realm.json, scheduling-booking-agent; + crates/registry-scheduling/src/auth.rs; crates/registry-scheduling/src/http.rs, + create_hold; products/scheduling/generated/registry-scheduling.openapi.json. */} + ## Package the policy ```sh diff --git a/docs/site/src/content/docs/reference/api-stability.mdx b/docs/site/src/content/docs/reference/api-stability.mdx index d504c33734..18bed508e7 100644 --- a/docs/site/src/content/docs/reference/api-stability.mdx +++ b/docs/site/src/content/docs/reference/api-stability.mdx @@ -69,10 +69,10 @@ Registry Evidence's versioned routes are `POST /v1/evidence`, `POST /v1/evidence [experimental surfaces](#experimental-surfaces). Registry Coordinator's promise covers its workflow model of five step types, its run API, and -the `coordinator` SDK namespace. Its versioned routes are `GET /v1/workflows/{workflow}`, -`POST /v1/runs`, `GET /v1/runs`, `GET /v1/runs/{run}`, `GET /v1/runs/{run}/inspect`, -`POST /v1/runs/{run}/retry-same`, `POST /v1/runs/{run}/cancel`, `POST /v1/runs/{run}/reconcile`, -`POST /v1/runs/{run}/check`, `POST /v1/events/{workflow}/{trigger}`, and +the `coordinator` SDK namespace. Its versioned routes are `GET /v1/workflows/{workflowId}`, +`POST /v1/runs`, `GET /v1/runs`, `GET /v1/runs/{runId}`, `GET /v1/runs/{runId}/inspect`, +`POST /v1/runs/{runId}/retry-same`, `POST /v1/runs/{runId}/cancel`, `POST /v1/runs/{runId}/reconcile`, +`POST /v1/runs/{runId}/check`, `POST /v1/events/{workflowId}/{triggerId}`, and `POST /v1/review-completions`. Its deployment-wide operator routes are `GET /v1/doctor`, `POST /v1/restore-hold`, `POST /v1/release-restore-hold`, `POST /v1/release-admission-hold`, `POST /v1/complete-execution-recovery`, and `POST /v1/retention`. Its operational routes are @@ -148,8 +148,7 @@ release without deprecation: Engine, Casework, an external HTTP service, or the evaluation host, and are promised Registry Document Store is held out of the 1.0 release. -The session service is source-build only while `SESSION_FIRST_RELEASE` is unset. -No release script builds, stages or publishes `registry-session` yet. +Numbered releases ship the session service binary, `registry-session`, from v0.51.0. Before `v1.0.0`, one breaking release moves the promised products' version strings from `v1alpha1` to stable versions, so a `v1alpha1` version string that a 1.x release reads or writes diff --git a/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx b/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx index c54ff48477..7b4357bcb9 100644 --- a/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx +++ b/docs/site/src/content/docs/reference/apis/registry-coordinator.mdx @@ -17,7 +17,7 @@ import ApiReferenceTable from '../../../../components/ApiReferenceTable.astro'; Registry Coordinator serves one HTTP surface for starting a run of a served workflow, following and recovering that run, operating the deployment, and taking Casework completion wake-ups. Every route except `/health`, `/ready`, `/v1/review-completions`, and -`/v1/events/{workflow}/{trigger}` takes a caller access token, and the access profile that token +`/v1/events/{workflowId}/{triggerId}` takes a caller access token, and the access profile that token resolves to decides what the caller may do. A Casework completion authenticates with its Standard Webhooks signature, as does a product event. [API stability](../../api-stability/) states the versioning contract. @@ -66,7 +66,7 @@ configured for that connection, and the receiving product decides it. ## Discover a workflow -`GET /v1/workflows/{workflow}` returns the active permitted contract, including `workflowRevision`, +`GET /v1/workflows/{workflowId}` returns the active permitted contract, including `workflowRevision`, input, and declared outcomes. It requires the caller's `start` action for that Workflow. Use that revision for fresh starts or a generated revision-pinned TypeScript/Python wrapper. Generated wrappers provide typed `start`, `get`, and `cancel` over the maintained public generic @@ -106,7 +106,7 @@ A start is refused before admission when: ## Start a run from a product event -`POST /v1/events/{workflow}/{trigger}` admits a run from a signed product event, when the workflow +`POST /v1/events/{workflowId}/{triggerId}` admits a run from a signed product event, when the workflow declares that trigger and the runtime file lists its source under `eventSources`. The body is the platform hook envelope, at most 1,048,576 canonical JSON bytes, above which it answers `413 request.body-too-large`; the admitted event value must then fit the 131,072-byte value @@ -130,7 +130,7 @@ The event grants no authority for the calls the run then makes. ## Read and inspect runs -`GET /v1/runs/{run}` answers the run's `RunStatus`: its `workflow`, computed `workflowRevision`, +`GET /v1/runs/{runId}` answers the run's `RunStatus`: its `workflow`, computed `workflowRevision`, `bindingDigest`, its current step and state, when it was admitted and when its deadline falls, whether an effect is `uncertain`, and whether it needs restore review. `stepLabel` is the label the workflow author gave the current step, as packaged in the workflow @@ -160,7 +160,7 @@ includes `nextCursor`, pass it as `cursor` with the same filters to continue. Ev current caller and workflow permissions. An invalid cursor or one from a different caller or filter answers `400 request.invalid`. Keep the run ID a start returns for direct status lookup. -`GET /v1/runs/{run}/inspect` answers the run, one entry per step with its state, attempt count, +`GET /v1/runs/{runId}/inspect` answers the run, one entry per step with its state, attempt count, whether its command is prepared, whether its effect is uncertain, and whether its receipt expired, and a `recovery` block. `recovery.retryAllowed` and `recovery.reason` describe whether the run can be scheduled again. For a compatible current call, `recovery.operation` names the pinned operation's diff --git a/docs/site/src/content/docs/reference/coordinator-configuration.mdx b/docs/site/src/content/docs/reference/coordinator-configuration.mdx index 7157bba68b..88d54acdd5 100644 --- a/docs/site/src/content/docs/reference/coordinator-configuration.mdx +++ b/docs/site/src/content/docs/reference/coordinator-configuration.mdx @@ -105,7 +105,7 @@ at most {reference.operations[0].maximum_call_attempts} attempts of ## Connections `runtime.yaml` declares every logical connection in one `connections` map, at most sixteen names. -Each entry selects its complete contract with `type`: `breg`, `casework-review-producer`, `messaging`, `payments`, `scheduling`, `external-http`, or `evaluation`. +Each entry selects its complete contract with `type`: `breg`, `casework-review-producer`, `messaging`, `payments`, `scheduling`, `external-http`, `service-function`, or `evaluation`. The [deployment runbook](../../operate/coordinator/) covers the rest of the `deployment` block. {/* Evidence: crates/registry-coordinator/src/runtime.rs ConnectionConfig. */} @@ -202,6 +202,59 @@ Coordinator trusts a 429 to mean the provider did not process the command, so th crates/registry-coordinator/src/runtime.rs command_path; crates/registry-coordinator/tests/external_command.rs. */} +### Service function connections + +A `service-function` connection serves `service.invoke-function/v1` and binds exactly one service function. +`rstack dev` checks the name against the service's `service.yaml`, and an operator recipe binds a name it has checked. +Set `baseUrl` to the function host, `function` to the function's identifier, exactly one credential, and the required `responseSchema` for `{status, body}`. +The credential is either `authorization`, an OAuth client for the function host, or `hostKeyRef`, a secret reference to a key only the function host accepts, sent as the bearer token. +`rstack dev` supplies `baseUrl` and a per-run `hostKeyRef` for the preview function host. +Coordinator sends each call as one POST to `functions/` under `baseUrl`. +The attempt timeout, response size and request body bounds are those of an external command. +Use HTTPS for institutional endpoints. +HTTP requires numeric loopback. +`authorization.taskAuthority` is refused. + +Add one connection for each function a workflow calls. +The credential is for the function host alone. +The runtime refuses a `resource` equal to a product or external connection's resource, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own issuer audience, comparing URLs with the scheme and host in lower case, no default port and no trailing `/`, and URNs with the `urn:` scheme and namespace identifier in lower case. +It also refuses a `clientId` or key reference that a product, external or evaluation connection, a review completion, an event source or the deployment's own keys use. +At startup it refuses a key whose material one of those holds under another reference. +Other `service-function` connections are not compared, so two function connections may share a function host credential. +Each refusal names the colliding connection. +Bind every function host as `service-function`: an `external-http` connection gets none of these checks. +A record change stays a separate BReg step in the workflow. + +```yaml +connections: + notice-drafts: + type: service-function + baseUrl: https://functions.example.org/ + function: draft-notice + authorization: + tokenEndpoint: https://issuer.example.org/oauth/token + clientAssertionAudience: https://issuer.example.org + clientId: coordinator-notice-functions + signingKeyRef: secret:file/notice-functions-jwk + resource: https://functions.example.org + scopes: + - functions:draft-notice + responseSchema: + type: object + required: + - status + - body + properties: + status: + type: integer +``` + +The function host must pass the `Idempotency-Key` it receives to any effect the function makes, as an external provider must deduplicate on it. + +{/* Evidence: crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; + crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references; + crates/registry-coordinator/tests/service_function.rs. */} + ### Payment connections A `payments` connection serves the native payment operations over the Registry Adapter payment host. diff --git a/docs/site/src/content/docs/reference/glossary.mdx b/docs/site/src/content/docs/reference/glossary.mdx index eecbeea412..d0cf3c90f0 100644 --- a/docs/site/src/content/docs/reference/glossary.mdx +++ b/docs/site/src/content/docs/reference/glossary.mdx @@ -111,7 +111,7 @@ Product names are always in English, including on future translated pages.
An `evidence.yaml` file and the scripts it names, kept in version control, declaring assertion definitions, sources, lookups, and Functions. `evidencectl` checks, tests, and packages it with a target into a deployment candidate.
Function
-
A project-local typed implementation asset. In BReg, an Action's Plan uses one to compute effects within the Action's declared write ceiling; it cannot grant authority or invent a review decision. In an Evidence project, a Rhai script with the `assertion-derive/v1` interface that turns a source route's validated facts into declared outputs, under fixed operation and size limits. Provider response normalisation belongs to the reviewed Adapter pack. In a Registry Coordinator workflow, a Rhai script that routes a `choose` step or computes a value a call's input maps with `type: function`, with no clock, file, network, database, or credentials.
+
A project-local typed implementation asset. In BReg, an Action's Plan uses one to compute effects within the Action's declared write ceiling; it cannot grant authority or invent a review decision. In an Evidence project, a Rhai script with the `assertion-derive/v1` interface that turns a source route's validated facts into declared outputs, under fixed operation and size limits. Provider response normalisation belongs to the reviewed Adapter pack.
grant ceiling
The widest authority a Registry Evidence assertion definition lets any grant give for it: the authorities, actor kinds, value origins, and audiences a grant may name. A target authority's grant may only narrow it; Registry Evidence refuses to activate one that widens it.
@@ -296,6 +296,9 @@ Product names are always in English, including on future translated pages.
team
A named Casework group that serves queues and declares the profiles its members and supervisors must hold; its membership lives in the directory.
+
Transform
+
A bounded Rhai computation in a Registry Coordinator workflow. A `type: transform` mapping calls it with named, typed inputs. It can select a branch or compute an operation value using only the supplied data.
+
trust domain
The institutional boundary whose operators, runtime identities, policy, keys, and approval govern one deployment. A Registry Evidence process serves one trust domain, named by the URI in `service.trustDomain`, with one signer and one audit boundary.
diff --git a/docs/site/src/content/docs/reference/render-configuration.mdx b/docs/site/src/content/docs/reference/render-configuration.mdx index de6e2011bf..ccefe92cc8 100644 --- a/docs/site/src/content/docs/reference/render-configuration.mdx +++ b/docs/site/src/content/docs/reference/render-configuration.mdx @@ -162,6 +162,7 @@ Serve and `check` report these as runtime problems at the position of the key. | `render.runtime.seal-not-bound` | A document type names a seal `signing.seals` does not bind (error). | | `render.runtime.seal-unused` | A runtime seal is named by no document type (warning). | | `render.posture.seals-not-served` | Document types name seals and the runtime has no `signing` block. Production refuses the combination. Development warns and renders the documents unsealed. | +| `platform.posture.compose-native-secret-mount` | `secretProviders.file.mountPolicy` is `compose-native`, so the file provider also accepts a root-owned, single-link file at mode `0444`, which every user in the container can read. Production accepts it as an explicit setting: `serve` logs it and `check --format json` lists it under `explicitProductionSettings`. `/ready` does not report it. | | `platform.posture.unrestricted-clients` | An issuer entry's `allowedClients` is `unrestricted`, so OIDC admits every client that issuer verifies. Production accepts it as an explicit setting: `serve` logs it and `check --format json` lists it under `explicitProductionSettings`. `/ready` does not report it. | `test-seal` reports `render.posture.test-signing` when you run it in production. diff --git a/docs/site/src/content/docs/reference/typescript-clients.mdx b/docs/site/src/content/docs/reference/typescript-clients.mdx index 49713da5ad..d60160093f 100644 --- a/docs/site/src/content/docs/reference/typescript-clients.mdx +++ b/docs/site/src/content/docs/reference/typescript-clients.mdx @@ -156,12 +156,15 @@ generates three entry points in the owned build directory. Import `createRegistr from `generated/service.ts` and `functionPaths` from `generated/routes.ts` in your page. Function paths are relative to the preview origin. A function entry imports `defineFunction` from `generated/server.ts`. Its callback receives the request and a typed -client bound to that request's caller and the private BReg address. Keep the server entry in -the function's import graph. +client bound to that request's caller and the private BReg address. The callback receives a +copy of the request without the `Authorization`, `Cookie` and `Proxy-Authorization` headers; +the typed client carries the caller's credential. Keep the server entry in the function's +import graph. {/* Evidence: crates/registry-rstack/src/cli.rs; clients/typescript/generate-project.ts; clients/typescript/generate-service.ts; + clients/typescript/preview/host.mjs; clients/typescript/tests/generate-preview.test.ts. */} ## Match the generator and runtime versions diff --git a/docs/site/src/content/docs/security/adapter.mdx b/docs/site/src/content/docs/security/adapter.mdx index 5ff94b44b8..a8265cf611 100644 --- a/docs/site/src/content/docs/security/adapter.mdx +++ b/docs/site/src/content/docs/security/adapter.mdx @@ -90,6 +90,13 @@ Configured hook ingress increments it for credential and rate-limit refusals. Th crates/registry-adapter-job/src/hook_ingress.rs, validate_hook_runtime, refused_hook_requests_are_counted_by_reason, each_refused_credential_is_counted_under_its_check_with_an_unchanged_answer. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Next - [Configure caller and source access](../../configure/adapter/#authorisation-and-secrets) diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 898775d3f2..9554193437 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -862,6 +862,13 @@ and its ancestors. Deny other write access in every posture and group write acce If data subjects must see Proposal review reads and attachment downloads, cover them in your own audit, because they write no subject-log entry. +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals The residuals are ordered by operator impact. diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index ce300d4488..812aa5c5b7 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -145,6 +145,9 @@ grants in [Registry Casework task grants](../../reference/casework-task-grants/) alongside the `casework` header file. Casework applies its usual client, profile, and human-identity checks ([run isolation](../../configure/run-a-project-with-rstack-dev/#run-isolation)). + A development binding may rewrite one named trusted producer's issuer to the run issuer, in a + private copy of the project and only when its pinned issuer, profile and subject match exact + guards. The source project and production Casework are unchanged. {/* Evidence: crates/registry-cli-api/README.md, Security boundary. */} - Separate credentials for the same human: every current-source provider binding requires `humanSourceAuthentication.audience`, distinct from every Casework issuer entry's audience, and @@ -299,6 +302,13 @@ The residuals refer to these obligations by number. (`CASEWORK-SEC-16`). Producer profiles, which are services, share one claim among themselves. +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Each residual lists the condition, the consequence, the mitigation, and the related matrix diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index d7a61e323a..f2bd83f3c3 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -13,23 +13,26 @@ standards_referenced: [] This page states what Registry Coordinator holds, what it does not hold, and what you must do for its guarantees to hold. -Each guarantee carries a stable identifier from `COORDINATOR-INV-01` to `COORDINATOR-INV-15`, and -each accepted residual risk one from `COORDINATOR-RES-01` to `COORDINATOR-RES-27`. +Each guarantee carries a stable identifier from `COORDINATOR-INV-01` to `COORDINATOR-INV-17`, and +each accepted residual risk one from `COORDINATOR-RES-01` to `COORDINATOR-RES-29`. Terms follow [Author a Coordinator workflow](../../configure/coordinator/). Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/). ## Scope and trust boundaries - The operator owns the runtime configuration: connection base URLs, the external command path, - credentials, issuer settings, the Base Registry Engine (BReg) connection profile and the Registry + the service function each `service-function` connection binds, credentials, issuer settings, the Base Registry Engine (BReg) connection profile and the Registry Adapter payment connection. Operator configuration is trusted; workflow data is not. - A workflow author writes a project that Coordinator freezes into a definition. - The author supplies bodies, mappings and pure Functions. + The author supplies bodies, mappings and pure Transforms. The author does not choose destinations, headers, credentials or recovery behaviour; the closed operation catalogue does. - Providers decide every effect a run requests: Registry Casework, Registry Scheduling, BReg, the Registry Adapter payment host and external HTTP providers. + A service function is not a provider of record authority. + Coordinator calls it with a credential distinct from every product credential the runtime file + declares, so a record change stays a separate step to the owning product. Coordinator holds workload identity, not decision authority, and each receiving product still authorises the call. - Coordinator verifies the access token against the matching entry in @@ -232,12 +235,12 @@ Enforcement: Once the request may have left, a lost or broken exchange, a timeout, a redirect, any other 5xx, and an oversize, malformed or schema-invalid response are uncertain and hold the run. - Coordinator checks the response against the alias's `responseSchema`, then runs the project's - pinned pure Function. + pinned pure Transform. Only `accepted` with a result matching the step's declared output, or `refused` with a declared - code, leaves the hold; everything else, including a Function error, is uncertain. - The worker and offline scenarios use the same Function, and scenario validation + code, leaves the hold; everything else, including a Transform error, is uncertain. + The worker and offline scenarios use the same Transform, and scenario validation (`scenario.reply`) refuses a `success` or `declared-refusal` reply to the step, so no scenario - reaches a result or refusal route the Function would not produce. + reaches a result or refusal route the Transform would not produce. Transport and scenario validation share one status classification, so a `response` reply with a status the worker holds or retries before interpretation (a redirect, a 429 or any 5xx) is refused too. @@ -458,7 +461,8 @@ start or submit on retry; settlement from an event. doctor_counts_proposal_waits_by_their_last_turn_without_reading_breg; crates/registry-coordinator/tests/runtime_config.rs breg_proposal_follow_settings_are_bounded_and_outside_the_binding_digest; - crates/registry-coordinator/src/runtime.rs request_link, is_loopback. */} + crates/registry-coordinator/src/runtime.rs request_link; + crates/registry-coordinator/src/outbound.rs numeric_loopback. */} ### COORDINATOR-INV-08: BReg control metadata has its own response ceiling @@ -489,9 +493,9 @@ Refused: a metadata answer beyond 8 MiB; any business answer beyond 64 KiB. derived_response_limits_retain_credentials_and_leave_the_original_bound_unchanged. These HTTP fixtures do not establish database transaction or deployed service behavior. */} -### COORDINATOR-INV-09: the pure Function profile is bounded and deterministic +### COORDINATOR-INV-09: the pure Transform profile is bounded and deterministic -Threat: a pure Function runs author-supplied code inside the worker. +Threat: a pure Transform runs author-supplied code inside the worker. An argument-controlled loop or allocation could hold a worker thread or exhaust memory. A host-dependent result could differ when a wait replays or a job attempt recomputes, and a changed engine could reinterpret a frozen definition. @@ -535,18 +539,18 @@ Enforcement: functions take results from the platform math library and may differ in the last digits between operating systems, CPU architectures or library versions. Results are recomputed, not only read back: a held wait is recomputed when waits replay, the next - WaitUntil is evaluated again, and each job attempt runs the Function again. + WaitUntil is evaluated again, and each job attempt runs the Transform again. A deadline computed with such a function could therefore land a second apart on two hosts. Coordinator registers only deterministic functions: `sqrt`, `floor`, `ceiling`, `round`, `int`, `fraction`, `is_nan`, `is_finite`, `is_infinite`, `to_degrees`, `to_radians`, `PI`, `E`, `parse_int`, `parse_float`, `to_int` and `to_float`, next to the arithmetic package's `abs`, `sign`, `min` and `max`. -- A Function result holding NaN or an infinite float (`0.0 / 0.0`, `sqrt(-1.0)`) is refused with +- A Transform result holding NaN or an infinite float (`0.0 / 0.0`, `sqrt(-1.0)`) is refused with `function.execution` where results turn into JSON, instead of becoming `null`. - The unknown-call check walks the syntax tree and function table, which Rhai exposes only under its `internals` feature, enabled in the build. It is an authoring aid, not a security boundary: the engine refuses any name it lacks when the - Function runs. + Transform runs. Refused: empty-padding `pad`; `pad` or `replace` results over the string budget; NaN and infinity results; a definition frozen under another interpreter identity; any function outside the @@ -616,7 +620,7 @@ admission. Startup refuses a profile without `subjects`. Threat: every workflow in a deployment calls Casework under the same review producer identity, so Casework cannot tell which run submitted a review request. -A cancel whose `request` is built from input, a literal, a Function or another step could withdraw +A cancel whose `request` is built from input, a literal, a Transform or another step could withdraw a review that another run submitted. Enforcement: check refuses a `casework.cancel-review-request/v1` step unless its input is a fields @@ -860,6 +864,108 @@ unknown, a timeout or a missing receipt authorises release or replacement. provider_confirmation_report_is_one_exact_keyed_command, disbursement_completion_settles_only_terminal_exactly_bound_state. */} +### COORDINATOR-INV-17: a service function call holds no credential the runtime file gives a product + +Threat: `service.invoke-function/v1` calls code a service declares, outside every product's +authorization. +A workflow could steer the call to another function, host or credential. +A deployment could hand the function host a token a product accepts, such as the BReg connection's +credential, so a function that forwards its incoming bearer would change records under the +Coordinator's product authority without a product step in the workflow. + +Enforcement: + +- The workflow names the function (`serviceFunction`) and supplies only the JSON body a pure + Transform builds. + The runtime connection (`type: service-function`) fixes the function host `baseUrl`, the one + bound `function`, and the credential. + Coordinator sends one POST to `functions/` under `baseUrl` and nowhere else. + The function name is a local identifier, so it cannot add a path segment. +- `coordinatorctl check` refuses an alias without `serviceFunction`, a `serviceFunction` on any + other operation, and an alias whose function is not the one its connection binds + (`workflow-binding`). + It checks the name against the runtime connection only. + `rstack dev` also refuses a name the service's `service.yaml` does not declare. + A connection of another type cannot carry the call. + The function name is part of the Operation revision and the connection's binding digest, so a + live Run cannot be moved to another function. +- The connection holds exactly one credential: an OAuth `authorization` without `taskAuthority`, + or a `hostKeyRef` key only the function host accepts. + `rstack dev` generates a per-run host key for the preview function host, and that host hands + a Coordinator-called function a fixed placeholder bearer, never the key. + It also generates a separate per-run review completion key, shared only by the run's Casework + completion hook and Coordinator connection, and removes both keys first when the run stops. + Its Coordinator bindings also register per-run machine client signing keys for the review + producer and BReg connections, on the run-local token endpoint only. +- The credential is distinct from every credential and product audience the runtime file declares. + The runtime refuses a function `resource` equal to a product or external connection's + `resource`, a task authority `bootstrapResource` or `exchangeAudience`, or the Coordinator's own + `deployment.authentication.issuers.*.audience`. + URL resources are compared with the scheme and host in lower case, the default port dropped and a + trailing `/` removed, and URNs with the scheme and namespace identifier in lower case. + It refuses a `clientId` such a connection uses, and a `signingKeyRef` or `hostKeyRef` equal to + any product, external or evaluation credential, review completion key, event source key, or the + deployment's audit, state or admission key. + Each refusal names the colliding member as its related location, and no value. + At startup the resolved keys are compared too, a JWK by its RFC 7638 thumbprint and any other key + by its bytes, so the same key under another reference is refused. + Other `service-function` connections are not compared. +- The call is an external command in every other respect (COORDINATOR-INV-03). + The request id is frozen before the first send and sent as `Idempotency-Key`, redirects are never + followed, bodies and responses are bounded, an ambiguous exchange holds the run, and only the + pinned interpretation Transform turns the response into an accepted result or a declared refusal. + Nothing an operator reads carries the body, request id or credential. + +These checks prove only that the credential differs from the ones this file declares. +Whether a product elsewhere accepts the function host token is RES-28, and a function host bound as +`external-http` is not checked at all (RES-29). + +Refused: a workflow-chosen function, host, header or credential. +Also refused: a function the connection does not bind, a function connection with no credential or +two, a function credential matching a product, external or task authority credential or the +Coordinator's audience, and task authority on a function connection. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references, + normalised_resource, validate_workflow_effect_bindings; + crates/registry-coordinator/src/adapters.rs distinct_function_keys; + crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; + crates/registry-coordinator/tests/service_function.rs + a_call_posts_to_the_bound_function_with_the_function_host_credential, + a_refusal_is_handed_to_the_interpretation_and_a_redirect_is_not_followed, + the_function_name_is_one_local_identifier, + the_bound_function_is_part_of_the_binding_digest, + a_service_function_connection_requires_its_own_credential, + a_service_function_credential_is_never_a_product_credential, + a_host_key_credential_is_sent_as_the_bearer_to_the_bound_function, + a_function_connection_names_exactly_one_credential, + a_host_key_is_never_a_product_signing_key, + a_function_resource_is_compared_after_normalisation, + a_function_resource_is_never_a_casework_or_exchange_audience, + a_function_resource_is_never_a_scheduling_messaging_or_external_audience, + a_function_resource_is_never_the_coordinator_audience, + a_taskauthority_refusal_names_the_service_function_remedy, + the_same_signing_key_under_another_reference_is_refused_at_startup, + the_runtime_routes_a_function_call_with_its_oauth_token_and_frozen_request_id, + a_lost_acknowledgement_is_uncertain_and_the_same_request_id_is_sent_again, + a_credential_collision_names_the_colliding_member_as_related, + a_function_resource_is_compared_with_any_trailing_slash_and_urn_case, + a_host_key_is_never_an_evaluation_completion_or_event_key, + a_host_key_is_never_a_deployment_key, + rotating_the_host_key_keeps_the_binding_and_changing_the_credential_kind_does_not, + the_same_host_key_or_jwk_under_another_form_is_refused_at_startup. + crates/registry-coordinator/tests/service_function_project.rs + a_missing_function_name_is_refused_at_the_operation, + only_the_service_function_operation_names_a_function, + an_unbound_function_name_is_refused_against_the_runtime_binding, + the_workflow_cannot_name_a_destination_or_credential, + the_named_function_is_part_of_the_operation_revision, + a_function_reply_reaches_its_result_only_through_the_interpret_transform, + unresolved_routed_straight_to_a_service_function_is_refused. + crates/registry-coordinator/tests/service_function_postgres.rs + an_accepted_function_call_records_the_step_and_its_typed_result, + a_declared_refusal_takes_the_workflow_refusal_route, + an_authority_refusal_the_interpretation_does_not_recognise_holds_the_run. */} + ## Operator obligations The guarantees hold only when you meet these obligations. @@ -891,7 +997,7 @@ The residuals refer to them by number. A live run whose retained definition a version does not restore, under another interpreter identity or a restore rule it breaks, is held with `definition-refused`, and only a release that accepts its definition can end it (COORDINATOR-INV-12). -9. Treat a project's Function as reviewed code: a Function that maps an ambiguous provider answer +9. Treat a project's Transform as reviewed code: a Transform that maps an ambiguous provider answer to `accepted` is an authoring defect that scenarios and review must catch. 10. List in each access profile's `subjects` only the identities it is meant to admit: a producer client's own service-account subject, or the named operators. @@ -914,6 +1020,13 @@ The residuals refer to them by number. identities. Investigate an unresolved original-request receipt before any same-command recovery or cancellation decision (COORDINATOR-INV-16). +15. Bind every function host as `type: service-function`, never as `external-http`, so the + credential checks of COORDINATOR-INV-17 apply (RES-29). + Give each `service-function` connection a client, key and resource that only its function host + accepts, scoped to the one function it binds, and add one connection per bound function. + Register the function host resource only for the function host at the authorization server. + Run the function host so that the function forwards the `Idempotency-Key` it receives to any + effect it makes, as obligation 1 asks of an external provider (COORDINATOR-INV-17). {/* Evidence: crates/registry-coordinator/tests/external_command_postgres.rs a_lost_acknowledgement_holds_and_retry_same_sends_the_same_command; @@ -927,6 +1040,13 @@ The residuals refer to them by number. caller_policies_list_the_exact_subjects_they_admit, every_connection_credential_states_its_client_assertion_audience. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Each residual names the condition under which it applies, its consequence, and the mitigation. @@ -983,14 +1103,16 @@ Each residual names the condition under which it applies, its consequence, and t ### COORDINATOR-RES-07: no receipt settles an uncertain external command -- Condition: `external.command/v1` has no original-result receipt. -- Consequence: `reconcile` cannot settle an uncertain command. +- Condition: `external.command/v1` and `service.invoke-function/v1` have no original-result + receipt. +- Consequence: `reconcile` cannot settle an uncertain command or function call. - Mitigation: check the provider's records, then retry or cancel the held run. -### COORDINATOR-RES-08: an accepted result is the Function's reading +### COORDINATOR-RES-08: an accepted result is the Transform's reading -- Condition: Coordinator does not independently verify the provider's effect. -- Consequence: a Function that maps an ambiguous answer to `accepted` records an effect that may +- Condition: Coordinator does not independently verify the effect of an external command or a + service function call. +- Consequence: a Transform that maps an ambiguous answer to `accepted` records an effect that may not have happened. - Mitigation: cover ambiguous answers in scenarios and review. @@ -1106,7 +1228,7 @@ Each residual names the condition under which it applies, its consequence, and t ### COORDINATOR-RES-19: float `**` is not on the deterministic math list -- Condition: a Function uses float `**` (`powf`, in the arithmetic package). +- Condition: a Transform uses float `**` (`powf`, in the arithmetic package). - Consequence: its result is not covered by the deterministic-math rule, so last digits could differ across hosts. - Mitigation: do not derive a deadline or a comparison threshold from float `**`. @@ -1207,6 +1329,35 @@ Each residual names the condition under which it applies, its consequence, and t a_run_whose_retained_definition_does_not_restore_is_held_alone, an_unreadable_snapshot_or_store_outage_fails_the_check_and_holds_nothing. */} +### COORDINATOR-RES-28: a function credential is distinct, not proven unusable at a product + +- Condition: a `service-function` connection names a resource, client and key that no product, + external or task authority credential in the same runtime file uses. +- Consequence: Coordinator cannot see the authorization server or the products of other + deployments, so it cannot prove that the function host token is refused everywhere else. + An authorization server that mints a product audience for the function host resource, or a + product that accepts the function host resource, would give a function product authority. +- Mitigation: obligation 15. + Register the function host resource only for the function host, and never list it as a product + audience. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references; + crates/registry-coordinator/tests/service_function.rs + a_service_function_credential_is_never_a_product_credential. */} + +### COORDINATOR-RES-29: a function host bound as `external-http` is not checked + +- Condition: an operator binds a function host as `type: external-http` with a `commandPath` such + as `functions/`, and calls it with `external.command/v1`. +- Consequence: `external-http` credentials are never compared with product credentials, so that + connection can carry the BReg connection's resource, client and key, and a function that + forwards its bearer would act with product authority. +- Mitigation: obligation 15. + Bind function hosts as `service-function`. + A later release is planned to refuse product credentials on `external-http` connections too. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs function_credential_collisions, other_key_references. */} + ## Report a vulnerability Report a suspected vulnerability through the process in diff --git a/docs/site/src/content/docs/security/documents.mdx b/docs/site/src/content/docs/security/documents.mdx index 58aa1cf5fd..9c19416504 100644 --- a/docs/site/src/content/docs/security/documents.mdx +++ b/docs/site/src/content/docs/security/documents.mdx @@ -223,6 +223,13 @@ The guarantees hold only when you meet these obligations. an_exhausted_transfer_budget_refuses_uploads_and_downloads; crates/registry-documents/src/config.rs allow_insecure_http. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Related rows are the neighbouring enforced behaviour, not the residual itself. diff --git a/docs/site/src/content/docs/security/evidence.mdx b/docs/site/src/content/docs/security/evidence.mdx index ab3ddf3b30..1229548ba5 100644 --- a/docs/site/src/content/docs/security/evidence.mdx +++ b/docs/site/src/content/docs/security/evidence.mdx @@ -501,6 +501,12 @@ holds the duties no service-side control can hold for you: products/evidence/contracts/runtime.schema.yaml, secretProviders; crates/registry-evidence/src/bundle.rs, validate_read_only. */} +Registry Evidence and both wallet adapters refuse `secretProviders.file.mountPolicy`, so their +key files keep the owner-only rule on Docker Compose too. See the +[hardening checklist](../hardening-checklist/#secret-files). + +{/* Evidence: crates/registry-evidence/src/config.rs, COMPOSE_NATIVE_REFUSED_ACTION. */} + ## Report a vulnerability Report a suspected vulnerability through the process in diff --git a/docs/site/src/content/docs/security/hardening-checklist.mdx b/docs/site/src/content/docs/security/hardening-checklist.mdx index 1463b3ffce..8f13456ea9 100644 --- a/docs/site/src/content/docs/security/hardening-checklist.mdx +++ b/docs/site/src/content/docs/security/hardening-checklist.mdx @@ -93,6 +93,11 @@ A file the runtime user owns with any group access is refused. Group read is acc file root owns. Give that file's group to the runtime user alone, because every member of the group can read the secret. On a plain host that is every member of the group in `/etc/group`. +Two inputs widen only the read checks. The explicit `secretProviders.file.mountPolicy: compose-native` +setting also accepts a root-owned file at mode exactly `0444`, the Docker Compose secret shape. A +[public document](#public-configuration-files), such as a static JWKS or a CA bundle, may be read by +group and others with no setting. + Registry Evidence and both wallet adapters require a real secret root directory owned by root or the runtime account. The runtime must be able to open and search it. Clear group and other write bits in both postures, even on a read-only mount. `evidencectl doctor` checks the same root rule. @@ -123,16 +128,61 @@ refusal holds in development. Production refuses all of them. on a memory-backed volume. - **The Helm chart.** The chart stages each secret into a memory volume owned by the runtime user at mode `0400`, which the rule accepts. It does not use `fsGroup`. See the chart's README. -- **Docker Compose.** Set ownership and mode on the host. Compose ignores `uid`, `gid`, and - `mode` for [file-backed service secrets](https://docs.docker.com/reference/compose-file/container-spec/#secrets). - Mount the directory read-only and verify the numeric IDs and permissions inside the container. - Follow the [Messaging Compose setup](../../operate/messaging/#mount-secret-files-with-docker-compose) - for a directory bind and replacement procedure. +- **Docker Compose.** Compose ignores `uid`, `gid`, and `mode` for + [file-backed service secrets](https://docs.docker.com/reference/compose-file/container-spec/#secrets), + and on some hosts presents each file root-owned at mode `0444`, which the default rule refuses. + Either set ownership and mode on the host, mount the directory read-only and verify the numeric + IDs and permissions inside the container, or write + `secretProviders.file.mountPolicy: compose-native`. That setting admits only a root-owned + regular file with one link and mode exactly `0444` under the declared root. Every user in the + container can read such a file, so use it in a container that runs one service under one + runtime identity. Startup and the production check report the setting as + `platform.posture.compose-native-secret-mount`, and the `provision` tools print it when they + read the runtime file. Writable files, other owners, extra links and paths outside the root + stay refused. A runtime that runs as root gains only the `0444` shape: stage its own files at + `0400` or `0600`, because a root-owned `0440` file is still refused. Registry Evidence and both + wallet adapters refuse the setting, since their key rule never lets other users read a key + file. Saved CLI connections and task connection files do not accept it. + The + [Messaging Compose setup](../../operate/messaging/#mount-secret-files-with-docker-compose) + shows both routes. {/* Evidence: crates/registry-evidence/src/bundle.rs, validate_secret_root; + crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT, StrictSecretProvidersConfig; + crates/registry-platform-config/src/secrets_tests.rs, compose_native_adds_only_root_owned_single_link_mode_0444; + crates/registry-platform-config/src/blocks_tests.rs, compose_native_mount_is_an_explicit_production_setting_at_its_member; + crates/registry-evidence/src/config.rs, COMPOSE_NATIVE_REFUSED_ACTION; + crates/registry-platform-provision/src/cli.rs, the_runtime_file_explicit_settings_are_printed_on_stderr; deploy/helm/registry-stack/templates/evidence-deployment.yaml, stage-evidence-inputs; deploy/helm/registry-stack/README.md, Images and workload security. */} +## Public configuration files + +Protect who can replace public trust material. Replacing an issuer's static JWKS or a CA bundle +changes which keys or certificates your deployment trusts. + +- A static JWKS or a CA bundle is a public document, not a secret. An input such as + `jwksSource.documentRef` or `database.caBundleRef` may reference `secret:file/`. The + runtime then reads it under `secretProviders.file.root` with the walk, owner and link rules of a + secret, but group and other may read it. A root-owned Compose mount at mode `0444` needs no + setting. Group or other write access, an execute bit, another owner or a second link is still + refused, with a fix worded for a public document. A file that holds a PEM private key block is + refused, and a key set with a private or symmetric member is refused, so key material staged in + the wrong file never loads. The runtime still parses the JWKS or PEM before use. +- If a runtime checks its configuration path with the shared trusted path rule, give it an absolute, + normalised path without symbolic links. In production, root or the runtime user must own the file + and its ancestors. Clear group and other write access. The rule permits a root-owned sticky + ancestor. +- In a container deployment, check the owner and mode as seen by the runtime user. Run the + product's production configuration check, then confirm readiness. To verify a CA or key set, + also exercise an operation that connects to the configured peer or verifies its token. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, JwksSource, DatabaseConfig, DatabaseMember; + crates/registry-platform-config/src/loader.rs, require_trusted_runtime_path; + crates/registry-platform-config/src/secrets.rs, SecretResolver, resolve_public_document, open_secret_file; + crates/registry-platform-config/src/secrets_tests.rs, a_public_document_drops_only_the_read_checks, a_public_document_holding_a_private_key_is_refused; + crates/registry-breg/src/action_evidence_config.rs, public_jwks_document. */} + ## Check BReg and Casework authority 1. Use separate migration and runtime database roles with TLS. Run the product's doctor against diff --git a/docs/site/src/content/docs/security/messaging.mdx b/docs/site/src/content/docs/security/messaging.mdx index 4b6ccfc23a..7307ba028c 100644 --- a/docs/site/src/content/docs/security/messaging.mdx +++ b/docs/site/src/content/docs/security/messaging.mdx @@ -360,6 +360,13 @@ The boundaries hold only if your deployment does the following. queued, `unknown` and retained callback work has settled; or drain or cancel those messages first. Same receiver credential rotation needs none of this. +14. Write `secretProviders.file.mountPolicy: compose-native` only for a container that runs + Messaging alone under one runtime identity. + The setting accepts root-owned Compose secret mounts at mode `0444`, which every user in the + container can read. + Startup and `messagingctl check` report it as `platform.posture.compose-native-secret-mount`. + Without it, stage the secret directory with the hardened owner and mode instead. + A static JWKS or CA bundle is a public document and needs no setting. {/* Evidence: crates/registry-messaging-core/src/package.rs idempotent_submit, accept_duplicates; crates/registry-messaging/src/package.rs a_symbolic_link_anywhere_in_the_package_is_refused; @@ -370,7 +377,9 @@ The boundaries hold only if your deployment does the following. crates/registry-messaging/src/config.rs runtime_reads_the_explicit_http_issuer_opt_in; crates/registry-messaging/src/http_provider/aws_tests.rs aws_settings; crates/registry-messaging/tests/postgres_messages.rs - an_exact_retry_across_an_audit_key_rotation_replays_and_never_sends_again. */} + an_exact_retry_across_an_audit_key_rotation_replays_and_never_sends_again; + crates/registry-platform-config/src/blocks.rs COMPOSE_NATIVE_SECRET_MOUNT; + crates/registry-platform-config/src/secrets.rs resolve_public_document. */} ## Accepted residuals diff --git a/docs/site/src/content/docs/security/render.mdx b/docs/site/src/content/docs/security/render.mdx index 1a5e076457..238998c31c 100644 --- a/docs/site/src/content/docs/security/render.mdx +++ b/docs/site/src/content/docs/security/render.mdx @@ -217,6 +217,13 @@ rules only. crates/registry-render/src/pdf_signature.rs sealable_holds_pdf_a_1_2_and_3_to_their_string_length_limits. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## How refusals are recorded For OIDC bearer requests, Render matches the exact entry in `authentication.oidc.issuers`. diff --git a/docs/site/src/content/docs/security/scheduling.mdx b/docs/site/src/content/docs/security/scheduling.mdx index 85bc2bda3d..ee594067b7 100644 --- a/docs/site/src/content/docs/security/scheduling.mdx +++ b/docs/site/src/content/docs/security/scheduling.mdx @@ -202,6 +202,13 @@ The guarantees hold only when you meet these obligations. crates/registry-schedulingctl/tests/activation_postgres.rs an_apply_whose_response_audit_entry_is_refused_reports_it_applied_unaudited. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals Each residual names the condition under which it applies, its consequence, the operator diff --git a/docs/site/src/content/docs/security/session.mdx b/docs/site/src/content/docs/security/session.mdx index 996388e1cb..9130bc5f7f 100644 --- a/docs/site/src/content/docs/security/session.mdx +++ b/docs/site/src/content/docs/security/session.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-27" +last_reviewed: "2026-12-01" doc_type: explanation locale: en standards_referenced: [] @@ -78,9 +78,17 @@ A module's `signIns` list routes kinds of sessions, but grants no product permis A private bind alone does not establish that restriction. 4. Regenerate the gateway fragments after every runtime change. Splice them and verify the assembled static configuration before deploying it. + For a checked standalone assembly, regenerate the assembly and re-export the inventory after + every runtime change. The inventory describes every configured module and page and names one + selected browser binding. Its two digests bind the Envoy JSON bytes and the sign-in projection. + Envoy and Session enforce the live routing and sign-in policy. 5. Terminate TLS in front of the public listener. The service accepts `development-loopback` only in development posture. Use it for local HTTP in a browser that supports `Secure` cookies on loopback. + For checked browser route export, use the dedicated loopback HTTPS Envoy assembly and deploy + the verified configuration. The browser verifies the ingress certificate. The operator + controls the gateway namespace, private Session sockets and upstream endpoints. + The standalone HTTPS assembly requires TLS 1.2 or later. 6. Name every host HTTP filter in `gateway.hostFilters`. Retain a filter on a module or page only through `upstream.keepHostFilters`. A retained filter must preserve the path, route cache and authorisation header. @@ -97,6 +105,13 @@ A module's `signIns` list routes kinds of sessions, but grants no product permis crates/registry-session/src/public.rs sign_out; crates/registry-session/README.md. */} +Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The +explicit `secretProviders.file.mountPolicy: compose-native` setting lets every user in the +container read root-owned `0444` secret mounts. Write it only for a container that runs this +service alone under one runtime identity. + +{/* Evidence: crates/registry-platform-config/src/blocks.rs, COMPOSE_NATIVE_SECRET_MOUNT. */} + ## Accepted residuals ### SESSION-RES-01: a restart loses sessions diff --git a/docs/site/src/content/docs/start/adopt.mdx b/docs/site/src/content/docs/start/adopt.mdx index 33f506d416..e432783e7b 100644 --- a/docs/site/src/content/docs/start/adopt.mdx +++ b/docs/site/src/content/docs/start/adopt.mdx @@ -140,28 +140,35 @@ Your team owns four things: That answer means that the first request completed. Read its result, such as the Record or the Proposal, and do not send the request again. -Each product still checks every call itself and stores its own results. - -Some sequences of steps run for days or weeks. -For example: ask a reviewer, wait for the decision, then send the applicant a notice. -Add [Registry Coordinator](../../reference/glossary/#registry-coordinator) only when such a -sequence must continue without a person or a running script keeping track of it. -Coordinator runs the sequence as a reviewed workflow. -It keeps the workflow going across long waits, outages, and restarts. -Read the [Coordinator overview](../coordinator/) for more. - -Review alone does not need Coordinator. -Your application can prepare a Proposal, get a Casework review, and have BReg apply it. -A Proposal is a change that BReg holds before it applies it. -BReg freezes exactly what will change when the Proposal is submitted. -Where the Action requires a review, BReg applies the change only after approval. - Add [Registry Messaging](../../reference/glossary/#registry-messaging) only when the application must send messages from templates that were reviewed in advance. Messaging sends one message to one destination over one channel, such as SMS or email. It sends through a messaging provider that is configured for your deployment. It then reports what it knows about delivery. +### Choose a service function or a Coordinator flow + +Use a service function when the work finishes within one request, such as preparing the input +for a licence renewal. The function holds no authority of its own. It asks the owning product +to make the change, and the product checks the caller's authority and stores the result. + +Use a [Registry Coordinator](../coordinator/) flow when the work must wait or someone needs to +review the procedure's steps. For example, the flow can ask for a review, wait for the +decision, and then send the applicant a notice. Call a service function for a step the flow +cannot express. If you write the whole procedure as function code, you give up the drawing +and the record of each step. See [how to choose a service function or a flow](../../configure/run-a-project-with-rstack-dev/#choose-a-service-function-or-a-coordinator-flow). + +If the work is a single review of a BReg change, your application can submit a Proposal to +BReg and let BReg and Casework handle the review. BReg freezes what will change when the +Proposal is submitted. Where the Action requires review, BReg applies the change only after +approval. + +{/* Evidence: crates/registry-coordinator/src/definition.rs, Step::WaitUntil, Step::WaitFor; + crates/registry-coordinator/src/cli.rs, render_explain; + crates/registry-coordinator/src/store.rs, RunInspection; + crates/registry-breg/src/api/actions.rs, authorize_action_mode; + products/breg/contracts/security-invariant-matrix.yaml. */} + ## Run your own module On this page, a module is a service or worker that you write, deploy, and run yourself. diff --git a/docs/site/src/content/docs/start/breg-quickstart.mdx b/docs/site/src/content/docs/start/breg-quickstart.mdx index 95e9457ef1..989cf0e4bd 100644 --- a/docs/site/src/content/docs/start/breg-quickstart.mdx +++ b/docs/site/src/content/docs/start/breg-quickstart.mdx @@ -58,6 +58,8 @@ journal stay on, so the local registry checks each request the way a deployed on ## Then follow your role - **You build applications on a registry.** Keep the + [preview a business registration service](../../tutorials/preview-a-breg-service/) to submit a + test registration from your browser. Keep the [client reference](../../reference/breg-client-capabilities/) open, then [send registry events to a webhook](../../tutorials/send-registry-events-to-a-webhook/) to connect the registry to the systems around it. diff --git a/docs/site/src/content/docs/start/coordinator.mdx b/docs/site/src/content/docs/start/coordinator.mdx index fa5ad46650..22ce72f66b 100644 --- a/docs/site/src/content/docs/start/coordinator.mdx +++ b/docs/site/src/content/docs/start/coordinator.mdx @@ -39,9 +39,9 @@ cannot restore that definition holds the run. A workflow is built from five step types: - `call` runs one product operation. -- `choose` routes on one typed value, on a pure [Function](../../reference/glossary/#function) +- `choose` routes on one typed value, on a pure [Transform](../../reference/glossary/#function) written in bounded [Rhai](../../reference/glossary/#rhai), or on a `compare` of typed values that - needs no Function. In a `compare`, a value that is missing or of the wrong type fails the run + needs no Transform. In a `compare`, a value that is missing or of the wrong type fails the run instead of routing to `unmatched`. The `present` test is the exception, because it reads absence. - `wait-until` waits for an instant. - `wait-for` waits for a named result, such as a Casework review decision. @@ -49,7 +49,7 @@ A workflow is built from five step types: `coordinatorctl check` compiles the project offline. It proves that each step a mapping reads has run on every route that reaches it, and it checks each path against the declared schemas. Values a -schema leaves open, and values a Function computes, are left to scenarios and the runtime. +schema leaves open, and values a Transform computes, are left to scenarios and the runtime. `coordinatorctl package` freezes the project into an immutable [package](../../reference/glossary/#package) whose digest the deployment pins. @@ -63,7 +63,7 @@ schema leaves open, and values a Function computes, are left to scenarios and th An authorised caller starts a run with `POST /v1/runs`, giving the expected workflow revision, its input, and an idempotency key. An authored event trigger can also start one from a signed product -event at `POST /v1/events/{workflow}/{trigger}`, and an authored calendar trigger starts one on a +event at `POST /v1/events/{workflowId}/{triggerId}`, and an authored calendar trigger starts one on a schedule with no caller. The same key with the same revision and input returns the same run, and the [API reference](../../reference/apis/registry-coordinator/) states what a conflicting reuse gets. diff --git a/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx b/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx index e3e8cbe096..cd739f3656 100644 --- a/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx +++ b/docs/site/src/content/docs/tutorials/build-and-deploy-evidence-project.mdx @@ -166,7 +166,7 @@ Project: adult-status Target: deploy-target/target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. error[evidence.target.production-assurance-required] deploy-target/target.yaml:/assuranceProfile --production requires production or evidence-grade target assurance next: Correct the selected project or target artifact and rerun check. @@ -266,7 +266,7 @@ rstack evidence runtime check --runtime-config candidate/runtime.yaml Evidence package sha256: passed check (4 requirements) Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx b/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx index 9cc5c75d62..1bc4d47e44 100644 --- a/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx +++ b/docs/site/src/content/docs/tutorials/connect-a-sqlite-extract.mdx @@ -149,7 +149,7 @@ Project: . Target: local-target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. @@ -206,7 +206,7 @@ Project: . Target: local-target.yaml Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx b/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx index 1ae3afe88c..c7f54aa775 100644 --- a/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx +++ b/docs/site/src/content/docs/tutorials/connect-an-institution-source.mdx @@ -93,7 +93,7 @@ Target: local-target.yaml Deployment inputs missing: signer.publicJwkFile; the compiled-target bundle check was skipped. Supply them and rerun check to prove the target. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. diff --git a/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx b/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx index ecb69dd237..3dcbce3163 100644 --- a/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx +++ b/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx @@ -227,7 +227,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.household.example.test products: - - {product: breg, project: ., audience: "urn:example:household-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:household-registry" people: operator: subject: household-registry-operator diff --git a/docs/site/src/content/docs/tutorials/first-breg.mdx b/docs/site/src/content/docs/tutorials/first-breg.mdx index b11b1ebdca..559455591b 100644 --- a/docs/site/src/content/docs/tutorials/first-breg.mdx +++ b/docs/site/src/content/docs/tutorials/first-breg.mdx @@ -120,16 +120,19 @@ accessProfiles: `rstack dev` runs the project on your machine from a development plan. The plan lists the products to run and the synthetic people who call them, with the claims each person's test token carries. -`rstack breg init` wrote a starter `service.yaml`, `dev.yaml` and `dev-journeys.yaml`. Replace `dev.yaml` with this -plan, which gives the test caller `editor` the claim `zone-a` and `foreign-editor` the claim -`zone-b`: +`rstack breg init` already wrote the plan you need, so you do not change any file in this step. +Open `dev.yaml`. It gives the test caller `editor` the claim `zone-a` and `foreign-editor` the +claim `zone-b`: -```yaml title="dev.yaml" test-file -apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 -kind: RStackDev +```yaml title="dev.yaml" test-excerpt="dev.yaml" issuer: https://identity.directory.example.test products: - - {product: breg, project: ., audience: "urn:example:local-directory"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:local-directory" people: editor: subject: synthetic-directory-editor @@ -137,31 +140,27 @@ people: roles: [directory-editor] claims: breg: {jurisdiction: zone-a} + purposes: {breg: directory-administration} foreign-editor: subject: synthetic-foreign-editor client: directory-editor roles: [directory-editor] claims: breg: {jurisdiction: zone-b} -# Both people match the profile, so each journey step names its person. -schemaTestPeople: - directory-contact: - create-contact: editor - read-contact: editor - conceal-contact-outside-jurisdiction: foreign-editor - obtain-email-condition: editor - update-contact-email: editor - read-updated-contact: editor - start-registration: editor - submit-registration: editor + purposes: {breg: directory-administration} +# Both people match the editor profile, so each schema-test step names its person. journeyFile: dev-journeys.yaml ``` +Each person's `roles` entry refers to a role in `service.yaml`, which selects the +`directory-editor` access profile for them. Each step in `tests/journeys.yaml` names the person who +runs it with `actor`. + The plan's `journeyFile` names the HTTP requests that `rstack dev` sends once the registry is -running. Replace `dev-journeys.yaml` at the project root with a journey that adds one contact in -`zone-a` as `editor` and reads it back. +running. Open `dev-journeys.yaml` at the project root. Its journey adds one contact in `zone-a` as +`editor` and reads it back: -```yaml title="dev-journeys.yaml" test-file +```yaml title="dev-journeys.yaml" test-excerpt="dev-journeys.yaml" apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 kind: RStackJourneys journeys: diff --git a/docs/site/src/content/docs/tutorials/first-casework.mdx b/docs/site/src/content/docs/tutorials/first-casework.mdx index 105d9aac0f..ea91b08158 100644 --- a/docs/site/src/content/docs/tutorials/first-casework.mdx +++ b/docs/site/src/content/docs/tutorials/first-casework.mdx @@ -110,67 +110,13 @@ Casework keeps the snapshot the producer sends and refuses each listed case. ## Describe the local run -`rstack dev` runs the project on your machine from a plan file. First tell Casework which issuer -and subject the producer's tokens carry. The template trusts a fixed local address, and a run signs -its test tokens under an HTTPS issuer name of your choosing: - -```diff test-edit title="casework.yaml" - trustedProducers: - requester: - profile: requester -- issuer: http://127.0.0.1:8093 -- subject: b75315b2-5854-70f3-8867-511dd771a6da -+ issuer: https://identity.standalone.example.test -+ subject: requester -``` +`rstack dev` uses the generated `dev.yaml`. The plan issues test tokens under the requester's +issuer and subject in `casework.yaml`. -Replace the generated plan with the following plan. It lists the product, test people and the roles they hold. It names a journey file, which -runs when the run starts: - -```yaml title="dev.yaml" test-file -apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 -kind: RStackDev -issuer: https://identity.standalone.example.test -products: - - {product: casework, project: ., audience: "urn:example:standalone-decision"} -people: - administrator: - subject: administrator - client: standalone-workbench - roles: [administrator] - staff: - subject: staff - client: standalone-workbench - roles: [staff] - requester: - subject: requester - client: standalone-requester - roles: [requester] -journeyFile: dev-journeys.yaml -``` +{/* Evidence: crates/registry-caseworkctl/src/project.rs, STANDALONE_YAML, development_plan. */} -A new Casework directory has no staff. The journey has the administrator seat one team on the -`decisions` queue and put the person `staff` in it: - -```yaml title="dev-journeys.yaml" test-file -apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 -kind: RStackJourneys -journeys: - - id: staff-the-queue - steps: - - id: staff-the-queue - product: casework - as: administrator - method: POST - path: /v1/directory/bootstrap - headers: {If-Match: '"0"', Idempotency-Key: staff-the-queue} - body: - teamId: decisions-team - staff: [{issuer: https://identity.standalone.example.test, subject: staff}] - supervisors: [] - queueId: decisions - expect: {status: 200} -``` +Keep the generated `dev.yaml` and `dev-journeys.yaml`. The starter journey checks the +running service. You'll staff the empty directory with the administrator after startup. ## Start the run @@ -184,7 +130,7 @@ run_id="$(jq -r .run_id run.json)" casework_url="$(jq -r .products.casework run.json)" ``` -PostgreSQL runs in Docker, and the run has seated one staff team. Its state, keys and logs live in +PostgreSQL runs in Docker. Its state, keys and logs live in the run's own owner-only directory, outside your project. Each call below needs a short-lived token for one of the plan's people. This function asks for one and prints the header file to pass to curl: @@ -197,6 +143,33 @@ headers_for() { {/* Evidence: crates/registry-rstack-dev/src/lib.rs; crates/registry-rstack/tests/dev_run.rs, casework_alone_runs_end_to_end; products/casework/examples/standalone-decision/dev.yaml. */} +## Staff the review queue + +Save the directory bootstrap as `directory-bootstrap.json`. It seats one team on +the `decisions` queue and names the staff person's issuer and subject from `dev.yaml`. + +```json title="directory-bootstrap.json" test-file +{ + "teamId": "decisions-team", + "queueId": "decisions", + "staff": [{"issuer": "https://identity.casework.example.test", "subject": "staff"}], + "supervisors": [] +} +``` + +Send it as the administrator. The `If-Match` header names revision zero, the empty directory. + +```sh +curl -sS --fail-with-body --header @"$(headers_for administrator)" \ + --header 'Content-Type: application/json' \ + --header 'If-Match: "0"' \ + --header 'Idempotency-Key: staff-the-queue' \ + --data @directory-bootstrap.json "$casework_url/v1/directory/bootstrap" +``` + +{/* Evidence: crates/registry-casework/src/http.rs, bootstrap(); + crates/registry-casework-core/src/http.rs, BootstrapDirectoryRequest. */} + ## Submit a ReviewRequest Save the request. It names the policy, the subject under review, and the snapshot a reviewer will @@ -293,7 +266,7 @@ claimed_revision="$(jq -r .revision claimed.json)" ```json test-excerpt { "revision": 2, - "state": {"held": {"holder": {"issuer": "https://identity.standalone.example.test", "subject": "staff"}}} + "state": {"held": {"holder": {"issuer": "https://identity.casework.example.test", "subject": "staff"}}} } ``` diff --git a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx index d012a8a293..301f13da4a 100644 --- a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx +++ b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx @@ -87,7 +87,7 @@ Target: local-target.yaml Deployment inputs missing: signer.publicJwkFile; the compiled-target bundle check was skipped. Supply them and rerun check to prove the target. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/issuer. An issuer endpoint uses plain HTTP on loopback. Explicit production setting platform.posture.issuer-loopback-plaintext at /authentication/oidc/issuers/primary/jwksSource/uri. An issuer endpoint uses plain HTTP on loopback. -Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. admits a token from every client this issuer signs for. +Explicit production setting platform.posture.unrestricted-clients at /authentication/oidc/issuers/primary/allowedClients. Admits a token from every client this issuer signs for. warning[evidence.posture.local-assurance] local-target.yaml /assuranceProfile local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. @@ -161,7 +161,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: run products: - - {product: evidence, project: ., audience: "urn:example:resource:standalone-evidence"} + evidence: + projects: + evidence: + path: . +audiences: + evidence: "urn:example:resource:standalone-evidence" people: caller: subject: "urn:registrystack:evidence:local:client:example-caller" diff --git a/docs/site/src/content/docs/tutorials/first-messaging.mdx b/docs/site/src/content/docs/tutorials/first-messaging.mdx index 73ebb066ec..8ac44663f2 100644 --- a/docs/site/src/content/docs/tutorials/first-messaging.mdx +++ b/docs/site/src/content/docs/tutorials/first-messaging.mdx @@ -81,7 +81,10 @@ reports ready. The plan holds no keys and no addresses: ```yaml title="dev.yaml" test-excerpt="tutorial-work/notices/dev.yaml" issuer: https://identity.starter.example.test products: - - {product: messaging, project: ., audience: "urn:example:messaging"} + messaging: + path: . +audiences: + messaging: "urn:example:messaging" people: case-system: subject: case-system diff --git a/docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx b/docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx new file mode 100644 index 0000000000..932fa53978 --- /dev/null +++ b/docs/site/src/content/docs/tutorials/preview-a-breg-service.mdx @@ -0,0 +1,113 @@ +--- +title: Preview a business registration service +description: Run the business registration starter, submit a test registration in your browser, and read the resulting Record from Base Registry Engine. +status: draft +owner: registry-docs +source_repos: + - registry-stack +last_reviewed: unreviewed +doc_type: tutorial +persona: + - data publisher + - operator +locale: en +standards_referenced: [] +tutorial_test: + toolset: breg + skip: The browser preview uses the matching release checkout, npm package, Node.js 24 and Docker. Replay it with the service preview acceptance tools. +--- + +import QuickstartMeta from '../../../components/QuickstartMeta.astro'; + +If you are building a service on Base Registry Engine (BReg), try the business registration +starter. You will run it on your machine, register a test business from a browser form, and see +the Record that BReg returns. + + + +## Scaffold the preview + +Start in an empty working directory. Use the Registry Stack release selected in the docs +version picker and install the BReg component from that release. Replace `` with the +release number, without the leading `v`. Copy the business registration starter from its source tag. + +```sh +version='' +rstack breg --version +git clone --depth 1 --branch "v${version}" https://github.com/registrystack/registry-stack.git registry-stack-preview-source +cp -R registry-stack-preview-source/products/platform/examples/service-previews/business-registration ./business-registration +``` + +Check that the reported tool version matches ``. +You now have a `business-registration` directory with a registry project, a browser page, and a +registration function. If Git cannot find the tag, check the release number in the verified +installer's filename. If the starter is missing, choose a release that includes the preview. + +## Install the client + +Install the published client for the release you selected. npm saves that exact version in your +copy of the starter. Run the remaining commands from the preview directory. + +```sh +cd business-registration +npm install --save-exact "@registrystack/client@${version}" +``` + +If npm cannot find the version, check the package version against the Registry Stack release you +installed. Use the same version for both. + +{/* Evidence: crates/registry-rstack/src/cli.rs, generate_client(); clients/typescript/package.json. */} + +## Start the preview + +Use synthetic data and trusted code on a trusted machine. The preview runs as a test registrar. +Other processes and users on the same host can reach the loopback URL. + +Check the development plan and start a local run. + +```sh +rstack dev check . +rstack dev start . --ttl 30m +``` + +If the check fails, use the file and field named in its diagnostic. The first start may download +the PostgreSQL image. If start fails, check that Docker is running and read the diagnostic. +Keep the run ID and open the URL marked `Application` in the start report. + +{/* Evidence: crates/registry-rstack/src/cli.rs, dispatch_dev; crates/registry-rstack-dev/src/lib.rs, start(). */} + +## Register a test business + +In the browser, enter `Example Supply Cooperative` for **Business name** and +`BR-TUTORIAL-001` for **Registration number**. Select **Register business**. + +The **Business registered** confirmation shows the name, registration number and Record ID +read back from BReg. Reload the page and use a fresh number to repeat the exercise in the same run. + +{/* TODO[evidence]: Bind the business-registration page and its native browser acceptance source when the preview release baseline lands. */} + +## Stop the preview + +Replace `` with the ID from the start report. The `--clean` flag deletes the managed +development data for this preview. + +```sh +RUN='' +rstack dev stop "$RUN" --clean +``` + +The stop report confirms the run stopped. + +## Next + +[Generate clients for your own projects](../../reference/typescript-clients/) diff --git a/docs/site/src/data/cli-reference.yaml b/docs/site/src/data/cli-reference.yaml index 499eb78b0c..c44a06ee35 100644 --- a/docs/site/src/data/cli-reference.yaml +++ b/docs/site/src/data/cli-reference.yaml @@ -12,4 +12,4 @@ status: current last_reviewed: 2026-11-28 unreviewed_binaries: [adapter, adapter-job, adapterctl, coordinator, coordinatorctl, documents, documentsctl, evidence-oid4vp, manifest, registry-mcp, registry-session, rstack, discovery, discoveryctl] -source_build_only_binaries: [adapter-job, evidence-oid4vp, registry-mcp, registry-session] +source_build_only_binaries: [adapter-job, evidence-oid4vp, registry-mcp] diff --git a/docs/site/src/data/coordinator-api.yaml b/docs/site/src/data/coordinator-api.yaml index cab253d937..8927909ca0 100644 --- a/docs/site/src/data/coordinator-api.yaml +++ b/docs/site/src/data/coordinator-api.yaml @@ -53,15 +53,15 @@ rows: - ['`GET`', '`/health`', 'None', '`200` with `{"live":true}` while the process answers.'] - ['`GET`', '`/ready`', 'None', '`200` with `{"ready":true}`, or `503` with `{"ready":false}` while the service cannot accept work.'] - - ['`GET`', '`/v1/workflows/{workflow}`', 'Bearer, `start` on the named workflow', 'Discover the active revision, input schema, and declared outcomes.'] + - ['`GET`', '`/v1/workflows/{workflowId}`', 'Bearer, `start` on the named workflow', 'Discover the active revision, input schema, and declared outcomes.'] - ['`POST`', '`/v1/runs`', 'Bearer, `start` on the named workflow', 'Start one run with the expected `workflowRevision` and an `Idempotency-Key`.'] - ['`GET`', '`/v1/runs`', 'Bearer, `status`', 'List at most 100 of the most recently admitted runs the caller may see, newest first.'] - - ['`GET`', '`/v1/runs/{run}`', 'Bearer, `status`', 'Read one run''s progress and its reviewed terminal output.'] - - ['`GET`', '`/v1/runs/{run}/inspect`', 'Bearer, `inspect`', 'Read bounded steps, accepted or unknown effects, durable wait budgets, and available recovery actions.'] - - ['`POST`', '`/v1/runs/{run}/cancel`', 'Bearer, `cancel`', 'Stop future dispatch where possible, without rolling back an accepted effect.'] - - ['`POST`', '`/v1/runs/{run}/check`', 'Bearer, `inspect`', 'Read a waiting step''s product now, no sooner than the read floor after its last read, counting against the wait''s read budget. Body `{"step":"..."}`.'] - - ['`POST`', '`/v1/runs/{run}/reconcile`', 'Bearer, `reconcile`', 'Settle an uncertain call from the receiving product''s original-key receipt.'] - - ['`POST`', '`/v1/runs/{run}/retry-same`', 'Bearer, `retry-same`', 'Schedule held work again with its original command, key, binding, and authority.'] + - ['`GET`', '`/v1/runs/{runId}`', 'Bearer, `status`', 'Read one run''s progress and its reviewed terminal output.'] + - ['`GET`', '`/v1/runs/{runId}/inspect`', 'Bearer, `inspect`', 'Read bounded steps, accepted or unknown effects, durable wait budgets, and available recovery actions.'] + - ['`POST`', '`/v1/runs/{runId}/cancel`', 'Bearer, `cancel`', 'Stop future dispatch where possible, without rolling back an accepted effect.'] + - ['`POST`', '`/v1/runs/{runId}/check`', 'Bearer, `inspect`', 'Read a waiting step''s product now, no sooner than the read floor after its last read, counting against the wait''s read budget. Body `{"step":"..."}`.'] + - ['`POST`', '`/v1/runs/{runId}/reconcile`', 'Bearer, `reconcile`', 'Settle an uncertain call from the receiving product''s original-key receipt.'] + - ['`POST`', '`/v1/runs/{runId}/retry-same`', 'Bearer, `retry-same`', 'Schedule held work again with its original command, key, binding, and authority.'] - ['`GET`', '`/v1/doctor`', 'Bearer, operator', 'Report activation, audit readiness, holds, and run counts.'] - ['`POST`', '`/v1/restore-hold`', 'Bearer, operator', 'Place the restore hold, which stops dispatch and admissions.'] - ['`POST`', '`/v1/release-restore-hold`', 'Bearer, operator', 'Release the restore hold once no held work is unresolved.'] @@ -69,4 +69,4 @@ - ['`POST`', '`/v1/complete-execution-recovery`', 'Bearer, operator', 'Attest complete execution history and prior fencing while the restore hold remains.'] - ['`POST`', '`/v1/retention`', 'Bearer, operator', 'Erase eligible terminal payloads that ended before a cutoff.'] - ['`POST`', '`/v1/review-completions`', 'Standard Webhooks signature using the key selected by the recipient binding', 'Bring forward the next result read of a run waiting on that review request.'] - - ['`POST`', '`/v1/events/{workflow}/{trigger}`', 'Standard Webhooks signature using the key for the trigger URL', 'Admit one run per exact authenticated event and trigger; exact redelivery returns the same run.'] + - ['`POST`', '`/v1/events/{workflowId}/{triggerId}`', 'Standard Webhooks signature using the key for the trigger URL', 'Admit one run per exact authenticated event and trigger; exact redelivery returns the same run.'] diff --git a/products/adapter/examples/dev-starter/dev.yaml b/products/adapter/examples/dev-starter/dev.yaml index e274de8086..0765c6784c 100644 --- a/products/adapter/examples/dev-starter/dev.yaml +++ b/products/adapter/examples/dev-starter/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: adapter, project: ., audience: "urn:example:adapter"} + adapter: + path: . +audiences: + adapter: "urn:example:adapter" people: reader: subject: starter-reader diff --git a/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml b/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml index e449f06d23..dd9a02a1e2 100644 --- a/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml +++ b/products/adapter/examples/kobotoolbox-job/workflow/workflow.yaml @@ -40,7 +40,7 @@ contracts: households: type: breg source: generated/households.contract.json -functions: +transforms: proposal-request: runtime: rhai source: functions.rhai @@ -132,8 +132,8 @@ workflow: type: call operation: submit-household input: - type: function - function: proposal-request + type: transform + transform: proposal-request inputs: event: {type: input, path: /event} next: await-proposal @@ -155,8 +155,8 @@ workflow: type: call operation: lookup-household input: - type: function - function: lookup-request + type: transform + transform: lookup-request inputs: event: {type: input, path: /event} next: review-resolved @@ -165,8 +165,8 @@ workflow: type: call operation: submit-review input: - type: function - function: resolved-review-request + type: transform + transform: resolved-review-request inputs: event: {type: input, path: /event} lookup: {type: step, step: lookup-revised} @@ -181,8 +181,8 @@ workflow: type: call operation: submit-review input: - type: function - function: unresolved-review-request + type: transform + transform: unresolved-review-request inputs: event: {type: input, path: /event} next: await-unresolved-review @@ -196,8 +196,8 @@ workflow: type: call operation: submit-review input: - type: function - function: returned-review-request + type: transform + transform: returned-review-request inputs: event: {type: input, path: /event} next: await-returned-review diff --git a/products/adapter/schemas/job-runtime.v1alpha1.schema.json b/products/adapter/schemas/job-runtime.v1alpha1.schema.json index 8cd2717407..65edca9821 100644 --- a/products/adapter/schemas/job-runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/job-runtime.v1alpha1.schema.json @@ -123,8 +123,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -850,6 +857,12 @@ } ] }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/adapter/schemas/runtime.v1alpha1.schema.json b/products/adapter/schemas/runtime.v1alpha1.schema.json index ba0b9c1e61..1292518000 100644 --- a/products/adapter/schemas/runtime.v1alpha1.schema.json +++ b/products/adapter/schemas/runtime.v1alpha1.schema.json @@ -306,8 +306,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -699,6 +706,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 5f688e05c8..aed26eb2eb 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- The Evidence provider `trustedJwksRef` key set is read as a public document + and refused when it holds a private or symmetric member. + ## 0.49.0 - 2026-12-01 - BREAKING: `bregctl data export` JSONL uses `recordId` and `revisionId` in place of v0.48.0's `recordIdentifier` and `revisionIdentifier`. Migration: Update export file consumers for both keys. Finish an in-progress export with the matching v0.48.0 `bregctl`, serving runtime, and compiled package before upgrading, or start a fresh output and checkpoint pair after upgrading. Convert archived exports on a separate copy to preserve any checkpoint digest. diff --git a/products/breg/acceptance/facility/dev.yaml b/products/breg/acceptance/facility/dev.yaml index c8c2911286..d86658c668 100644 --- a/products/breg/acceptance/facility/dev.yaml +++ b/products/breg/acceptance/facility/dev.yaml @@ -4,7 +4,12 @@ kind: RStackDev # BReg alone. The project-root dev-journeys.yaml holds the run's HTTP requests. issuer: https://identity.facility.example.test products: - - {product: breg, project: ., audience: "urn:example:facility-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:facility-registry" people: facility-operator: subject: synthetic-facility-operator diff --git a/products/breg/acceptance/generated-identifiers/dev.yaml b/products/breg/acceptance/generated-identifiers/dev.yaml index 4f4f9a16ea..fc14412f2a 100644 --- a/products/breg/acceptance/generated-identifiers/dev.yaml +++ b/products/breg/acceptance/generated-identifiers/dev.yaml @@ -5,7 +5,12 @@ kind: RStackDev # key under this logical issuer. issuer: https://identity.identifiers.example.test products: - - {product: breg, project: ., audience: "urn:example:generated-identifiers"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:generated-identifiers" people: clerk-a: subject: synthetic-clerk-a diff --git a/products/breg/acceptance/issuer-portability/dev.yaml b/products/breg/acceptance/issuer-portability/dev.yaml index ea27d913e5..f8926cbe3a 100644 --- a/products/breg/acceptance/issuer-portability/dev.yaml +++ b/products/breg/acceptance/issuer-portability/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # root so bregctl discovers native schema checks under tests/ independently. issuer: https://identity.portability.example.test products: - - {product: breg, project: ., audience: "urn:example:issuer-portability"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:issuer-portability" people: clerk-service: subject: urn:institution:service-clerk diff --git a/products/breg/acceptance/reviewed-evidence-journey/dev.yaml b/products/breg/acceptance/reviewed-evidence-journey/dev.yaml index a27097f2ee..aa3ca3e072 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/dev.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/dev.yaml @@ -3,8 +3,15 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://issuer.example.test products: - - {product: breg, project: registry, audience: "urn:journey:breg"} - - {product: casework, project: casework, audience: "urn:journey:casework"} + breg: + projects: + breg: + path: registry + casework: + path: casework +audiences: + breg: "urn:journey:breg" + casework: "urn:journey:casework" bindings: bregReviewAuthority: {id: casework, producer: registry, identity: producer} caseworkContextProvider: {id: registry, identity: context-status, action: correct-status} diff --git a/products/breg/acceptance/spatial-service-sites/dev.yaml b/products/breg/acceptance/spatial-service-sites/dev.yaml index bca4e01c4d..7c3cf385fd 100644 --- a/products/breg/acceptance/spatial-service-sites/dev.yaml +++ b/products/breg/acceptance/spatial-service-sites/dev.yaml @@ -5,7 +5,12 @@ kind: RStackDev # at the project root and BReg's native schema checks under tests/. issuer: https://identity.service-sites.example.test products: - - {product: breg, project: ., audience: "urn:example:service-sites"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:service-sites" people: operator: subject: synthetic-service-site-admin diff --git a/products/breg/evidence/registry/dev.yaml b/products/breg/evidence/registry/dev.yaml index dea45ba6ac..ca1323f235 100644 --- a/products/breg/evidence/registry/dev.yaml +++ b/products/breg/evidence/registry/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.evidence.example.test products: - - product: breg - project: . - audience: urn:example:evidence-registry + breg: + projects: + breg: + path: . +audiences: + breg: urn:example:evidence-registry people: operator: subject: generic-registry-operator diff --git a/products/breg/examples/external-views/dev.yaml b/products/breg/examples/external-views/dev.yaml index 2aefa7a286..7556746dab 100644 --- a/products/breg/examples/external-views/dev.yaml +++ b/products/breg/examples/external-views/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://fixture-issuer.example.test/licensing products: - - product: breg - project: . - audience: urn:breg:external-views-fixture + breg: + projects: + breg: + path: . +audiences: + breg: urn:breg:external-views-fixture people: officer: subject: synthetic-licensing-officer diff --git a/products/breg/examples/facility/dev.yaml b/products/breg/examples/facility/dev.yaml index a07bb123d4..56296ed27c 100644 --- a/products/breg/examples/facility/dev.yaml +++ b/products/breg/examples/facility/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # and BReg's native schema checks under tests/. issuer: https://identity.facility.example.test products: - - {product: breg, project: ., audience: "urn:example:facility-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:facility-registry" people: operator-editor: subject: synthetic-operator-editor diff --git a/products/breg/examples/formats/identity-facts-report.json b/products/breg/examples/formats/identity-facts-report.json new file mode 100644 index 0000000000..d9dd14156c --- /dev/null +++ b/products/breg/examples/formats/identity-facts-report.json @@ -0,0 +1,44 @@ +{ + "ok": true, + "command": "generate", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "kind": "BRegCtlReport", + "version": "0.49.0", + "artifacts": [ + { + "byteLength": 802, + "mediaType": "application/yaml", + "path": "identity-facts.yaml", + "sha256": "d6061ec53e023e24401cbff448cfea3f900c78747956ec97265b6b3da64a4f62" + } + ], + "explanation": { + "identityFacts": { + "accessProfiles": 3, + "claims": 4 + } + }, + "profile": "authoring", + "revision": "sha256:a850cc821c54ce783ab57c4d271edb7e8f8d2fc16fc8dca172bc6320f137a385", + "posture": { + "value": "production", + "source": "default" + }, + "diagnostics": [ + { + "artifact": "BRegModule", + "code": "breg.record-type.stored-field-unfillable", + "message": "this optional stored field has no writable access grant, fixed Action set, function-plan write, or import that can supply a value; add the field to one of those writers, or remove the field", + "path": "/extendRecordTypes/record/fields/0", + "rank": "hygiene", + "severity": "warning", + "source": { + "column": 9, + "file": "modules/record-notes/module.yaml", + "line": 19 + }, + "suggestedAction": "Add the field to a grant's writableFields, a fixed Action set, a function plan write, or an import permission, or remove the field." + } + ] +} diff --git a/products/breg/examples/minimal/dev.yaml b/products/breg/examples/minimal/dev.yaml index 5d1b35a6cd..be2763a58f 100644 --- a/products/breg/examples/minimal/dev.yaml +++ b/products/breg/examples/minimal/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # holds the run's HTTP requests at the project root. issuer: https://identity.directory.example.test products: - - {product: breg, project: ., audience: "urn:example:local-directory"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:local-directory" people: editor: subject: synthetic-directory-editor diff --git a/products/breg/fixtures/generic-operator-workflows/dev.yaml b/products/breg/fixtures/generic-operator-workflows/dev.yaml index 28ad478abf..1e18f33aca 100644 --- a/products/breg/fixtures/generic-operator-workflows/dev.yaml +++ b/products/breg/fixtures/generic-operator-workflows/dev.yaml @@ -8,7 +8,12 @@ kind: RStackDev # dev-journeys.yaml holds the run's HTTP requests. issuer: https://identity.generic-registry.example.test products: - - {product: breg, project: ., audience: "urn:example:generic-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:generic-registry" people: operator: subject: generic-registry-operator diff --git a/products/breg/fixtures/multi-reference-array-claim/dev.yaml b/products/breg/fixtures/multi-reference-array-claim/dev.yaml index 926b0b4819..b63b264693 100644 --- a/products/breg/fixtures/multi-reference-array-claim/dev.yaml +++ b/products/breg/fixtures/multi-reference-array-claim/dev.yaml @@ -6,7 +6,12 @@ kind: RStackDev # allowed_jurisdictions claim, so each refusal step names its person. issuer: https://identity.permits.example.test products: - - {product: breg, project: ., audience: "urn:example:permit-registry"} + breg: + projects: + breg: + path: . +audiences: + breg: "urn:example:permit-registry" people: reference-loader: subject: synthetic-reference-loader diff --git a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json index 6a59ea013e..670c75ac18 100644 --- a/products/breg/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/breg/generated/mcp-runtime/mcp-runtime.schema.json @@ -222,8 +222,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -625,6 +632,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/generated/review-runtime/review-runtime.schema.json b/products/breg/generated/review-runtime/review-runtime.schema.json index 6c87764833..17e32d145f 100644 --- a/products/breg/generated/review-runtime/review-runtime.schema.json +++ b/products/breg/generated/review-runtime/review-runtime.schema.json @@ -127,8 +127,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -274,6 +281,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index 622232a8bc..d147742477 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -716,8 +716,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -2340,6 +2347,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/breg/generated/tools/ctl-report.v1alpha1.schema.json b/products/breg/generated/tools/ctl-report.v1alpha1.schema.json new file mode 100644 index 0000000000..5642d5ce12 --- /dev/null +++ b/products/breg/generated/tools/ctl-report.v1alpha1.schema.json @@ -0,0 +1,319 @@ +{ + "$defs": { + "CheckScope": { + "additionalProperties": false, + "description": "A source file relative to the project and the resource path a check reports.", + "properties": { + "file": { + "minLength": 1, + "type": "string" + }, + "path": { + "description": "A pointer whose list positions use existing unique identifiers when available.", + "type": "string" + } + }, + "required": [ + "file", + "path" + ], + "type": "object" + }, + "FindingRank": { + "enum": [ + "widens-access", + "performance", + "hygiene" + ], + "type": "string" + }, + "ProfileArg": { + "enum": [ + "authoring", + "production" + ], + "type": "string" + }, + "RankedProjectFinding": { + "additionalProperties": false, + "description": "One problem, in the shape every checking command reports (CFG-DIAG-1).\n\nMessages name keys, paths, accepted values, bounds, and the expected\nenvelope without repeating rejected scalar values (CFG-SEC-3). Warning\nacceptance metadata separately identifies the resource and carries the\nproject's deliberately authored reason.", + "properties": { + "acceptedReason": { + "description": "The project's reason for accepting this advisory warning.", + "type": "string" + }, + "artifact": { + "description": "The document's `kind`, or the expected kind when the document's own is\nabsent or wrong and the reader expected exactly one.", + "type": "string" + }, + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "path": { + "description": "RFC 6901 JSON pointer into the document as written; `\"\"` is the root.", + "type": "string" + }, + "rank": { + "$ref": "#/$defs/FindingRank" + }, + "related": { + "items": { + "$ref": "#/$defs/Related" + }, + "type": "array" + }, + "scope": { + "$ref": "#/$defs/CheckScope", + "description": "Project-relative identity copied into a check acceptance." + }, + "severity": { + "$ref": "#/$defs/Severity" + }, + "source": { + "$ref": "#/$defs/Source" + }, + "suggestedAction": { + "type": "string" + } + }, + "required": [ + "severity", + "code", + "path", + "message", + "suggestedAction", + "rank" + ], + "type": "object" + }, + "Related": { + "additionalProperties": false, + "description": "A second place that explains a diagnostic, such as the first occurrence\nof a duplicate. Human output prints it as a `note:` line.", + "properties": { + "column": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "message": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "file", + "path", + "message" + ], + "type": "object" + }, + "Severity": { + "description": "Whether a diagnostic refuses the input.", + "enum": [ + "error", + "warning" + ], + "type": "string" + }, + "Source": { + "additionalProperties": false, + "description": "Where a diagnostic points. `file` is the path exactly as the caller gave\nit; `line` and `column` are 1-based and absent when the problem concerns\nthe file as a whole.", + "properties": { + "column": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + }, + "file": { + "type": "string" + }, + "line": { + "format": "uint", + "maximum": 1048577, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "file" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The completed report from bregctl generate identity-facts. Validation describes the report structure; its artifact metadata does not establish the path or contents of a file.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/breg/ctl-report/v1alpha1", + "description": "The format and version this file is written in.", + "type": "string" + }, + "artifacts": { + "items": { + "additionalProperties": false, + "properties": { + "byteLength": { + "maximum": 1048576, + "minimum": 1, + "type": "integer" + }, + "mediaType": { + "const": "application/yaml", + "type": "string" + }, + "path": { + "minLength": 1, + "type": "string" + }, + "sha256": { + "maxLength": 64, + "minLength": 64, + "pattern": "^[0-9a-f]{64}$", + "type": "string" + } + }, + "required": [ + "path", + "mediaType", + "byteLength", + "sha256" + ], + "type": "object" + }, + "maxItems": 1, + "minItems": 1, + "type": "array" + }, + "command": { + "const": "generate", + "type": "string" + }, + "diagnostics": { + "items": { + "$ref": "#/$defs/RankedProjectFinding" + }, + "type": "array" + }, + "explanation": { + "additionalProperties": false, + "properties": { + "identityFacts": { + "additionalProperties": false, + "properties": { + "accessProfiles": { + "maximum": 64, + "minimum": 0, + "type": "integer" + }, + "claims": { + "maximum": 64, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "accessProfiles", + "claims" + ], + "type": "object" + } + }, + "required": [ + "identityFacts" + ], + "type": "object" + }, + "kind": { + "const": "BRegCtlReport", + "description": "The kind of document this file is.", + "type": "string" + }, + "nextSteps": { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + "ok": { + "const": true, + "type": "boolean" + }, + "posture": { + "additionalProperties": false, + "properties": { + "source": { + "enum": [ + "default", + "environment", + "flag" + ], + "type": "string" + }, + "value": { + "enum": [ + "production", + "development" + ], + "type": "string" + } + }, + "required": [ + "value", + "source" + ], + "type": "object" + }, + "profile": { + "$ref": "#/$defs/ProfileArg" + }, + "revision": { + "maxLength": 71, + "minLength": 71, + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "status": { + "const": "complete", + "type": "string" + }, + "version": { + "minLength": 1, + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "ok", + "command", + "status", + "version", + "profile", + "revision", + "posture", + "diagnostics", + "artifacts", + "explanation" + ], + "title": "Completed BReg identity facts command report", + "type": "object" +} diff --git a/products/breg/loadtest/support/loadenv.py b/products/breg/loadtest/support/loadenv.py index 8d71e12beb..a304d4ee4a 100755 --- a/products/breg/loadtest/support/loadenv.py +++ b/products/breg/loadtest/support/loadenv.py @@ -32,7 +32,9 @@ kind: RStackDev issuer: https://identity.loadtest.example.test products: - - {product: breg, project: ., audience: "urn:example:business-establishments"} + breg: {projects: {breg: {path: .}}} +audiences: + breg: "urn:example:business-establishments" people: loadtest-driver: subject: synthetic-business-operator diff --git a/products/casework/examples/formats/reports/identity-facts-report.json b/products/casework/examples/formats/reports/identity-facts-report.json new file mode 100644 index 0000000000..cdd4c57374 --- /dev/null +++ b/products/casework/examples/formats/reports/identity-facts-report.json @@ -0,0 +1,18 @@ +{ + "ok": true, + "command": "generate-identity-facts", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/casework/report/v1alpha2", + "kind": "CaseworkReport", + "version": "0.49.0-dev", + "accessProfiles": 4, + "assertionIssuers": 0, + "claims": 1, + "output": "casework.identity-facts.yaml", + "product": "casework", + "posture": { + "value": "production", + "source": "default" + }, + "diagnostics": [] +} diff --git a/products/casework/examples/standalone-decision/dev.yaml b/products/casework/examples/standalone-decision/dev.yaml index 8f0ae3414c..cb5bf471d0 100644 --- a/products/casework/examples/standalone-decision/dev.yaml +++ b/products/casework/examples/standalone-decision/dev.yaml @@ -6,7 +6,10 @@ kind: RStackDev # throwaway local key under this name. issuer: https://identity.standalone.example.test products: - - {product: casework, project: ., audience: "urn:example:standalone-decision"} + casework: + path: . +audiences: + casework: "urn:example:standalone-decision" people: administrator: subject: administrator diff --git a/products/casework/generated/runtime/runtime.schema.json b/products/casework/generated/runtime/runtime.schema.json index 9c5aca82d1..9a872c2c64 100644 --- a/products/casework/generated/runtime/runtime.schema.json +++ b/products/casework/generated/runtime/runtime.schema.json @@ -552,8 +552,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -799,6 +806,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/casework/scripts/test-backup-restore.sh b/products/casework/scripts/test-backup-restore.sh index edc73baf25..1483269933 100755 --- a/products/casework/scripts/test-backup-restore.sh +++ b/products/casework/scripts/test-backup-restore.sh @@ -204,7 +204,7 @@ from pathlib import Path import sys path = Path(sys.argv[1]) text = path.read_text() -for before, after in (("issuer: http://127.0.0.1:8093", f"issuer: {sys.argv[2]}"), +for before, after in (("issuer: https://identity.casework.example.test", f"issuer: {sys.argv[2]}"), ("subject: b75315b2-5854-70f3-8867-511dd771a6da", "subject: requester")): assert text.count(before) == 1, before text = text.replace(before, after) diff --git a/products/coordinator/AGENTS.md b/products/coordinator/AGENTS.md index 8ca991b8c2..548afa576e 100644 --- a/products/coordinator/AGENTS.md +++ b/products/coordinator/AGENTS.md @@ -36,8 +36,8 @@ receives the call, which decides it under its own authorization. that contract. Wake-ups only advance an eligible authoritative read and start no run. Keep the durable observation floor, budget, correlation, and original deadline intact across recovery. -- Keep the canonical authoring separation: contracts, types, named pure Functions, - local exact Operation aliases, and one Workflow graph. Functions take one typed +- Keep the canonical authoring separation: contracts, types, named pure Transforms, + local exact Operation aliases, and one Workflow graph. Transforms take one typed object of named inputs and gain no I/O capability. Runtime uses one tagged connections map. Each exact verified client identity resolves one access profile, which scopes run actions through workflows. Start requires the expected workflowRevision. diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index b0d0a6f445..6a68751c72 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- BREAKING: Name the bounded Rhai computations in a Coordinator workflow Transforms. Rename `functions` to `transforms` and use `type: transform` with a `transform` member in mappings. Use `coordinatorctl explain transforms` for the interpreter helpers and update diagnostic consumers from `coordinator.function.*` to `coordinator.transform.*`. Retained definition snapshots keep their reader and revision format. +- Add `service.invoke-function/v1`, which calls one service function. The workflow names it with `serviceFunction`. A `type: service-function` runtime connection binds the function host, that one function and one credential for the host alone: an OAuth `authorization` or a `hostKeyRef` key. `check` refuses a missing name and a name the connection does not bind. The runtime refuses a function credential whose resource, client or key matches a product, external or task authority credential or the Coordinator's own audience, and compares resolved key material at startup. Calls follow external command recovery and require an `interpret` Transform. + ## 0.49.0 - 2026-12-01 - BREAKING: BReg record operation outputs use `revisionId` and the updated Registry Record metadata names. Migration: update workflow mappings and fixture replies, then recompile against the regenerated operation contracts. diff --git a/products/coordinator/examples/decision-follow-up/README.md b/products/coordinator/examples/decision-follow-up/README.md index 02d0359e5a..fc1f38383e 100644 --- a/products/coordinator/examples/decision-follow-up/README.md +++ b/products/coordinator/examples/decision-follow-up/README.md @@ -77,5 +77,5 @@ cp /tmp/applications-actions/generated/action-contracts.json \ ``` Review a changed contract before packaging a new workflow version. -Functions declare named input schemas and take one object of those inputs; they do not select +Transforms declare named input schemas and take one object of those inputs; they do not select transport credentials or replace the imported Action contract. diff --git a/products/coordinator/examples/decision-follow-up/workflow.yaml b/products/coordinator/examples/decision-follow-up/workflow.yaml index 7a06a1f976..68aa6f1002 100644 --- a/products/coordinator/examples/decision-follow-up/workflow.yaml +++ b/products/coordinator/examples/decision-follow-up/workflow.yaml @@ -23,7 +23,7 @@ contracts: applications: type: breg source: generated/applications.contract.json -functions: +transforms: assessment-request: runtime: rhai source: functions.rhai @@ -75,8 +75,8 @@ workflow: type: call operation: assessor-evaluate-decision input: - type: function - function: assessment-request + type: transform + transform: assessment-request inputs: input: type: input @@ -84,8 +84,8 @@ workflow: route: type: choose choose: - type: function - function: assessment-route + type: transform + transform: assessment-route inputs: reply: type: step @@ -98,8 +98,8 @@ workflow: type: call operation: applications-invoke-breg-action input: - type: function - function: action-request + type: transform + transform: action-request inputs: input: type: input diff --git a/products/coordinator/examples/deferred-appointment/workflow.yaml b/products/coordinator/examples/deferred-appointment/workflow.yaml index 13e5058a63..6e9c0b16fe 100644 --- a/products/coordinator/examples/deferred-appointment/workflow.yaml +++ b/products/coordinator/examples/deferred-appointment/workflow.yaml @@ -40,7 +40,7 @@ types: expiresAt: type: integer minimum: 1 -functions: +transforms: appointment-route: runtime: rhai source: functions.rhai @@ -129,8 +129,8 @@ workflow: eligibility: type: choose choose: - type: function - function: appointment-route + type: transform + transform: appointment-route inputs: record: type: step @@ -173,8 +173,8 @@ workflow: capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: availability: type: step @@ -186,8 +186,8 @@ workflow: type: call operation: bookings-create-appointment input: - type: function - function: booking-request + type: transform + transform: booking-request inputs: input: type: input @@ -202,8 +202,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: input: type: input diff --git a/products/coordinator/examples/delayed-follow-up/dev.yaml b/products/coordinator/examples/delayed-follow-up/dev.yaml index 9ffb968ae2..95e331c5b5 100644 --- a/products/coordinator/examples/delayed-follow-up/dev.yaml +++ b/products/coordinator/examples/delayed-follow-up/dev.yaml @@ -3,7 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: coordinator, project: ., audience: "urn:example:coordinator"} + coordinator: + projects: + coordinator: + path: . +audiences: + coordinator: "urn:example:coordinator" people: reader: subject: starter-reader diff --git a/products/coordinator/examples/delayed-follow-up/workflow.yaml b/products/coordinator/examples/delayed-follow-up/workflow.yaml index d7aaa06e93..163c28a75c 100644 --- a/products/coordinator/examples/delayed-follow-up/workflow.yaml +++ b/products/coordinator/examples/delayed-follow-up/workflow.yaml @@ -18,7 +18,7 @@ types: sendAfter: type: string format: date-time -functions: +transforms: notice-route: runtime: rhai source: functions.rhai @@ -77,8 +77,8 @@ workflow: permission: type: choose choose: - type: function - function: notice-route + type: transform + transform: notice-route inputs: record: type: step @@ -90,8 +90,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: input: type: input diff --git a/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml b/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml index 7feeb74741..417f45d58f 100644 --- a/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml +++ b/products/coordinator/examples/earlier-appointment-alerts/source-registry/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.alerts.example.test products: - - product: breg - project: . - audience: urn:example:earlier-appointment-alert-source + breg: + projects: + breg: + path: . +audiences: + breg: urn:example:earlier-appointment-alert-source people: alert-administrator: subject: alert-administrator diff --git a/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml b/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml index 282c245a2b..9b18615820 100644 --- a/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml +++ b/products/coordinator/examples/earlier-appointment-alerts/workflow.yaml @@ -28,7 +28,7 @@ contracts: notice-templates: type: messaging source: generated/notices.contract.json -functions: +transforms: source-route: runtime: rhai source: functions.rhai @@ -155,8 +155,8 @@ workflow: source-state: type: choose choose: - type: function - function: source-route + type: transform + transform: source-route inputs: {subscription: {type: step, step: read-subscription}} cases: inspect: read-appointment @@ -167,8 +167,8 @@ workflow: type: call operation: scheduling-read-appointment input: - type: function - function: appointment-request + type: transform + transform: appointment-request inputs: input: {type: input} subscription: {type: step, step: read-subscription} @@ -176,8 +176,8 @@ workflow: appointment-state: type: choose choose: - type: function - function: appointment-route + type: transform + transform: appointment-route inputs: subscription: {type: step, step: read-subscription} appointment: {type: step, step: read-appointment} @@ -186,30 +186,30 @@ workflow: type: call operation: scheduling-preview-availability input: - type: function - function: preview-request + type: transform + transform: preview-request inputs: {subscription: {type: step, step: read-subscription}} next: capacity capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: {preview: {type: step, step: preview}} cases: {available: claim-state, unavailable: no-capacity} claim-state: type: choose choose: - type: function - function: claim-route + type: transform + transform: claim-route inputs: {subscription: {type: step, step: read-subscription}} cases: {claim: claim, resume: read-current-subscription} claim: type: call operation: alerts-claim input: - type: function - function: claim-request + type: transform + transform: claim-request inputs: {subscription: {type: step, step: read-subscription}} next: read-current-subscription read-current-subscription: @@ -225,8 +225,8 @@ workflow: type: call operation: scheduling-read-appointment input: - type: function - function: appointment-request + type: transform + transform: appointment-request inputs: input: {type: input} subscription: {type: step, step: read-current-subscription} @@ -234,8 +234,8 @@ workflow: final-state: type: choose choose: - type: function - function: final-route + type: transform + transform: final-route inputs: subscription: {type: step, step: read-current-subscription} appointment: {type: step, step: read-current-appointment} @@ -244,23 +244,23 @@ workflow: type: call operation: scheduling-preview-availability input: - type: function - function: preview-request + type: transform + transform: preview-request inputs: {subscription: {type: step, step: read-current-subscription}} next: final-capacity final-capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: {preview: {type: step, step: final-preview}} cases: {available: authorize-dispatch, unavailable: capacity-changed} authorize-dispatch: type: call operation: alerts-authorize-dispatch input: - type: function - function: authorize-request + type: transform + transform: authorize-request inputs: {subscription: {type: step, step: read-current-subscription}} next: read-dispatching-subscription read-dispatching-subscription: @@ -276,8 +276,8 @@ workflow: type: call operation: scheduling-read-appointment input: - type: function - function: appointment-request + type: transform + transform: appointment-request inputs: input: {type: input} subscription: {type: step, step: read-dispatching-subscription} @@ -285,8 +285,8 @@ workflow: dispatch-state: type: choose choose: - type: function - function: dispatch-route + type: transform + transform: dispatch-route inputs: subscription: {type: step, step: read-dispatching-subscription} appointment: {type: step, step: read-dispatching-appointment} @@ -295,16 +295,16 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: {subscription: {type: step, step: read-dispatching-subscription}} next: record-submission record-submission: type: call operation: alerts-record-submission input: - type: function - function: completion-request + type: transform + transform: completion-request inputs: subscription: {type: step, step: read-dispatching-subscription} message: {type: step, step: notify} diff --git a/products/coordinator/examples/external-directory/workflow.yaml b/products/coordinator/examples/external-directory/workflow.yaml index 62c5800893..91d8c55c8f 100644 --- a/products/coordinator/examples/external-directory/workflow.yaml +++ b/products/coordinator/examples/external-directory/workflow.yaml @@ -17,7 +17,7 @@ types: type: string minLength: 1 maxLength: 128 -functions: +transforms: lookup-request: runtime: rhai source: functions.rhai @@ -54,8 +54,8 @@ workflow: type: call operation: directory-external-get input: - type: function - function: lookup-request + type: transform + transform: lookup-request inputs: input: type: input @@ -63,8 +63,8 @@ workflow: result: type: choose choose: - type: function - function: office-route + type: transform + transform: office-route inputs: reply: type: step diff --git a/products/coordinator/examples/external-job/README.md b/products/coordinator/examples/external-job/README.md index 1e34f05720..f0c768ba36 100644 --- a/products/coordinator/examples/external-job/README.md +++ b/products/coordinator/examples/external-job/README.md @@ -11,11 +11,11 @@ coordinatorctl test --project products/coordinator/examples/external-job ``` The `read-job` Operation alias uses `external.get/v1`, specializes its response schema, and exposes -a named `terminal` completion. Its `bounded-poll` declaration names pure Function `job-observation` +a named `terminal` completion. Its `bounded-poll` declaration names pure Transform `job-observation` and a 30-second interval. The workflow reads once, then waits on `completion: {step: read, name: terminal}` for up to 600 seconds within a 900-second run deadline. -The request Function takes one named-input object and selects only the configured `jobs/status` +The request Transform takes one named-input object and selects only the configured `jobs/status` path and `id` query parameter. The interpreter receives the saved original `command` and latest validated `response`. It checks the job ID, returns `pending` for queued/running, `complete` with a typed job result for succeeded, or a declared `external-job-failed` refusal for failed. diff --git a/products/coordinator/examples/external-job/workflow.yaml b/products/coordinator/examples/external-job/workflow.yaml index a98c40d9ad..eec46cfdbb 100644 --- a/products/coordinator/examples/external-job/workflow.yaml +++ b/products/coordinator/examples/external-job/workflow.yaml @@ -50,7 +50,7 @@ types: state: {type: string, const: refused} code: {type: string, enum: [external-job-failed]} -functions: +transforms: job-request: runtime: rhai source: functions.rhai @@ -88,8 +88,8 @@ workflow: type: call operation: read-job input: - type: function - function: job-request + type: transform + transform: job-request inputs: request: {type: input} next: await-terminal diff --git a/products/coordinator/examples/governed-action-follow-up/README.md b/products/coordinator/examples/governed-action-follow-up/README.md index 6d0b753375..be48b94a67 100644 --- a/products/coordinator/examples/governed-action-follow-up/README.md +++ b/products/coordinator/examples/governed-action-follow-up/README.md @@ -96,5 +96,5 @@ cp /tmp/applications-actions/generated/action-contracts.json \ ``` Review a changed contract before packaging a new workflow version. -Functions declare named input schemas and take one object of those inputs; they do not select +Transforms declare named input schemas and take one object of those inputs; they do not select transport credentials or replace the imported Action contract. diff --git a/products/coordinator/examples/governed-action-follow-up/workflow.yaml b/products/coordinator/examples/governed-action-follow-up/workflow.yaml index 2417e1d8ef..68a5167ab0 100644 --- a/products/coordinator/examples/governed-action-follow-up/workflow.yaml +++ b/products/coordinator/examples/governed-action-follow-up/workflow.yaml @@ -18,7 +18,7 @@ contracts: applications: type: breg source: generated/applications.contract.json -functions: +transforms: information-route: runtime: rhai source: functions.rhai @@ -88,8 +88,8 @@ workflow: needs-information: type: choose choose: - type: function - function: information-route + type: transform + transform: information-route inputs: record: type: step @@ -101,8 +101,8 @@ workflow: type: call operation: applications-invoke-breg-action input: - type: function - function: action-request + type: transform + transform: action-request inputs: input: type: input @@ -115,8 +115,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: record: type: step diff --git a/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml b/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml index abbfcf22a9..87f43a7694 100644 --- a/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml +++ b/products/coordinator/examples/invitation-booking/accept-invitation/workflow.yaml @@ -22,7 +22,7 @@ contracts: invitations: type: breg source: generated/invitations.contract.json -functions: +transforms: invitation-route: runtime: rhai source: functions.rhai @@ -131,8 +131,8 @@ workflow: current-state: type: choose choose: - type: function - function: invitation-route + type: transform + transform: invitation-route inputs: invitation: {type: step, step: read-invitation} cases: @@ -147,8 +147,8 @@ workflow: type: call operation: invitations-claim input: - type: function - function: claim-request + type: transform + transform: claim-request inputs: input: {type: input} next: read-claimed-invitation @@ -170,16 +170,16 @@ workflow: type: call operation: catalogue-read-availability input: - type: function - function: availability-request + type: transform + transform: availability-request inputs: invitation: {type: step, step: read-claimed-invitation} next: capacity capacity: type: choose choose: - type: function - function: capacity-route + type: transform + transform: capacity-route inputs: availability: {type: step, step: availability} cases: @@ -189,8 +189,8 @@ workflow: type: call operation: invitations-record-no-capacity input: - type: function - function: record-no-capacity-request + type: transform + transform: record-no-capacity-request inputs: invitation: {type: step, step: read-claimed-invitation} next: no-capacity @@ -198,8 +198,8 @@ workflow: type: call operation: book-appointment input: - type: function - function: booking-request + type: transform + transform: booking-request inputs: input: {type: input} invitation: {type: step, step: read-claimed-invitation} @@ -210,8 +210,8 @@ workflow: type: call operation: invitations-record-booking-result input: - type: function - function: record-result-request + type: transform + transform: record-result-request inputs: invitation: {type: step, step: read-claimed-invitation} appointment: {type: step, step: book} @@ -220,8 +220,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: invitation: {type: step, step: read-claimed-invitation} appointment: {type: step, step: book} diff --git a/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml b/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml index 9a0a8ebfd0..8fa14404da 100644 --- a/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml +++ b/products/coordinator/examples/invitation-booking/issue-invitation/workflow.yaml @@ -27,7 +27,7 @@ contracts: invitations: type: breg source: generated/invitations.contract.json -functions: +transforms: issue-request: runtime: rhai source: functions.rhai @@ -62,8 +62,8 @@ workflow: type: call operation: invitations-issue input: - type: function - function: issue-request + type: transform + transform: issue-request inputs: input: {type: input} next: read-invitation @@ -80,8 +80,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: invitation: {type: step, step: read-invitation} next: accepted diff --git a/products/coordinator/examples/reservation-review/request-only/workflow.yaml b/products/coordinator/examples/reservation-review/request-only/workflow.yaml index bd31b3aeb1..19bbd4c272 100644 --- a/products/coordinator/examples/reservation-review/request-only/workflow.yaml +++ b/products/coordinator/examples/reservation-review/request-only/workflow.yaml @@ -23,7 +23,7 @@ types: expiresAt: {type: integer, minimum: 1} contracts: reservations: {type: breg, source: generated/reservations.contract.json} -functions: +transforms: review-request: runtime: rhai source: functions.rhai @@ -133,7 +133,7 @@ workflow: submit-review: type: call operation: review-submit - input: {type: function, function: review-request, inputs: {input: {type: input}, reservation: {type: step, step: read-source}}} + input: {type: transform, transform: review-request, inputs: {input: {type: input}, reservation: {type: step, step: read-source}}} next: await-review await-review: type: wait-for @@ -149,12 +149,12 @@ workflow: record-rejected: type: call operation: source-review-rejected - input: {type: function, function: source-rejection-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} + input: {type: transform, transform: source-rejection-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} next: rejected record-approved: type: call operation: source-review-approved - input: {type: function, function: source-decision-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} + input: {type: transform, transform: source-decision-request, inputs: {input: {type: input}, result: {type: step, step: await-review}}} next: await-agreement-fixture await-agreement-fixture: type: wait-until @@ -167,12 +167,12 @@ workflow: record-agreement-failed: type: call operation: source-agreement-failed - input: {type: function, function: agreement-failed-request, inputs: {input: {type: input}}} + input: {type: transform, transform: agreement-failed-request, inputs: {input: {type: input}}} next: agreement-failed record-agreement-completed: type: call operation: source-agreement-completed - input: {type: function, function: agreement-completed-request, inputs: {input: {type: input}}} + input: {type: transform, transform: agreement-completed-request, inputs: {input: {type: input}}} next: read-after-agreement read-after-agreement: type: call @@ -187,17 +187,17 @@ workflow: book: type: call operation: scheduling-book - input: {type: function, function: booking-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, metadata: {type: step, step: metadata}}} + input: {type: transform, transform: booking-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, metadata: {type: step, step: metadata}}} next: record-confirmed record-confirmed: type: call operation: source-record-confirmed - input: {type: function, function: record-confirmation-request, inputs: {input: {type: input}, appointment: {type: step, step: book}}} + input: {type: transform, transform: record-confirmation-request, inputs: {input: {type: input}, appointment: {type: step, step: book}}} next: notify notify: type: call operation: notices-submit - input: {type: function, function: notice-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, appointment: {type: step, step: book}}} + input: {type: transform, transform: notice-request, inputs: {input: {type: input}, reservation: {type: step, step: read-after-agreement}, appointment: {type: step, step: book}}} next: confirmed cancel-review-timeout: type: call @@ -212,12 +212,12 @@ workflow: record-withdrawal-after-timeout: type: call operation: source-withdraw - input: {type: function, function: withdrawal-request, inputs: {input: {type: input}}} + input: {type: transform, transform: withdrawal-request, inputs: {input: {type: input}}} next: review-withdrawn record-withdrawal-after-cancel: type: call operation: source-withdraw - input: {type: function, function: withdrawal-request, inputs: {input: {type: input}}} + input: {type: transform, transform: withdrawal-request, inputs: {input: {type: input}}} next: review-withdrawn confirmed: type: finish diff --git a/products/coordinator/examples/reviewed-notice/workflow.yaml b/products/coordinator/examples/reviewed-notice/workflow.yaml index cba135d3fc..df320a1737 100644 --- a/products/coordinator/examples/reviewed-notice/workflow.yaml +++ b/products/coordinator/examples/reviewed-notice/workflow.yaml @@ -23,7 +23,7 @@ types: applicationDigest: type: string pattern: ^sha256:[0-9a-f]{64}$ -functions: +transforms: review-subject-route: runtime: rhai source: functions.rhai @@ -114,8 +114,8 @@ workflow: verify-review-subject: type: choose choose: - type: function - function: review-subject-route + type: transform + transform: review-subject-route inputs: input: type: input @@ -129,8 +129,8 @@ workflow: type: call operation: review-submit-review-request input: - type: function - function: review-request + type: transform + transform: review-request inputs: input: type: input @@ -176,8 +176,8 @@ workflow: verify-notice: type: choose choose: - type: function - function: notice-route + type: transform + transform: notice-route inputs: input: type: input @@ -192,8 +192,8 @@ workflow: type: call operation: notices-submit-message input: - type: function - function: notice-request + type: transform + transform: notice-request inputs: input: type: input diff --git a/products/coordinator/generated/fixture/fixture.schema.json b/products/coordinator/generated/fixture/fixture.schema.json index 3d92772d5c..511d1dc962 100644 --- a/products/coordinator/generated/fixture/fixture.schema.json +++ b/products/coordinator/generated/fixture/fixture.schema.json @@ -102,7 +102,7 @@ }, { "additionalProperties": false, - "description": "The product returned a package-declared, no-effect business refusal.\nA supported call takes its `onDeclaredRefusal` edge when it has one;\notherwise the run stops as refused. An `external.command/v1` step\ntakes a `response` reply instead, which its interpretation Function\nmay turn into a declared refusal.", + "description": "The product returned a package-declared, no-effect business refusal.\nA supported call takes its `onDeclaredRefusal` edge when it has one;\notherwise the run stops as refused. An `external.command/v1` step\ntakes a `response` reply instead, which its interpretation Transform\nmay turn into a declared refusal.", "properties": { "refusalCode": { "$ref": "#/$defs/DeclaredRefusalCode", @@ -140,7 +140,7 @@ }, { "additionalProperties": false, - "description": "The provider answered an `external.command/v1` call with `value`. The\noperation's pinned interpretation Function turns it into an accepted\nresult, a declared refusal or an uncertain outcome, as it would at run\ntime. The status must be one the worker hands to that Function: a\nredirect, a 429 or a 5xx never reaches it, so a fixture models those\nwith an `uncertain` or `retryable` reply.", + "description": "The provider answered an `external.command/v1` call with `value`. The\noperation's pinned interpretation Transform turns it into an accepted\nresult, a declared refusal or an uncertain outcome, as it would at run\ntime. The status must be one the worker hands to that Transform: a\nredirect, a 429 or a 5xx never reaches it, so a fixture models those\nwith an `uncertain` or `retryable` reply.", "properties": { "type": { "const": "response", @@ -196,7 +196,7 @@ }, { "additionalProperties": false, - "description": "The host repeats the accepted external read and interprets these\nsynthetic typed responses under the completion's named Function.", + "description": "The host repeats the accepted external read and interprets these\nsynthetic typed responses under the completion's named Transform.", "properties": { "responses": { "description": "One to 128 bounded response objects in observation order.", diff --git a/products/coordinator/generated/openapi/coordinator.openapi.json b/products/coordinator/generated/openapi/coordinator.openapi.json index 787e91fdaf..c8bab9ae5f 100644 --- a/products/coordinator/generated/openapi/coordinator.openapi.json +++ b/products/coordinator/generated/openapi/coordinator.openapi.json @@ -491,7 +491,8 @@ "payments.record-receipt/v1", "payments.request-disbursement/v1", "payments.read-disbursement/v1", - "payments.record-provider-confirmation/v1" + "payments.record-provider-confirmation/v1", + "service.invoke-function/v1" ], "type": "string" }, @@ -1768,14 +1769,14 @@ "summary": "Report deployment readiness and run state" } }, - "/v1/events/{workflow}/{trigger}": { + "/v1/events/{workflowId}/{triggerId}": { "post": { "description": "Accept at most 1048576 canonical JSON bytes in a HookEnvelope, then hold the admitted event to the 131072-byte structured value profile. Standard Webhooks signs the webhook ID, Unix timestamp and exact body using the key for the trigger in the URL. The signed timestamp must be within 300 seconds in either direction. The webhook ID must equal the envelope ID, and the envelope must match the configured producer URI and authored event type and data schema. The source URI, event ID and trigger bind admission across retries. Every downstream call uses its own product authorization.", "operationId": "admitEvent", "parameters": [ { "in": "path", - "name": "workflow", + "name": "workflowId", "required": true, "schema": { "maxLength": 64, @@ -1785,7 +1786,7 @@ }, { "in": "path", - "name": "trigger", + "name": "triggerId", "required": true, "schema": { "maxLength": 64, @@ -3824,13 +3825,13 @@ "summary": "Start a run of a served workflow" } }, - "/v1/runs/{run}": { + "/v1/runs/{runId}": { "get": { "operationId": "runStatus", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4038,14 +4039,14 @@ "summary": "Read one run's status" } }, - "/v1/runs/{run}/cancel": { + "/v1/runs/{runId}/cancel": { "post": { "description": "An authorized cancellation of a parked review wait with onCancel records durable intent and takes that authored path. A leased result read settles or expires before cleanup advances. Repeating cancellation preserves cleanup, reported by authoredCancelRequested. Other cancellation stops future calls where possible; it never reverses an accepted product effect.", "operationId": "cancelRun", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4333,13 +4334,13 @@ "summary": "Cancel a run" } }, - "/v1/runs/{run}/check": { + "/v1/runs/{runId}/check": { "post": { "operationId": "checkNow", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4626,13 +4627,13 @@ "summary": "Read a waiting step's product now" } }, - "/v1/runs/{run}/inspect": { + "/v1/runs/{runId}/inspect": { "get": { "operationId": "inspectRun", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -4865,13 +4866,13 @@ "summary": "Inspect a run's steps and recovery options" } }, - "/v1/runs/{run}/reconcile": { + "/v1/runs/{runId}/reconcile": { "post": { "operationId": "reconcileRun", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -5165,13 +5166,13 @@ "summary": "Reconcile an uncertain step against its receipt" } }, - "/v1/runs/{run}/retry-same": { + "/v1/runs/{runId}/retry-same": { "post": { "operationId": "retrySame", "parameters": [ { "in": "path", - "name": "run", + "name": "runId", "required": true, "schema": { "format": "uuid", @@ -5466,13 +5467,13 @@ "summary": "Retry a held step with the same command" } }, - "/v1/workflows/{workflow}": { + "/v1/workflows/{workflowId}": { "get": { "operationId": "workflowContract", "parameters": [ { "in": "path", - "name": "workflow", + "name": "workflowId", "required": true, "schema": { "maxLength": 64, diff --git a/products/coordinator/generated/operations/README.md b/products/coordinator/generated/operations/README.md index 57754e4b99..d958a37aa5 100644 --- a/products/coordinator/generated/operations/README.md +++ b/products/coordinator/generated/operations/README.md @@ -36,6 +36,7 @@ Each catalog operation has an input contract, the type its adapter decodes, and | [`payments.request-disbursement/v1`](#payments.request-disbursement/v1) | 1 | `payments` | mutation | required | none | hold-after-dispatch | read | none | | [`payments.read-disbursement/v1`](#payments.read-disbursement/v1) | 1 | `payments` | read | none | none | read-again | none | none | | [`payments.record-provider-confirmation/v1`](#payments.record-provider-confirmation/v1) | 1 | `payments` | mutation | required | none | same-command | none | none | +| [`service.invoke-function/v1`](#service.invoke-function/v1) | 1 | `service-function` | mutation | required | none | same-command | none | [`onDeclaredRefusal`](service.invoke-function.v1.declared-refusal.schema.json) | ## breg.read-record/v1 @@ -2352,6 +2353,73 @@ Output ([`payments.record-provider-confirmation.v1.output.schema.json`](payments No other members are accepted. +## service.invoke-function/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "service-function", + "identity": { + "effect": "mutation", + "id": "service.invoke-function/v1", + "keyRequirement": "required", + "product": "service-function", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectionMayLowerLimits": true, + "maximumMutationRetries": 0, + "maximumRequestBytes": 65536, + "maximumResponseBytes": 65536, + "redirects": "refused" + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`service.invoke-function.v1.input.schema.json`](service.invoke-function.v1.input.schema.json)): + +Any JSON value. + +Output ([`service.invoke-function.v1.output.schema.json`](service.invoke-function.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `body` | any | yes | +| `status` | integer | yes | + +Other members are tolerated. + +Declared-refusal output ([`service.invoke-function.v1.declared-refusal.schema.json`](service.invoke-function.v1.declared-refusal.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `refusalCode` | string | yes | + +No other members are accepted. + ## Completions A `wait-for` step observes a named completion on an accepted Operation. The host reads the authoritative result under current connection authority, using the saved command and exact correlation. A terminal result continues through `next` as the step output. A step reached by `onTimeout` has no completion output. Authenticated signals only wake an eligible read and never carry the result. Durable read spacing, the observation budget and the original deadline survive retries and restarts. diff --git a/products/coordinator/generated/operations/catalog.json b/products/coordinator/generated/operations/catalog.json index bf1abe8a5a..78079b1767 100644 --- a/products/coordinator/generated/operations/catalog.json +++ b/products/coordinator/generated/operations/catalog.json @@ -2258,7 +2258,7 @@ }, "output": { "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The bounded provider response. The operation's interpret Function receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", + "description": "The bounded provider response. The operation's interpret Transform receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", "properties": { "body": { "description": "The parsed JSON response body, or null for an empty body." @@ -7712,5 +7712,91 @@ "title": "scheduling.reschedule-appointment/v1 output", "type": "object" } + }, + "service.invoke-function/v1": { + "declaredRefusal": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "One package-declared business refusal from a validated product response.\n\nThe code is deliberately absent from `Debug`; callers must opt in to reading\nor serializing it for an authored refusal branch.", + "properties": { + "refusalCode": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + } + }, + "required": [ + "refusalCode" + ], + "title": "service.invoke-function/v1 declared-refusal output", + "type": "object" + }, + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "service-function", + "identity": { + "effect": "mutation", + "id": "service.invoke-function/v1", + "keyRequirement": "required", + "product": "service-function", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectionMayLowerLimits": true, + "maximumMutationRetries": 0, + "maximumRequestBytes": 65536, + "maximumResponseBytes": 65536, + "redirects": "refused" + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": true, + "description": "The request body, sent as the exact JSON object to the one service function the connection binds.", + "title": "service.invoke-function/v1 input", + "type": "object" + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "The bounded function host response. The operation's interpret Transform receives it with the request body and returns the step result, a declared refusal, or an uncertain outcome.", + "properties": { + "body": { + "description": "The parsed JSON response body, or null for an empty body." + }, + "status": { + "maximum": 65535, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "status", + "body" + ], + "title": "service.invoke-function/v1 output", + "type": "object" + } } } diff --git a/products/coordinator/generated/operations/external.command.v1.output.schema.json b/products/coordinator/generated/operations/external.command.v1.output.schema.json index 5ebe3566fd..ac42a0be8b 100644 --- a/products/coordinator/generated/operations/external.command.v1.output.schema.json +++ b/products/coordinator/generated/operations/external.command.v1.output.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The bounded provider response. The operation's interpret Function receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", + "description": "The bounded provider response. The operation's interpret Transform receives it with the command and returns the step result, a declared refusal, or an uncertain outcome.", "properties": { "body": { "description": "The parsed JSON response body, or null for an empty body." diff --git a/products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json b/products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json new file mode 100644 index 0000000000..9db6c263f8 --- /dev/null +++ b/products/coordinator/generated/operations/service.invoke-function.v1.declared-refusal.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "One package-declared business refusal from a validated product response.\n\nThe code is deliberately absent from `Debug`; callers must opt in to reading\nor serializing it for an authored refusal branch.", + "properties": { + "refusalCode": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + } + }, + "required": [ + "refusalCode" + ], + "title": "service.invoke-function/v1 declared-refusal output", + "type": "object" +} diff --git a/products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json b/products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json new file mode 100644 index 0000000000..f430a06dd7 --- /dev/null +++ b/products/coordinator/generated/operations/service.invoke-function.v1.input.schema.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": true, + "description": "The request body, sent as the exact JSON object to the one service function the connection binds.", + "title": "service.invoke-function/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json b/products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json new file mode 100644 index 0000000000..f8f5edb3e6 --- /dev/null +++ b/products/coordinator/generated/operations/service.invoke-function.v1.output.schema.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "The bounded function host response. The operation's interpret Transform receives it with the request body and returns the step result, a declared refusal, or an uncertain outcome.", + "properties": { + "body": { + "description": "The parsed JSON response body, or null for an empty body." + }, + "status": { + "maximum": 65535, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "status", + "body" + ], + "title": "service.invoke-function/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/project/project.schema.json b/products/coordinator/generated/project/project.schema.json index 64304d2df8..ba614a461a 100644 --- a/products/coordinator/generated/project/project.schema.json +++ b/products/coordinator/generated/project/project.schema.json @@ -52,7 +52,7 @@ "properties": { "interpret": { "$ref": "#/$defs/LocalId", - "description": "The typed pure Function that turns the saved command and response into an observation." + "description": "The typed pure Transform that turns the saved command and response into an observation." }, "intervalSeconds": { "description": "Seconds between pending observations; the host may impose a stricter minimum.", @@ -174,68 +174,12 @@ ], "type": "object" }, - "AuthoredFunction": { - "additionalProperties": false, - "properties": { - "description": { - "$ref": "#/$defs/DisplayText", - "description": "An optional explanation for readers; it has no execution or authorization effect." - }, - "entrypoint": { - "description": "One public source function taking exactly one named-input object.", - "type": "string" - }, - "inputs": { - "additionalProperties": { - "$ref": "#/$defs/Schema" - }, - "description": "Named input schemas or references; every declared input is required exactly once.", - "maxProperties": 16, - "propertyNames": { - "$ref": "#/$defs/LocalId" - }, - "type": "object" - }, - "label": { - "$ref": "#/$defs/DisplayText", - "description": "An optional human label; it changes neither stable identity nor behavior revision." - }, - "limits": { - "$ref": "#/$defs/NarrowedLimits", - "description": "Optional narrowing of the bounded pure profile; omitted limits retain the default ceiling." - }, - "output": { - "$ref": "#/$defs/Schema", - "description": "The declared result schema or mapping; Functions and the host enforce it." - }, - "runtime": { - "$ref": "#/$defs/FunctionRuntime", - "description": "The pinned pure runtime; rhai has no clock, network, database or credential capability." - }, - "source": { - "description": "A local reviewed source asset inside the project directory.", - "type": "string" - } - }, - "required": [ - "runtime", - "source", - "entrypoint", - "inputs", - "output" - ], - "type": "object" - }, "AuthoredMapping": { "oneOf": [ { "additionalProperties": false, - "description": "Computes a value with a declared typed pure Function.", + "description": "Computes a value with a declared typed pure Transform.", "properties": { - "function": { - "$ref": "#/$defs/LocalId", - "description": "A declared pure Function called with an object of named inputs." - }, "inputs": { "additionalProperties": { "$ref": "#/$defs/Reference" @@ -247,14 +191,18 @@ }, "type": "object" }, + "transform": { + "$ref": "#/$defs/LocalId", + "description": "A declared pure Transform called with an object of named inputs." + }, "type": { - "const": "function", + "const": "transform", "type": "string" } }, "required": [ "type", - "function", + "transform", "inputs" ], "type": "object" @@ -399,7 +347,7 @@ }, "interpret": { "$ref": "#/$defs/LocalId", - "description": "The typed pure Function that interprets an external command's provider\nresponse into an accepted result, a declared refusal or an uncertain\noutcome. Required on, and accepted only on, `external.command/v1`." + "description": "The typed pure Transform that interprets an external command's provider\nresponse into an accepted result, a declared refusal or an uncertain\noutcome. Required on, and accepted only on, `external.command/v1` and\n`service.invoke-function/v1`." }, "label": { "$ref": "#/$defs/DisplayText", @@ -411,7 +359,11 @@ }, "responseSchema": { "$ref": "#/$defs/Schema", - "description": "An optional typed response specialization for the bounded external GET\nor external command Operation." + "description": "An optional typed response specialization for the bounded external GET\nor external command Operation, or the service function Operation." + }, + "serviceFunction": { + "$ref": "#/$defs/LocalId", + "description": "The one service function `service.invoke-function/v1` calls. Required\non, and accepted only on, that Operation. `check` matches it against\nthe function the runtime connection binds; `rstack dev` also checks it\nagainst `service.yaml`. The runtime connection binds the host and\ncredential, and the workflow supplies neither." }, "template": { "$ref": "#/$defs/TemplateReference", @@ -615,7 +567,7 @@ }, "output": { "$ref": "#/$defs/AuthoredMapping", - "description": "The declared result schema or mapping; Functions and the host enforce it." + "description": "The declared result schema or mapping; Transforms and the host enforce it." }, "type": { "const": "finish", @@ -630,6 +582,58 @@ } ] }, + "AuthoredTransform": { + "additionalProperties": false, + "properties": { + "description": { + "$ref": "#/$defs/DisplayText", + "description": "An optional explanation for readers; it has no execution or authorization effect." + }, + "entrypoint": { + "description": "One public source function taking exactly one named-input object.", + "type": "string" + }, + "inputs": { + "additionalProperties": { + "$ref": "#/$defs/Schema" + }, + "description": "Named input schemas or references; every declared input is required exactly once.", + "maxProperties": 16, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + }, + "label": { + "$ref": "#/$defs/DisplayText", + "description": "An optional human label; it changes neither stable identity nor behavior revision." + }, + "limits": { + "$ref": "#/$defs/NarrowedLimits", + "description": "Optional narrowing of the bounded pure profile; omitted limits retain the default ceiling." + }, + "output": { + "$ref": "#/$defs/Schema", + "description": "The declared result schema or mapping; Transforms and the host enforce it." + }, + "runtime": { + "$ref": "#/$defs/TransformRuntime", + "description": "The pinned pure runtime; rhai has no clock, network, database or credential capability." + }, + "source": { + "description": "A local reviewed source asset inside the project directory.", + "type": "string" + } + }, + "required": [ + "runtime", + "source", + "entrypoint", + "inputs", + "output" + ], + "type": "object" + }, "AuthoredWorkflow": { "additionalProperties": false, "properties": { @@ -761,12 +765,6 @@ }, "type": "object" }, - "FunctionRuntime": { - "enum": [ - "rhai" - ], - "type": "string" - }, "ImportedContract": { "additionalProperties": false, "properties": { @@ -860,7 +858,7 @@ }, { "additionalProperties": false, - "description": "Builds a nested object member by member, never with a Function.", + "description": "Builds a nested object member by member, never with a Transform.", "properties": { "fields": { "$ref": "#/$defs/Fields", @@ -967,7 +965,8 @@ "payments.record-receipt/v1", "payments.request-disbursement/v1", "payments.read-disbursement/v1", - "payments.record-provider-confirmation/v1" + "payments.record-provider-confirmation/v1", + "service.invoke-function/v1" ], "type": "string" }, @@ -1101,6 +1100,12 @@ "version" ], "type": "object" + }, + "TransformRuntime": { + "enum": [ + "rhai" + ], + "type": "string" } }, "$id": "https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json", @@ -1123,18 +1128,6 @@ }, "type": "object" }, - "functions": { - "additionalProperties": { - "$ref": "#/$defs/AuthoredFunction" - }, - "description": "Named typed bounded pure computations over one object of named inputs.", - "maxProperties": 128, - "minProperties": 0, - "propertyNames": { - "$ref": "#/$defs/LocalId" - }, - "type": "object" - }, "kind": { "const": "CoordinatorProject", "description": "The kind of document this is.", @@ -1173,6 +1166,18 @@ "description": "The shared Project identity; its version is a human release label, not the computed Workflow revision.", "unevaluatedProperties": false }, + "transforms": { + "additionalProperties": { + "$ref": "#/$defs/AuthoredTransform" + }, + "description": "Named typed bounded pure computations over one object of named inputs.", + "maxProperties": 128, + "minProperties": 0, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + }, "types": { "additionalProperties": { "$ref": "#/$defs/Schema" diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index df12c4babe..3b96285a14 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -471,6 +471,62 @@ ], "type": "object" }, + { + "additionalProperties": false, + "description": "One service function, bound by the deployment to its function host and to a\ncredential for that host alone. `rstack dev` checks the name against the\nservice's `service.yaml`; an operator recipe binds a name it has checked.\nThe workflow names the function; it never supplies the destination or the\ncredential. The function host serves the function at `functions/`\nunder the base URL.", + "properties": { + "attemptTimeoutMilliseconds": { + "default": 2000, + "format": "uint64", + "maximum": 2000, + "minimum": 1, + "type": "integer" + }, + "authorization": { + "$ref": "#/$defs/AuthorizationConfig", + "description": "An OAuth client credential for the function host. Its client, key and\nresource must differ from every product, external and evaluation\ncredential this runtime file declares. Exactly one of `authorization`\nand `hostKeyRef` is required.", + "not": { + "required": [ + "taskAuthority" + ] + } + }, + "baseUrl": { + "$ref": "#/$defs/Url", + "pattern": "^[^\\s\\\\]+$" + }, + "function": { + "$ref": "#/$defs/LocalId", + "description": "The one function this connection binds." + }, + "hostKeyRef": { + "$ref": "#/$defs/SecretReference", + "description": "A static key only the function host accepts, sent as the bearer token.\n`rstack dev` generates one for each run; an operator recipe supplies\nits own. Exactly one of `authorization` and `hostKeyRef` is required." + }, + "maximumResponseBytes": { + "default": 65536, + "format": "uint64", + "maximum": 65536, + "minimum": 1, + "type": "integer" + }, + "responseSchema": { + "description": "Local JSON Schema for the complete {status, body} response.", + "x-registry-foreign": "json-schema-2020-12" + }, + "type": { + "const": "service-function", + "type": "string" + } + }, + "required": [ + "type", + "baseUrl", + "function", + "responseSchema" + ], + "type": "object" + }, { "additionalProperties": false, "properties": { @@ -779,8 +835,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -1088,6 +1151,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/coordinator/scripts/test-postgres.sh b/products/coordinator/scripts/test-postgres.sh index 85f5595ff3..517301e015 100755 --- a/products/coordinator/scripts/test-postgres.sh +++ b/products/coordinator/scripts/test-postgres.sh @@ -33,7 +33,7 @@ cargo test --locked -p registry-coordinator --features postgres-test --lib \ --test postgres_state --test service_deadline --test recovery_audit --test read_lease_recovery \ --test messaging_integration --test process_restart \ --test deployment_postgres --test refusal_golden --test review_wait_postgres \ - --test external_wait_postgres --test external_command_postgres \ + --test external_wait_postgres --test external_command_postgres --test service_function_postgres \ --test standalone_review_postgres --test compare_worker_postgres \ --test read_in_force_postgres --test breg_proposal_wait_postgres \ --test calendar_trigger_authoring diff --git a/products/coordinator/scripts/test-real-services.py b/products/coordinator/scripts/test-real-services.py index 380b0e0a8a..aab32f6bd1 100644 --- a/products/coordinator/scripts/test-real-services.py +++ b/products/coordinator/scripts/test-real-services.py @@ -698,12 +698,18 @@ def start_dev_issuer(self, breg_project, coordinator_project): "kind": "RStackDev", "issuer": "https://dev-issuer.local.test", "journeyFile": "dev-journeys.yaml", - "products": [ - {"product": "breg", "project": "breg", "audience": self.issuer_resource}, - {"product": "casework", "project": "casework", "audience": self.casework_resource}, - {"product": "messaging", "project": "messaging", "audience": "urn:example:messaging"}, - {"product": "coordinator", "project": "coordinator", "audience": COORDINATOR_RESOURCE}, - ], + "products": { + "breg": {"projects": {"breg": {"path": "breg"}}}, + "casework": {"path": "casework"}, + "messaging": {"path": "messaging"}, + "coordinator": {"projects": {"coordinator": {"path": "coordinator"}}}, + }, + "audiences": { + "breg": self.issuer_resource, + "casework": self.casework_resource, + "messaging": "urn:example:messaging", + "coordinator": COORDINATOR_RESOURCE, + }, "people": { alias: { "subject": principal, "client": alias, "roles": [alias], @@ -1000,7 +1006,8 @@ def fixture_key(client, purpose): private(project / "dev.yaml", { "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": issuer, "externalJwksUri": issuer + "/oauth2/jwks", - "products": [{"product": "breg", "project": ".", "audience": resource}], + "products": {"breg": {"projects": {"breg": {"path": "."}}}}, + "audiences": {"breg": resource}, "people": people, "journeyFile": "dev-journeys.yaml", "externalBreg": external, }) private(project / "dev-journeys.yaml", { diff --git a/products/discovery/examples/starter/dev.yaml b/products/discovery/examples/starter/dev.yaml index 040fb9451a..bcaec3bce0 100644 --- a/products/discovery/examples/starter/dev.yaml +++ b/products/discovery/examples/starter/dev.yaml @@ -3,6 +3,9 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: discovery, project: ., audience: "urn:example:discovery"} + discovery: + path: . +audiences: + discovery: "urn:example:discovery" people: {} journeyFile: dev-journeys.yaml diff --git a/products/discovery/scripts/test_catalog_transport.py b/products/discovery/scripts/test_catalog_transport.py new file mode 100644 index 0000000000..1f120aa96b --- /dev/null +++ b/products/discovery/scripts/test_catalog_transport.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Check Discovery catalog transport using a verified discoveryctl executable. + +Run with --discoveryctl --scratch . +The regression needs IPv4 and IPv6 loopback and performs no external fetches. +""" + +import argparse +import hashlib +import json +import os +import socket +import subprocess +import tempfile +import threading +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +PRODUCT = Path(__file__).resolve().parents[1] +PROFILE = "registry-discovery-v1alpha1" +MEDIA_TYPE = 'application/ld+json;profile="https://registrystack.org/discovery/profile/v1alpha1"' +CATALOG = PRODUCT / "fixtures/descriptions/evidence.jsonld" + + +@contextmanager +def catalog_server(host, url_host, family): + seen = [] + connections = [] + description = CATALOG.read_bytes() + + class CatalogHandler(BaseHTTPRequestHandler): + def do_GET(self): + seen.append((self.path, self.headers.get("Accept"), "Authorization" in self.headers)) + if self.path == "/redirect": + self.send_response_only(302) + self.send_header("Location", "/catalog.jsonld") + self.end_headers() + elif self.path == "/catalog.jsonld": + self.send_response_only(200) + self.send_header("Content-Type", MEDIA_TYPE) + self.send_header("Content-Length", str(len(description))) + self.end_headers() + self.wfile.write(description) + else: + self.send_response_only(404) + self.end_headers() + + class CatalogServer(HTTPServer): + address_family = family + + def get_request(self): + connection, address = super().get_request() + connection.settimeout(3) + connections.append(address) + return connection, address + + with CatalogServer((host, 0), CatalogHandler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"{url_host}:{server.server_port}", seen, connections + finally: + server.shutdown() + thread.join() + + +def project_for(directory, url): + project = directory / "project" + project.mkdir(parents=True) + (project / "origins.yaml").write_text(f"""\ +apiVersion: id.registrystack.org/formats/discovery/origins/v1alpha1 +kind: DiscoveryOrigins +origins: + fixture: + catalogUrl: {json.dumps(url)} + profile: {PROFILE} +""") + (project / "mappings").mkdir() + mapping = PRODUCT / "examples/starter/mappings/adult-status.yaml" + (project / "mappings/adult-status.yaml").write_bytes(mapping.read_bytes()) + return project + + +def run_package(binary, directory, url, posture, *, proxy=None): + project = project_for(directory, url) + output = directory / "package" + env = os.environ.copy() + env.pop("REGISTRY_STACK_POSTURE", None) + if proxy is not None: + for key in ("HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"): + env[key] = proxy + for key in ("NO_PROXY", "no_proxy"): + env.pop(key, None) + result = subprocess.run( + [binary, "package", "--project", project, "--output", output, "--posture", posture], + capture_output=True, text=True, timeout=30, env=env, + ) + return result, output + + +def require_refusal(result, output, diagnostic): + assert result.returncode == 1, (result.returncode, result.stdout, result.stderr) + assert diagnostic in result.stderr, result.stderr + assert not output.exists(), output + + +def loopback_cases(binary, directory, host, url_host, family): + with catalog_server(host, url_host, family) as (authority, seen, connections): + url = f"http://{authority}/catalog.jsonld" + request = ("/catalog.jsonld", MEDIA_TYPE, False) + result, output = run_package( + binary, directory / "development", url, "development", + proxy=f"http://{authority}", + ) + assert result.returncode == 0, (result.stdout, result.stderr) + assert seen == [request], seen + assert len(connections) == 1, connections + index_path = output / "discovery-index.json" + index_bytes = index_path.read_bytes() + index = json.loads(index_bytes) + assert len(index["services"]) == 1, index + assert index["origins"][0]["catalogUrl"] == url, index["origins"] + digest = hashlib.sha256(index_bytes).hexdigest() + checksums = (output / "SHA256SUMS").read_text().splitlines() + assert f"{digest} {index_path.name}" in checksums, checksums + + for scheme in ("http", "https"): + result, output = run_package( + binary, directory / f"production-{scheme}", + f"{scheme}://{authority}/catalog.jsonld", "production", + ) + require_refusal(result, output, "discovery.posture.loopback-catalog-url") + assert seen == [request], seen + assert len(connections) == 1, connections + + result, output = run_package( + binary, directory / "redirect", f"http://{authority}/redirect", "development", + ) + require_refusal(result, output, "an approved Discovery origin could not be fetched safely") + assert seen == [request, ("/redirect", MEDIA_TYPE, False)], seen + assert len(connections) == 2, connections + + +def spelling_cases(binary, directory): + for label, url, expected in ( + ("short-ipv4", "http://127.1:9/catalog.jsonld", "config.invalid-value"), + ("other-ipv4", "http://127.0.0.2:9/catalog.jsonld", + "discovery.origins.catalog-url-not-allowed"), + ("mapped-ipv6", "http://[::ffff:127.0.0.1]:9/catalog.jsonld", + "discovery.origins.catalog-url-not-allowed"), + ): + project = project_for(directory / label, url) + result = subprocess.run( + [binary, "check", "--project", project, "--posture", "development", "--format", "json"], + capture_output=True, text=True, timeout=10, + ) + assert result.returncode == 1, (result.returncode, result.stdout, result.stderr) + diagnostics = json.loads(result.stdout)["diagnostics"] + assert [(item["code"], item["path"]) for item in diagnostics] == [ + (expected, "/origins/fixture/catalogUrl") + ], diagnostics + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--discoveryctl", type=Path, required=True) + parser.add_argument("--scratch", type=Path, required=True) + args = parser.parse_args() + binary = args.discoveryctl.resolve(strict=True) + with tempfile.TemporaryDirectory(prefix="discovery-transport-", dir=args.scratch) as temporary: + directory = Path(temporary).resolve() + loopback_cases(binary, directory / "v4", "127.0.0.1", "127.0.0.1", socket.AF_INET) + loopback_cases(binary, directory / "v6", "::1", "[::1]", socket.AF_INET6) + spelling_cases(binary, directory) + print("Discovery catalog transport passed: two exact loopback fetches and nine refusal cases") + + +if __name__ == "__main__": + main() diff --git a/products/documents/examples/development-starter/dev.yaml b/products/documents/examples/development-starter/dev.yaml index 6abc4b0d3a..5fb52b2156 100644 --- a/products/documents/examples/development-starter/dev.yaml +++ b/products/documents/examples/development-starter/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: documents, project: ., audience: "urn:example:documents"} + documents: + path: . +audiences: + documents: "urn:example:documents" people: reader: subject: starter-reader diff --git a/products/documents/generated/runtime/runtime.schema.json b/products/documents/generated/runtime/runtime.schema.json index 5578a36259..f3a7eeec38 100644 --- a/products/documents/generated/runtime/runtime.schema.json +++ b/products/documents/generated/runtime/runtime.schema.json @@ -305,8 +305,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -631,6 +638,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/evidence/CHANGELOG.md b/products/evidence/CHANGELOG.md index d07ee62f37..4b4e5beaf4 100644 --- a/products/evidence/CHANGELOG.md +++ b/products/evidence/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- Evidence, the OID4VCI delivery service and the OID4VP verifier refuse + `secretProviders.file.mountPolicy`, keeping the Version 1 rule that a key + file is never readable by other users. `evidencectl doctor` reports the same + refusal, and the store-provision document does not accept the member. + ## 0.49.0 - 2026-12-01 - BREAKING: Evidence project, bundle, authority, audit, and client lookup declarations use `lookups` and single references use `lookup`. Migration: From v0.48.0, keep the previous binary, bundle, runtime file, authority store, and the active and numeric sealed files for both the service audit and its activation companion (`evidence.jsonl` and `evidence.activation.jsonl` for an `audit.path` of `evidence.jsonl`). Read authority with the v0.48.0 `evidence authority history --runtime-config OLD_RUNTIME`. Inspect the production audit JSON Lines using the matching release's audit schema and activation contract. Copy the authored project and target without the generated authority state. Set fresh `package.root` and `audit.path` values in the copy before packaging, and preserve or explicitly bind its referenced secrets and source extract. Rename `selectorProfiles` to `lookups` and `selectorProfile` (Python `selector_profile`) to `lookup` where the contract renamed those fields. Migrate the target issuer into `authentication.oidc.issuers`. Run `evidencectl package --target TARGET --output CANDIDATE PROJECT` and install the rebuilt bundle at the new package root. The fresh authority root is derived from the copied target directory. Run `evidence authority activate --runtime-config FILE --document CANDIDATE/compiled-authority.yaml`. Confirm sequence 1 in `evidence authority history --runtime-config FILE`, run `evidence check --runtime-config FILE --require-runtime-dependencies`, and start Evidence with `evidence serve --runtime-config FILE`. Verify a fresh signed assertion, its access and disclosure records in the new service stream, and the activation pair in the new activation companion before resuming traffic. diff --git a/products/evidence/OPERATOR-CONTRACT.md b/products/evidence/OPERATOR-CONTRACT.md index 38c67a745c..ed704378fc 100644 --- a/products/evidence/OPERATOR-CONTRACT.md +++ b/products/evidence/OPERATOR-CONTRACT.md @@ -68,6 +68,29 @@ constraint the authorization server issued the token under. An authorization server that binds tokens to DPoP keys or client certificates must issue Evidence clients unbound tokens. +### Provision a PostgreSQL store for qualification + +Use `evidencectl provision` to prepare a dedicated database and two PostgreSQL +logins for the status ledger or the OID4VCI store. Use +[`store-provision.yaml`](examples/formats/store-provision.yaml) as the operator +file. Set `store` to `status` or `oid4vci` and supply secret references for the +distinct migration and runtime login URLs. The URLs must name the same database +on the same server. Use the `database.caBundleRef` reference when the database +uses a private CA. + +Check the file with `evidencectl check --store-provision-config store-provision.yaml`. +Use `--environment` to fill text expressions from the current environment during +the check. The check leaves database secret references unresolved. Review the plan with +`evidencectl provision --runtime-config store-provision.yaml --print-sql`. +The plan reads the configured database secrets and connects to no PostgreSQL server. +To execute it, replace `--print-sql` with `--admin-url-file `. +You can run the same provision command again to converge the same target. + +Provision grants database `CREATE` to the migration login and `CONNECT` to both +logins. On an existing database, check that the runtime login holds only the +intended privileges. The explicit store migration and its table grants are a +separate step. Neither served runtime selects the PostgreSQL store. + ## Governed bundle and operator runtime The operator supplies one atomic bundle containing the approved YAML, diff --git a/products/evidence/examples/fhir/dev.yaml b/products/evidence/examples/fhir/dev.yaml index 14176b7949..be3e0b4b6b 100644 --- a/products/evidence/examples/fhir/dev.yaml +++ b/products/evidence/examples/fhir/dev.yaml @@ -8,7 +8,12 @@ kind: RStackDev # README shows: `python3 serve-source.py`. issuer: run products: - - {product: evidence, project: ., audience: "urn:example:resource:fhir-record-evidence"} + evidence: + projects: + evidence: + path: . +audiences: + evidence: "urn:example:resource:fhir-record-evidence" people: caller: subject: "urn:registrystack:evidence:local:client:fhir-client" diff --git a/products/evidence/examples/formats/store-provision.yaml b/products/evidence/examples/formats/store-provision.yaml new file mode 100644 index 0000000000..ec883d4f3f --- /dev/null +++ b/products/evidence/examples/formats/store-provision.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 +kind: EvidenceStoreProvisionConfig +store: status +database: + transport: verified-tls + migrationUrlRef: secret:file/migration-url + runtimeUrlRef: secret:file/runtime-url + caBundleRef: secret:file/postgres-ca +secretProviders: + file: + root: /run/evidence-store-secrets diff --git a/products/evidence/examples/standalone/dev.yaml b/products/evidence/examples/standalone/dev.yaml index e54d6d454a..9f31d5b15d 100644 --- a/products/evidence/examples/standalone/dev.yaml +++ b/products/evidence/examples/standalone/dev.yaml @@ -9,7 +9,12 @@ kind: RStackDev # `python3 serve-source.py --port 8081`. issuer: run products: - - {product: evidence, project: ., audience: "urn:example:resource:standalone-evidence"} + evidence: + projects: + evidence: + path: . +audiences: + evidence: "urn:example:resource:standalone-evidence" people: caller: subject: "urn:registrystack:evidence:local:client:example-caller" diff --git a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json index 47d436e6a1..7504007b90 100644 --- a/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json +++ b/products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json @@ -178,21 +178,6 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { - "additionalProperties": false, - "description": "The file secret provider.", - "properties": { - "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", - "pattern": "^/", - "type": "string" - } - }, - "required": [ - "root" - ], - "type": "object" - }, "IdentifierRestriction": { "anyOf": [ { @@ -549,43 +534,6 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, - "SecretProvidersConfig": { - "additionalProperties": false, - "anyOf": [ - { - "properties": { - "file": { - "$ref": "#/$defs/FileSecretProviderConfig" - } - }, - "required": [ - "file" - ] - }, - { - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig" - } - }, - "required": [ - "environment" - ] - } - ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig", - "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." - }, - "file": { - "$ref": "#/$defs/FileSecretProviderConfig", - "description": "Enables `secret:file/name` references, read from files under `root`." - } - }, - "type": "object" - }, "SecretReference": { "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", @@ -638,6 +586,58 @@ }, "type": "object" }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, "TokenClientDocument": { "additionalProperties": false, "description": "The identity this service authenticates to its token issuer with.", @@ -752,8 +752,8 @@ "description": "Request budgets. Absent means the defaults of each member." }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig", - "description": "The secret providers `tokenClient.privateKeyRef` may name." + "$ref": "#/$defs/StrictSecretProvidersConfig", + "description": "The secret providers `tokenClient.privateKeyRef` may name. The file provider takes no\n`mountPolicy`: these keys keep the strict file rule." }, "store": { "$ref": "#/$defs/StoreDocument", diff --git a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json index faaa870574..4d5330d100 100644 --- a/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json +++ b/products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json @@ -305,21 +305,6 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { - "additionalProperties": false, - "description": "The file secret provider.", - "properties": { - "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", - "pattern": "^/", - "type": "string" - } - }, - "required": [ - "root" - ], - "type": "object" - }, "IssuerActorKind": { "$ref": "#/$defs/DeclaredActorKind", "description": "The kind every token from one issuer is treated as." @@ -613,43 +598,6 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, - "SecretProvidersConfig": { - "additionalProperties": false, - "anyOf": [ - { - "properties": { - "file": { - "$ref": "#/$defs/FileSecretProviderConfig" - } - }, - "required": [ - "file" - ] - }, - { - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig" - } - }, - "required": [ - "environment" - ] - } - ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", - "properties": { - "environment": { - "$ref": "#/$defs/EnvironmentSecretProviderConfig", - "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." - }, - "file": { - "$ref": "#/$defs/FileSecretProviderConfig", - "description": "Enables `secret:file/name` references, read from files under `root`." - } - }, - "type": "object" - }, "SecretReference": { "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", @@ -704,6 +652,58 @@ "type": "array", "uniqueItems": true }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, "TokenIssuer": { "additionalProperties": false, "description": "One authorized token issuer entry.", @@ -1079,8 +1079,8 @@ "description": "Request-rate limits." }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig", - "description": "The secret providers the `*Ref` members may name." + "$ref": "#/$defs/StrictSecretProvidersConfig", + "description": "The secret providers the `*Ref` members may name. The file provider takes no\n`mountPolicy`: these keys keep the strict file rule." }, "sessions": { "$ref": "#/$defs/SessionsDocument", diff --git a/products/evidence/loadtest/support/loadenv.py b/products/evidence/loadtest/support/loadenv.py index efc71dd536..bd73ba5778 100755 --- a/products/evidence/loadtest/support/loadenv.py +++ b/products/evidence/loadtest/support/loadenv.py @@ -178,7 +178,9 @@ def dev_plan(clients: int) -> str: "kind: RStackDev", "issuer: run", "products:", - f' - {{product: evidence, project: ., audience: "{DEV_AUDIENCE}"}}', + " evidence: {projects: {evidence: {path: .}}}", + "audiences:", + f' evidence: "{DEV_AUDIENCE}"', "people:", ] for client in client_ids(clients): diff --git a/products/evidence/loadtest/support/test_harness.py b/products/evidence/loadtest/support/test_harness.py index cb31dd5b1b..6a028ae091 100644 --- a/products/evidence/loadtest/support/test_harness.py +++ b/products/evidence/loadtest/support/test_harness.py @@ -308,6 +308,11 @@ def test_local_project_adds_a_bounded_synthetic_source_and_refuses_reuse(self) - dev_plan = (project / "dev.yaml").read_text(encoding="utf-8") self.assertIn("kind: RStackDev", dev_plan) self.assertIn("issuer: run", dev_plan) + self.assertIn( + "products:\n evidence: {projects: {evidence: {path: .}}}\n" + f'audiences:\n evidence: "{loadenv.DEV_AUDIENCE}"\n', + dev_plan, + ) self.assertIn("journeyFile: dev-journeys.yaml", dev_plan) self.assertEqual(dev_plan.count("roles: [standalone-service]"), 3) self.assertEqual((project / "service.yaml").read_bytes(), (canonical / "service.yaml").read_bytes()) diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index 11b9d4ce38..dcfd97f4b7 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -309,6 +309,14 @@ "compatibilityLine": "v1alpha1", "description": "Registry Stack session service runtime configuration JSON Schema." }, + { + "glob": "products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json", + "sourcePath": "crates/registry-session/src/schema.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Checked Registry Session browser route inventory JSON Schema." + }, { "glob": "products/platform/generated/mcp-runtime/*.schema.json", "sourcePath": "crates/registry-mcp/src/schema.rs", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 23eec07fc8..e7ff14123c 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -1847,7 +1847,7 @@ "description": "Starts stay held after a restore until an operator releases the admission hold.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "admission.held", @@ -1866,7 +1866,7 @@ "description": "This instance runs in recovery-only mode and admits no runs. Send starts to the ordinary service.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "admission.recovery-only", @@ -1885,7 +1885,7 @@ "description": "The operation may have completed, but its audited result could not be released. Inspect the run before repeating the operation.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "audit.response-unavailable", @@ -1904,7 +1904,7 @@ "description": "The caller credential or completion signature is missing, invalid, or expired.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "authentication.refused", @@ -1923,7 +1923,7 @@ "description": "The run's original connection settings differ from this service's runtime configuration.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "binding.conflict", @@ -1942,7 +1942,7 @@ "description": "Connection settings that runs in progress use differ from this service's runtime configuration.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "binding.live-conflict", @@ -1961,7 +1961,7 @@ "description": "That step is not waiting.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "check.not-waiting", @@ -1977,10 +1977,10 @@ "compatibilityLine": "v1alpha1", "owner": "coordinator", "title": "Workflow definition refused", - "description": "The workflow's workflow definition, one of its mappings or one of its functions refused the request.", + "description": "The workflow's workflow definition, one of its mappings or one of its Transforms refused the request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "definition.refused", @@ -1999,7 +1999,7 @@ "description": "An apply changed the active packages after this service started. Restart it with the runtime file that apply used.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "deployment.activation-changed", @@ -2018,7 +2018,7 @@ "description": "The deployment's activation, runtime configuration or state key custody check failed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "deployment.refused", @@ -2037,7 +2037,7 @@ "description": "An evaluation may have completed at its provider, so the run is never evaluated again.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "evaluation.uncertain", @@ -2056,7 +2056,7 @@ "description": "The signed event must satisfy the accepted canonical envelope and typed event contract.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "event.invalid", @@ -2075,7 +2075,7 @@ "description": "The signed event exceeds the event value profile: 131072 canonical bytes, 32 levels of nesting, 4096 values, 256 items per array, 256 members per object, and 16384 bytes per string. Have the producer project fewer or smaller fields into the event.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "event.too-large", @@ -2094,7 +2094,7 @@ "description": "Send a fresh signed delivery from the exact configured source to its accepted trigger.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "event.unauthenticated", @@ -2113,7 +2113,7 @@ "description": "Execution is under restore hold until an operator releases it.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "execution.held", @@ -2132,7 +2132,7 @@ "description": "Supply an Idempotency-Key header of 1 to 256 bytes.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "idempotency.key-invalid", @@ -2151,7 +2151,7 @@ "description": "This idempotency key already started a run with different input.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "idempotency.key-reused", @@ -2170,7 +2170,7 @@ "description": "The start input does not satisfy the workflow's declared input schema and value bounds.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "input.invalid", @@ -2189,7 +2189,7 @@ "description": "A mutation may have completed at its provider, so the run never sends it again. Reconcile it when its operation offers a read-only receipt lookup; otherwise inspect or cancel the run.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "mutation.uncertain", @@ -2208,7 +2208,7 @@ "description": "The caller's policy does not allow this operation.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "operation.not-authorized", @@ -2227,7 +2227,7 @@ "description": "The original command's receipt can no longer be recovered. This is not evidence that the command was not sent.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "receipt.expired", @@ -2246,7 +2246,7 @@ "description": "The run's progress changed while it was being reconciled. Inspect it again.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "reconcile.raced", @@ -2265,7 +2265,7 @@ "description": "Reconcile applies only to a held mutation with a prepared command, its original binding and no active lease.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "reconcile.refused", @@ -2284,7 +2284,7 @@ "description": "The held operation has no original-result lookup.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "reconcile.unsupported", @@ -2303,7 +2303,7 @@ "description": "The request body exceeds the accepted size: 65536 bytes for a JSON request, or 1048576 bytes for a signed event delivery.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.body-too-large", @@ -2322,7 +2322,7 @@ "description": "The request could not be read as a Coordinator request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.invalid", @@ -2341,7 +2341,7 @@ "description": "The list limit must be between 1 and 100.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.limit-out-of-range", @@ -2360,7 +2360,7 @@ "description": "The route exists but not for this method.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.method-not-allowed", @@ -2379,7 +2379,7 @@ "description": "The requested route does not exist.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.not-found", @@ -2398,7 +2398,7 @@ "description": "The reason or recovery reference must be a bounded reference without personal data or control characters.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.reason-invalid", @@ -2417,7 +2417,7 @@ "description": "The retention cutoff must be in the past and the limit between 1 and 100.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.retention-invalid", @@ -2436,7 +2436,7 @@ "description": "The request body could not be processed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.unprocessable", @@ -2455,7 +2455,7 @@ "description": "The request body is not JSON.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "request.unsupported-media-type", @@ -2474,7 +2474,7 @@ "description": "This recovery action requires execution to be under restore hold.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.hold-required", @@ -2493,7 +2493,7 @@ "description": "Held work no longer matches its protected definition or prepared command.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.lease-incompatible", @@ -2512,7 +2512,7 @@ "description": "Execution history must be complete and the prior deployment fenced before recovery is reviewed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.review-required", @@ -2531,7 +2531,7 @@ "description": "Held work remains unresolved, so the restore hold cannot be released.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "restore.unresolved", @@ -2550,7 +2550,7 @@ "description": "Retry-same applies only to held work before its original deadline.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "retry.refused", @@ -2569,7 +2569,7 @@ "description": "This service's Coordinator version cannot interpret the run's pinned definition.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "run.definition-incompatible", @@ -2588,7 +2588,7 @@ "description": "No run with this identifier is visible to the caller.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "run.not-visible", @@ -2607,7 +2607,7 @@ "description": "Retention erased this run's payloads, so it can no longer be retried or reconciled.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "run.payload-erased", @@ -2626,7 +2626,7 @@ "description": "Coordinator could not complete the request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "runtime.failure", @@ -2645,7 +2645,7 @@ "description": "A dependency of the Coordinator, such as its database, audit stream or token verifier, is unavailable. Try again after the service recovers.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "service.unavailable", @@ -2664,7 +2664,7 @@ "description": "This deployment does not serve the named workflow.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "workflow.not-served", @@ -2683,7 +2683,7 @@ "description": "The expected workflow revision differs from the active revision or the original admission.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "45d584b668b183e59a2328f935f6caa523b3fef2d2e727e7d1faa98079d9e49f" + "sha256": "597d0f3d8488bd54437563b6149baa8410f6d44e16a7143e37bf990d0fd1f3de" }, "problem": { "code": "workflow.revision-mismatch", @@ -5267,7 +5267,7 @@ }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", - "sha256": "0449f7d543ff800396616fe2464f8feefb4288d1e3efc67caf1d97f8e7e93083", + "sha256": "fd12314109d5ecacf116c9489f928fdb22dc7a5459c79096005b0d887f34d2d2", "mediaType": "application/schema+json" } }, @@ -5447,7 +5447,7 @@ }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", - "sha256": "c50ad7d98f4b14b07c89614872d9fe3963cd68590014e6a995dba4ef0d4229ff", + "sha256": "114aa69242ef4bda35c5ebdf71530fd9551b5b365890ef8a440d1df23db7028e", "mediaType": "application/schema+json" } }, @@ -5533,7 +5533,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/backup-binding.v1alpha1.schema.json", @@ -5541,6 +5541,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "breg", + "title": "Completed BReg identity facts command report", + "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", + "source": { + "path": "crates/registry-bregctl/src/tool_schema.rs", + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" + }, + "artifact": { + "path": "products/breg/generated/tools/ctl-report.v1alpha1.schema.json", + "sha256": "6513298c7020104c036804abd150c61f28d18b7b38113a489b84f67335dc40ef", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/breg/event-record-view/event-record-view.v1alpha1.schema.json", "kind": "schema", @@ -5587,7 +5605,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/example-scenarios.v1alpha1.schema.json", @@ -5605,7 +5623,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/journeys.v1.schema.json", @@ -5645,7 +5663,7 @@ }, "artifact": { "path": "products/breg/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "2e625db395d51c21d1c3c5f02d4373ccc585c5c16ffceb247e3af61b2c3de808", + "sha256": "8b759e11301ca05eadb951aff39dfbb31b05481e68d222b4237c66661edc06f1", "mediaType": "application/schema+json" } }, @@ -5659,7 +5677,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/migration-descriptor.v1alpha1.schema.json", @@ -5695,7 +5713,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1alpha1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/model-selection.v1alpha1.schema.json", @@ -5789,7 +5807,7 @@ }, "artifact": { "path": "products/breg/generated/review-runtime/review-runtime.schema.json", - "sha256": "28f0d22758368cef7718da05186ba475e4051308f3df1ab9452b5bec39b53112", + "sha256": "7009f1c4301a93861873dd849b7abbc1193637a2ac2c84fd9b2fbfcd52378e01", "mediaType": "application/schema+json" } }, @@ -5825,7 +5843,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "6a2681e545da5d44a2d2bc2912797cc481dc39089eafd712acf738c478a5a7b0", + "sha256": "e99a03becdfdf693da8cbdd8e37319a4c1ce2f9c1588ec78c4813005e9f0f0c2", "mediaType": "application/schema+json" } }, @@ -5839,7 +5857,7 @@ "description": "Base Registry Engine tool-file JSON Schemas at version v1.", "source": { "path": "crates/registry-bregctl/src/tool_schema.rs", - "sha256": "7b301a42961b96b2ba696f0c6a412275ed7dc21fb03e18d42e66a57e7c05440a" + "sha256": "d9192db9db98a1242472bbc5002b6998a3dec17dfb05d7fbd2068d1353a52684" }, "artifact": { "path": "products/breg/generated/tools/schema-test-credentials.v1.schema.json", @@ -5933,7 +5951,7 @@ }, "artifact": { "path": "products/casework/generated/runtime/runtime.schema.json", - "sha256": "f24571d637629b2d913ec6efb88944306c84dcd2b00ea8e03848049fd7574201", + "sha256": "d7119a087c77192b099034d1304922118b9be1a9efa2e04adcab533629fa0f1f", "mediaType": "application/schema+json" } }, @@ -5947,11 +5965,11 @@ "description": "Registry Coordinator deterministic fixture authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/scenarios.rs", - "sha256": "a3b78b3da6f9fcec6f5e40416295ae5ad481cdcdfb770c6bb1715e0fd7dfc3c9" + "sha256": "fb76ce54849cf3beff2614c77dc222d541de45c0d1137339eeacc214ab1729b7" }, "artifact": { "path": "products/coordinator/generated/fixture/fixture.schema.json", - "sha256": "1802438e02edad82557153c88818bbe2ffa8e243679f6d0306b811edc1adedb3", + "sha256": "7817d78eff4d92363247ecae6d7b672a4c25f51e46ec3b6507f403e55416830d", "mediaType": "application/schema+json" } }, @@ -5965,11 +5983,11 @@ "description": "Registry Coordinator portable project authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/authoring.rs", - "sha256": "233ac8ce1b8f2a7c52bc39a2b48f55ba9ffc1c00be6dea1821089c9736ed8122" + "sha256": "7861faa7e6967c1780fea4fc224578c9410f58d5ba9038ee38d8fc2e9dc51355" }, "artifact": { "path": "products/coordinator/generated/project/project.schema.json", - "sha256": "69e53bda51ef36c2540769d13af80eaa09f6768b44d8379b79fe0886c7a53555", + "sha256": "de2670ab3661e52afdb9bfb9be0c491ebb60cf9cc2725c15428f225cd10d9b70", "mediaType": "application/schema+json" } }, @@ -5983,11 +6001,11 @@ "description": "Registry Coordinator runtime configuration JSON Schema.", "source": { "path": "crates/registry-coordinator/src/runtime.rs", - "sha256": "c0d0267ec81eac40b0f73dcc331f174d526ae32658a2be1609682f1d136e30cf" + "sha256": "083365a7bbb3eeb12293cd7c665e52d5bef7444d54e4a5eca9e2ea378c5884c3" }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "131466a7fe178d178cd7121eddd15a7bd9229c36a570ad378cd2bff5658c7e7f", + "sha256": "874e8f61db468dc1bcbed3d5ca363f8f4c2cac8eef31a2038a4cb7248610e0d3", "mediaType": "application/schema+json" } }, @@ -6149,7 +6167,7 @@ }, "artifact": { "path": "products/documents/generated/runtime/runtime.schema.json", - "sha256": "fdf6aa6c21a03c67c7cd656c55155f052d904637d14eadab49434dfd6b28cd8f", + "sha256": "493af8d7b9a450903138e999f63142e128807e50cfb7a27f429269b50cc013d2", "mediaType": "application/schema+json" } }, @@ -6307,11 +6325,11 @@ "description": "Evidence OID4VCI delivery runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vci/src/schema.rs", - "sha256": "a68d455ad4aae15031875f71af0047197cac6224aaa5f62f5c4a8cc936527224" + "sha256": "c5961b898a660417c39ce3a0552c53bfc397fe269588a3971f51214264e2ff0d" }, "artifact": { "path": "products/evidence/generated/oid4vci-runtime/oid4vci-runtime.schema.json", - "sha256": "d0b24a5fd3be64a975e6132022e74e95e7258af054466b8b068c78e85e64e870", + "sha256": "9648aced227106dbfddecbc2acf7fc43d538948f4a9c002b72840cf284f33b43", "mediaType": "application/schema+json" } }, @@ -6325,11 +6343,11 @@ "description": "Evidence OpenID4VP verifier runtime configuration JSON Schema.", "source": { "path": "crates/registry-evidence-oid4vp/src/schema.rs", - "sha256": "dce7ef9451a6324883cc24cab52f6107603fd4089976abe56d0952d14f0d2bf2" + "sha256": "b1129ebae14366ae175246d9da6223e957ee19a4ebb57e69706621b982378031" }, "artifact": { "path": "products/evidence/generated/oid4vp-runtime/oid4vp-runtime.schema.json", - "sha256": "a299d83c097229892bc82765782e86b7852bad3fddd4124d33b8b84ec0d66ca0", + "sha256": "bdb0e2b0ab0b4a23b7df12d643da1d7269049076c01986b317639f92b8be78eb", "mediaType": "application/schema+json" } }, @@ -6387,6 +6405,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "evidence", + "title": "Evidence store provisioning config", + "description": "Evidence authoring project marker and question JSON Schema.", + "source": { + "path": "crates/registry-evidence-authoring/src/schema.rs", + "sha256": "62464b27cb80552652f785f820ed3655cc9d48aa65dba30dcaea5696c5e79f70" + }, + "artifact": { + "path": "crates/registry-evidencectl/schemas/authoring/store-provision.schema.json", + "sha256": "961639d976875967842004e6e98a0b3e41a7ebd4612f4f7b55aed602ba2a4fe7", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/evidence/target-authority/target-authority.v1alpha1.schema.json", "kind": "schema", @@ -6545,7 +6581,7 @@ }, "artifact": { "path": "products/messaging/generated/runtime/runtime.schema.json", - "sha256": "a455dc4f8c409aa72b599b905b92270cbc0940d465ce57ad86c302b1c5e2974d", + "sha256": "f950af9d9b58006890d657dfd910722ec268e71b9beabc18eede9ab521d0b85a", "mediaType": "application/schema+json" } }, @@ -6617,7 +6653,7 @@ }, "artifact": { "path": "crates/registry-cli-api/schema/connections.schema.json", - "sha256": "8885a96cae62ec9a421f6327ec7b9d165991b6d7996763d20d018c3d7d249f39", + "sha256": "35c0369ec35cf11b3cab6a861b60eb59cff838e328098497f47f627aaadd22cc", "mediaType": "application/schema+json" } }, @@ -6631,7 +6667,7 @@ "description": "Report of the shared `provision` command that creates a product's PostgreSQL roles, database, schemas and extensions.", "source": { "path": "crates/registry-platform-provision/src/cli.rs", - "sha256": "29625dd439514b1351a0d36cba1102895a13416aa65a5675a10435d71bb4549b" + "sha256": "69249d1cd4b43379aa5f4a7c15bddfe443650f49bdb7477c9f068a5468f4f22f" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", @@ -6689,7 +6725,7 @@ }, "artifact": { "path": "products/platform/generated/mcp-runtime/mcp-runtime.schema.json", - "sha256": "f8e707b47f804f8c8fb44589dda071ab0eab14593185ec9c9376bfc88455f9f7", + "sha256": "ea22c026fe461327a97b37dd2534b78255570b7df9bd75772b31f386a8e883ca", "mediaType": "application/schema+json" } }, @@ -6703,7 +6739,7 @@ "description": "rstack error report JSON Schema.", "source": { "path": "crates/registry-rstack/src/cli.rs", - "sha256": "bcfb6c9aaa0911db294ea36fec384039ff55bc06ad84d9669bc78071a648d6b4" + "sha256": "0d9a9654fefbc7fb5ab8bce66129be190c984bfe31aa1e1ac550e62c96d36ffb" }, "artifact": { "path": "products/platform/schemas/rstack-dev-error.v1.schema.json", @@ -6711,6 +6747,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "Checked Registry Session route inventory", + "description": "Checked Registry Session browser route inventory JSON Schema.", + "source": { + "path": "crates/registry-session/src/schema.rs", + "sha256": "e80a34bb3965ff9d2cea8cdae58dc748db23ecb23c29eb53981f5b2abdc88665" + }, + "artifact": { + "path": "products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json", + "sha256": "b732312a4fb335fd6c1afcd6d146a5f3a402cc65a9a32a5c3be54c9541a6951f", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/platform/session-runtime/session-runtime.v1alpha1.schema.json", "kind": "schema", @@ -6721,11 +6775,11 @@ "description": "Registry Stack session service runtime configuration JSON Schema.", "source": { "path": "crates/registry-session/src/schema.rs", - "sha256": "280ac4ba91fc96ef4421ccc9deac1bab492036b8e48f48c197ff4c2bbf817091" + "sha256": "e80a34bb3965ff9d2cea8cdae58dc748db23ecb23c29eb53981f5b2abdc88665" }, "artifact": { "path": "products/platform/generated/session-runtime/session-runtime.schema.json", - "sha256": "65afffcd321fa818de14a7f568ee36ee8f42ac621d686a0c58bc0bba163ddf8c", + "sha256": "3139024000f51fbd4715b1ed048775e5277a920fe026a23a5cb750ccc5ea1de3", "mediaType": "application/schema+json" } }, @@ -6743,7 +6797,7 @@ }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", - "sha256": "aa6f4dded82d3614a2ce83916b0e916c63b12def7678a9eab9eb8aa67e55a7dd", + "sha256": "cc596239277be2a97b9027e6cd3b4501c8e6e2759a67cd34dad4931c0d2997d0", "mediaType": "application/schema+json" } }, @@ -6815,7 +6869,7 @@ }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "056770ac3ae7f273b82d4593ec2403c3706763e61c432d0615d8e6437c796d46", + "sha256": "f2d3e0cb18bae70a57b1d6e85b03bdbb0ed8712d06e68744747666b10fff806a", "mediaType": "application/schema+json" } }, @@ -6833,7 +6887,7 @@ }, "artifact": { "path": "products/platform/generated/dev/dev.v1alpha1.schema.json", - "sha256": "b22f51c0b03704dfab13513765c70acc631e4a01807703bbfb279dc9120afcde", + "sha256": "a7d8da1e475b8e5ef80e4879a4144bb5b247912ec5315d475d80c3b726953114", "mediaType": "application/schema+json" } }, @@ -6869,7 +6923,7 @@ }, "artifact": { "path": "products/platform/generated/dev/service.v1alpha1.schema.json", - "sha256": "e410d8aec61cc9029f3a22c03e8435476870b6a4c5166b2ae2231f6bd00b4618", + "sha256": "113e37bc3da27cf106f96c8ba1d48ab00c238adf3d0eaec02c1aeb0454afb16b", "mediaType": "application/schema+json" } }, @@ -6941,7 +6995,7 @@ }, "artifact": { "path": "products/scheduling/generated/runtime/runtime.schema.json", - "sha256": "3994ba81be800176372d33491965eb6f756d0426d3262135bf500cce1d6a6949", + "sha256": "cbcef9c994e7f822c5b3385ed621777cbb1dc27467852943d18ecee04f965839", "mediaType": "application/schema+json" } }, diff --git a/products/messaging/examples/starter/dev.yaml b/products/messaging/examples/starter/dev.yaml index 047a3f1059..a3eca02ce6 100644 --- a/products/messaging/examples/starter/dev.yaml +++ b/products/messaging/examples/starter/dev.yaml @@ -8,7 +8,10 @@ kind: RStackDev # carries registry_actor_kind. issuer: https://identity.starter.example.test products: - - {product: messaging, project: ., audience: "urn:example:messaging"} + messaging: + path: . +audiences: + messaging: "urn:example:messaging" people: case-system: subject: case-system diff --git a/products/messaging/generated/runtime/runtime.schema.json b/products/messaging/generated/runtime/runtime.schema.json index 336fdbf157..98672fd462 100644 --- a/products/messaging/generated/runtime/runtime.schema.json +++ b/products/messaging/generated/runtime/runtime.schema.json @@ -288,8 +288,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -956,6 +963,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/AGENTS.md b/products/platform/AGENTS.md index 3f1d2fdbee..ec9675ce6f 100644 --- a/products/platform/AGENTS.md +++ b/products/platform/AGENTS.md @@ -12,7 +12,7 @@ fragments. `registry-session` depends on `registry-platform-*` workspace crates only. No product crate depends on it. It issues no tokens and owns no product authorisation. Keep its check listener private to the gateway and run one replica. `SESSION_FIRST_RELEASE` in `release/scripts/release_roster.py` -holds it out of releases while unset. +adds its binary to numbered releases from v0.51.0. Platform also owns [the configuration conventions](CONFIG-CONVENTIONS.md), the rules every product's configuration formats follow, and the shared reader diff --git a/products/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index c8768fa0a8..f6c8890d9e 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,61 @@ ## Unreleased +- Add `@registrystack/client/holder-function`, a pre-1.0 subpath export of the existing `@registrystack/client` package with no new package name. A trusted host uses `createHolderActionHandler` to invoke one generated BReg Action for a signed-in person, with a declared function that only prepares the input. The function receives one projected value and a signal, never the Request, the bearer or a product client, and runs in the host's process, so the binding minimises arguments for trusted, reviewed code and does not isolate it. +- BREAKING: `dev.yaml` declares its products with the same mapping as `service.yaml`, and `rstack dev` refuses the list form with `rstack.dev.products-list`. Migration: replace each `- {product: KIND, project: PATH, audience: AUDIENCE}` entry with `products.KIND.projects.KIND.path: PATH` for `breg`, `coordinator` and `evidence`, or `products.KIND.path: PATH` for the other products, and move the audience to `audiences.KIND: AUDIENCE`. A directory has one inventory: when its `service.yaml` declares `products`, keep only `audiences` in `dev.yaml`. `service.yaml` also accepts `adapter`, `discovery`, `documents`, `render` and `scheduling` projects. +- The file secret provider accepts `mountPolicy: compose-native`, an explicit + production setting that also admits a root-owned, single-link regular file + with mode exactly `0444`, the Docker Compose secret mount shape, under the + declared root. Startup, `check` (including `registry-mcp check` and + `registry-session check`) and the `provision` tools report + `platform.posture.compose-native-secret-mount`. The default rule still + refuses that shape, and writable files, other owners, extra links and paths + outside the root stay refused in every case. Registry Evidence and both + wallet adapters refuse the setting, and saved CLI connections and task + connection files do not accept it. +- Every runtime reads a static JWKS (`jwksSource.documentRef`, BReg + `trustedJwksRef`) and every CA bundle (`caBundleRef`, Messaging + `tlsTrustProfiles.*.bundleRef`) as a public document, and so do the + `provision` tools for `database.caBundleRef`: group and other may read the + file, with no setting. Owner, link, write and walk checks still apply, and + the document is still parsed before use. A refused public document is + described with public-document wording. +- BREAKING: a public document (a static JWKS or a CA bundle, including + `caBundleRef` read by the `provision` tools) that holds an armored private + key block (PEM, OpenSSH or OpenPGP) is refused, even when the file is + owner-only. Migration: if `caBundleRef` named a combined certificate and + key file, split the key into its own secret file and point + `caBundleRef` at the certificates alone. +- Every provision tool refuses a CA bundle that is not UTF-8 text at its + `caBundleRef` member (`/database/caBundleRef`, or `/store/caBundleRef` for + `adapterctl job-provision`) when it reads the runtime file, so + `--print-sql` no longer prints a plan for a binary bundle. Apply still + parses the PEM and refuses a bundle without a certificate. Every provision + tool now words a secret or public-document refusal with its reason and the + fix the error names. +- The shared runtime blocks document publishes `StrictSecretProvidersConfig` + and `StrictFileSecretProviderConfig`, the secret providers without + `mountPolicy`. The Evidence OID4VCI and OID4VP runtime schemas embed them, + so the published contract does not offer a member those runtimes refuse. +- BREAKING for Rust callers of `registry-platform-config`: `SecretError` gains + `UnsafePublicDocument`, `PrivateKeyInPublicDocument` and + `PublicDocumentNotText`, and `ProvisionInput` gains `explicit_settings`. + Migration: add arms for the three variants to exhaustive matches (`SecretFileCheck::public_message` and + `public_suggested_action` give their text), and fill `explicit_settings` + from `PostureReport::explicit_setting_notices`. +- Numbered releases ship `registry-session` for Linux amd64, Linux arm64 and + macOS arm64. It is a standalone release asset: `rstack` does not install it, + and it has no installer or container image. Upgrade: `rstack update` from + v0.44.0 to v0.50.0 refuses this release, because those `rstack` versions do + not recognise the `registry-session` asset. Run this release's `rstack` + installer as for a first installation, naming the components you use. + Later updates work from this release. +- `rstack dev` can attach to PostgreSQL on an isolated development network + when the administrator URL selects `transport=private-network-plaintext`. + The runner pins the checked numeric address in the generated product URLs. + Verified TLS remains the default. Production and `provision` keep their + existing transport rules. + ## 0.50.0 - 2026-12-01 - BREAKING: Projects with authored development people must replace their grants with roles defined in `service.yaml` and assigned under `people..roles` in `dev.yaml`. See the [Stack migration notes](../../release/notes/v0.50.0.md#service-roles). diff --git a/products/platform/CONFIG-CONVENTIONS.md b/products/platform/CONFIG-CONVENTIONS.md index 58049ac7e0..c2b8f02f4d 100644 --- a/products/platform/CONFIG-CONVENTIONS.md +++ b/products/platform/CONFIG-CONVENTIONS.md @@ -42,7 +42,12 @@ In scope: CFG-SCHEMA-6. A product output that a maintained tool reads is a registered contract: it is a read-back format, registered with its schema and a `reader` entry naming that tool's reading function, whatever command prints it. Explain output a - maintained tool reads belongs here, not under `reader: none`. + maintained tool reads belongs in the read-back category. A saved writer + report may register `passiveReport: true` when a maintained offline check + validates it on read-back and its integers only observe completed work. + Register the `rstack dev check --owner-report` command and a saved writer + example with bounded integers. The corpus runs its baseline and both sides + of the integer boundary sweep with `--deny-warnings`. These cells must pass. A **build artifact** is a read-back format that its own product's build writes and reads again and that no one edits (the compiled package model in BReg's `package.json`). It is registered with `audience: generated` and @@ -580,12 +585,15 @@ value outside them with `config.out-of-range`, naming the bounds. An implicit a maximum below the unsigned format's own ceiling, as the bounded types emit it, does. -An output format registered with `reader: none` may state its writer's native -integer range. The schema must declare both bounds explicitly from the actual -serialized type, rather than rely on `format` alone. An observed count or -sequence does not configure resource use, so it needs no invented operational -cap. This distinction changes no input limit, output closedness, or other -schema requirement. +An output format registered with `reader: none` or a generated JSON report +registered with `passiveReport: true` may state its writer's native integer +range. Declare `minimum` and `maximum` explicitly from the serialized type. +A passive report's registered reader validates those bounds against the owner +schema. Use the marker only for a saved writer report with an offline file +check and no security or restricting members. Its integers record completed +work. The marker leaves the payload contract, reader limits and all other +checks in force. Files that configure work or convey authority follow the +ordinary reader rules. *Enforced by:* the convention lint (every `integer` property declares `minimum` and `maximum`); the conformance corpus boundary sweep (each integer in each format's example whose registered schema states both bounds, set one diff --git a/products/platform/README.md b/products/platform/README.md index 24a8a87744..75f437c85e 100644 --- a/products/platform/README.md +++ b/products/platform/README.md @@ -18,8 +18,8 @@ Platform also owns the [session service](../../crates/registry-session/README.md `registry-session`. It holds a person's tokens on the server and answers an Envoy gateway's per-call check. It uses only platform workspace dependencies, and no product crate depends on it. Sessions live in memory in one replica. -The check listener is private to the gateway. The service stays source-build -only while `SESSION_FIRST_RELEASE` is unset. +The check listener is private to the gateway. Numbered releases ship its +binary from v0.51.0, as `SESSION_FIRST_RELEASE` sets. ## Crates diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index c507fc67da..d97c85b1f9 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -276,6 +276,38 @@ formats: whenOmitted: closed restrictingMembers: [] + - id: platform/session-route-inventory + product: platform + title: Checked Registry Session browser route inventory + files: [] + syntax: json + audience: generated + stability: experimental + current: + apiVersion: id.registrystack.org/formats/platform/session-route-inventory/v1alpha1 + kind: PlatformSessionRouteInventory + checkedBy: + file: crates/registry-session/src/gateway/verify.rs + symbol: ROUTE_INVENTORY_API_VERSION + target: + apiVersion: id.registrystack.org/formats/platform/session-route-inventory/v1alpha1 + kind: PlatformSessionRouteInventory + schema: + path: products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-session --features schema --example session-runtime-schema -- --output products/platform/generated/session-runtime + driftCheck: crates/registry-session/src/schema.rs + reader: none + emittedBy: + file: crates/registry-session/src/gateway/verify.rs + symbol: write_verified_route_inventory + check: none + example: products/platform/examples/session/checked-routes.json + conformance: none + securityMembers: [] + restrictingMembers: [] + # breg - id: breg/project product: breg @@ -818,7 +850,7 @@ formats: set: /people/operator/roles reference: none operand: none - relativePath: none + relativePath: /products/breg/projects/breg/path securityMembers: - pointer: /issuer whenOmitted: refused @@ -844,7 +876,7 @@ formats: whenOmitted: refused - pointer: /application/prepareVersion whenOmitted: refused - - pointer: /products/*/audience + - pointer: /audiences/* whenOmitted: refused - pointer: /people/*/roles whenOmitted: refused @@ -860,6 +892,16 @@ formats: whenOmitted: refused - pointer: /bindings/bregReviewAuthority/runIssuerBinding/initiator whenOmitted: closed + - pointer: /bindings/coordinatorReviewProducer + whenOmitted: closed + - pointer: /bindings/coordinatorReviewProducer/runIssuerBinding + whenOmitted: refused + - pointer: /bindings/coordinatorReviewProducer/runIssuerBinding/producer + whenOmitted: refused + - pointer: /bindings/coordinatorReviewProducer/completionDestination + whenOmitted: refused + - pointer: /bindings/coordinatorBregClient + whenOmitted: closed - pointer: /preview whenOmitted: closed - pointer: /preview/actor @@ -870,7 +912,23 @@ formats: whenOmitted: closed - pointer: /preview/breg/post whenOmitted: closed - restrictingMembers: [/issuer, /application/client, /application/callbackPath, /products/*/audience, /people/*/roles] + - pointer: /externalScheduling + whenOmitted: closed + - pointer: /externalScheduling/taskGrant/assertionClient + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/sourceIssuer + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusUrl + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/tokenEndpoint + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusClient + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusKeyRef + whenOmitted: refused + - pointer: /externalScheduling/taskGrant/statusResource + whenOmitted: refused + restrictingMembers: [/issuer, /application/client, /application/callbackPath, /audiences/*, /people/*/roles, /externalScheduling/taskGrant/assertionClient, /externalScheduling/taskGrant/sourceIssuer, /externalScheduling/taskGrant/statusUrl, /externalScheduling/taskGrant/tokenEndpoint, /externalScheduling/taskGrant/statusClient, /externalScheduling/taskGrant/statusKeyRef, /externalScheduling/taskGrant/statusResource] - id: rstack/journeys product: rstack title: Registry Stack authored development journeys @@ -944,17 +1002,17 @@ formats: function: read_service type: ServiceFile check: rstack service check {file} - example: products/platform/conformance/projects/breg-project-dev/service.yaml + example: products/platform/examples/service-previews/business-registration/service.yaml conformance: requiredText: none optionalText: none integer: none boolean: none idList: none - set: /roles/operator/accessProfiles/breg + set: /roles/registrar/accessProfiles/breg reference: none operand: none - relativePath: /products/breg/projects/records/path + relativePath: /products/breg/projects/businesses/path securityMembers: [] restrictingMembers: [] - id: breg/example-scenarios @@ -1400,10 +1458,11 @@ formats: restrictingMembers: [] - id: breg/ctl-report product: breg - title: bregctl --format json report + title: Completed bregctl generate identity-facts JSON report files: [] syntax: json audience: generated + passiveReport: true stability: unpromised current: apiVersion: id.registrystack.org/formats/breg/ctl-report/v1alpha1 @@ -1414,13 +1473,22 @@ formats: target: apiVersion: id.registrystack.org/formats/breg/ctl-report/v1alpha1 kind: BRegCtlReport - schema: none - reader: none + schema: + path: products/breg/generated/tools/ctl-report.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/breg/ctl-report/ctl-report.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-bregctl --features schema --example tool-schema -- --output products/breg/generated/tools + driftCheck: products/breg/scripts/check-tool-schemas.sh + reader: + crate: registry-rstack-dev + file: crates/registry-rstack-dev/src/owner_report.rs + function: check_file + type: untyped emittedBy: file: crates/registry-bregctl/src/lib.rs symbol: write_ctl_report - check: none - example: products/breg/examples/formats/ctl-report.json + check: rstack dev check --owner-report {file} --owner-report-format breg-identity-facts-report + example: products/breg/examples/formats/identity-facts-report.json conformance: none securityMembers: [] restrictingMembers: [] @@ -1709,6 +1777,7 @@ formats: files: [] syntax: json audience: generated + passiveReport: true stability: unpromised current: apiVersion: id.registrystack.org/formats/casework/report/v1alpha2 @@ -1725,12 +1794,16 @@ formats: origin: generated generator: cargo run -p registry-caseworkctl --features schema --example report-schemas -- --output products/casework/contracts/cli driftCheck: crates/registry-caseworkctl/src/schema.rs - reader: none + reader: + crate: registry-rstack-dev + file: crates/registry-rstack-dev/src/owner_report.rs + function: check_file + type: untyped emittedBy: file: crates/registry-caseworkctl/src/report.rs symbol: write - check: none - example: products/casework/examples/formats/reports/check-report.json + check: rstack dev check --owner-report {file} --owner-report-format casework-report + example: products/casework/examples/formats/reports/identity-facts-report.json conformance: none securityMembers: [] restrictingMembers: [] @@ -2669,6 +2742,48 @@ formats: - pointer: /package/expectedDigest whenOmitted: open restrictingMembers: [] + - id: evidence/store-provision + product: evidence + title: Evidence store provisioning config + files: [store-provision.yaml] + syntax: yaml + audience: operator + stability: unpromised + current: + apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 + kind: EvidenceStoreProvisionConfig + checkedBy: + file: crates/registry-evidencectl/src/store_provision.rs + symbol: API_VERSION + target: + apiVersion: id.registrystack.org/formats/evidence/store-provision/v1alpha1 + kind: EvidenceStoreProvisionConfig + schema: + path: crates/registry-evidencectl/schemas/authoring/store-provision.schema.json + id: https://id.registrystack.org/schemas/evidence/store-provision/store-provision.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-evidencectl --features schema --example authoring-schema -- --output crates/registry-evidencectl/schemas/authoring + driftCheck: products/evidence/scripts/check-authoring-schema.sh + reader: + crate: registry-evidencectl + file: crates/registry-evidencectl/src/store_provision.rs + function: load + type: StoreProvisionDocument + check: evidencectl check --store-provision-config {file} + example: products/evidence/examples/formats/store-provision.yaml + conformance: + requiredText: /store + optionalText: /database/transport + integer: none + boolean: none + securityMembers: + - pointer: /database/migrationUrlRef + whenOmitted: refused + - pointer: /database/runtimeUrlRef + whenOmitted: refused + - pointer: /database/caBundleRef + whenOmitted: open + restrictingMembers: [/store] - id: evidence/codelist product: evidence title: Evidence code list @@ -3933,7 +4048,7 @@ formats: integer: /workflow/deadlineSeconds boolean: none reference: /workflow/start - relativePath: /functions/notice-route/source + relativePath: /transforms/notice-route/source securityMembers: [] restrictingMembers: [] - id: coordinator/runtime diff --git a/products/platform/conformance/projects/breg-project-dev/dev.yaml b/products/platform/conformance/projects/breg-project-dev/dev.yaml index 7d211eb13e..f89ed8a100 100644 --- a/products/platform/conformance/projects/breg-project-dev/dev.yaml +++ b/products/platform/conformance/projects/breg-project-dev/dev.yaml @@ -3,9 +3,12 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://issuer.example.invalid products: - - product: breg - project: registry - audience: urn:example:registry + breg: + projects: + breg: + path: registry +audiences: + breg: urn:example:registry people: operator: subject: operator diff --git a/products/platform/conformance/projects/breg-project-dev/service.yaml b/products/platform/conformance/projects/breg-project-dev/service.yaml index e3900321ec..b4128d1937 100644 --- a/products/platform/conformance/projects/breg-project-dev/service.yaml +++ b/products/platform/conformance/projects/breg-project-dev/service.yaml @@ -6,8 +6,3 @@ roles: actorKind: service accessProfiles: breg: [operator] -products: - breg: - projects: - records: - path: registry diff --git a/products/platform/conformance/yaml/formats.yaml b/products/platform/conformance/yaml/formats.yaml index 0ea961ba7e..d125edaaa3 100644 --- a/products/platform/conformance/yaml/formats.yaml +++ b/products/platform/conformance/yaml/formats.yaml @@ -135,7 +135,7 @@ formats: # Isolate the path role: other functions keep their shared source file # when the corpus moves or symlinks this one outside the project. set: - /functions/notice-route/source: notice-route.rhai + /transforms/notice-route/source: notice-route.rhai write: notice-route.rhai: | fn notice_route(args) { diff --git a/products/platform/examples/licensing/dev.yaml b/products/platform/examples/licensing/dev.yaml index 3047928c3b..8f945d86fc 100644 --- a/products/platform/examples/licensing/dev.yaml +++ b/products/platform/examples/licensing/dev.yaml @@ -3,8 +3,15 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.licensing.example.test products: - - {product: breg, project: registry, audience: "urn:example:licensing:registry"} - - {product: casework, project: casework, audience: "urn:example:licensing:review"} + breg: + projects: + breg: + path: registry + casework: + path: casework +audiences: + breg: "urn:example:licensing:registry" + casework: "urn:example:licensing:review" people: applicant: subject: applicant diff --git a/products/platform/examples/service-previews/README.md b/products/platform/examples/service-previews/README.md index 76c8f02840..03fb2d3ba9 100644 --- a/products/platform/examples/service-previews/README.md +++ b/products/platform/examples/service-previews/README.md @@ -1,9 +1,12 @@ # Local service previews -These two synthetic services run independently. Each uses a real BReg and a -managed development PostgreSQL database. +These three synthetic services run independently. Each uses a real BReg and a +managed development PostgreSQL database. The permit-review service also runs +a real Casework and Coordinator. Install `rstack`, `breg`, and `bregctl` from the same Registry Stack release. +The permit-review service also needs `casework`, `caseworkctl`, `coordinator` +and `coordinatorctl` from that release. Use Node 24 and a local Docker engine. Each starter has an exact npm lock. Place the matching release's `@registrystack/client` tarball beside that starter's lockfile as `registry-preview-client.tgz`, then install: @@ -11,19 +14,21 @@ starter's lockfile as `registry-preview-client.tgz`, then install: ```sh npm ci --prefix ./medical-renewal npm ci --prefix ./business-registration +npm ci --prefix ./permit-review ``` The lock matches the tarball by version and SHA-512. The client package supplies -the preview helper and build tools for both examples. +the preview helper and build tools for every example. -From a directory containing clean copies of the examples, start either preview. +From a directory containing clean copies of the examples, start any preview. ```sh rstack dev start ./medical-renewal rstack dev start ./business-registration +rstack dev start ./permit-review ``` -Open the URL each command prints. Use its run ID to check or stop the preview. +Open the URL each command prints. The permit-review start prints one `Actor` URL per synthetic person. Use its run ID to check or stop the preview. ```sh rstack dev status RUN_ID @@ -33,11 +38,13 @@ rstack dev stop RUN_ID --clean A clean stop removes the run's managed data. After editing a function or page, start the example again to build from the updated source. -Both services declare `ui.project: web` and `ui.output: dist`. Preview start +Every service declares `ui.project: web` and `ui.output: dist`. Preview start bundles `web/src/page.ts` into `app.js` and copies `web/public` into the run's owned output. It generates `generated/service.ts`, `generated/routes.ts` and the server binding inside the run's copy. The page imports the generated browser client and same-origin function paths. The gateway authorizes browser-origin requests for one synthetic actor. +The permit-review service runs one gateway per actor, each on its own origin over +the same built page, as a development substitution for one origin with sign-in. It keeps that actor's credential on the server. Use a trusted workstation or an isolated runner, trusted project code, and synthetic data. The numeric loopback listeners are local to the host and reachable by @@ -62,7 +69,25 @@ absolute examples directory. Set `RSTACK_PREVIEW_INSTALL_ROOT` and `RSTACK_PREVIEW_BIN_DIR` to the managed candidate installation's absolute roots. The driver uses those roots and checks that `npm ci` preserves the delivered files. Both modes check the browser reads and mutations and managed -database cleanup. +database cleanup. For permit-review, the driver opens the applicant and officer +origins in two browser contexts and checks that every actor origin serves the +same page bytes. It also checks that: + +- Casework refuses the applicant's decision with 403. +- the Coordinator refuses a completion Casework did not sign with 401. +- the neighbour's origin cannot read the applicant's run. +- the officer's approval finishes the run with the decision recorded in BReg. +- a start the browser rewrites to name the neighbour's application reviews and + decides only that stored application. It leaves the applicant's own + application submitted. + +The driver takes the Casework and Coordinator binaries from `RSTACK_CASEWORK_BIN`, +`RSTACK_CASEWORKCTL_BIN`, `RSTACK_COORDINATOR_BIN` and `RSTACK_COORDINATORCTL_BIN`, +or from the managed installation. A managed candidate whose release ships no +Coordinator sets `RSTACK_PREVIEW_SKIP_PERMIT_REVIEW=no-coordinator-in-release`. +The driver then reports permit-review as skipped. Any other run fails when +those components are missing. - [Renew a medical licence](medical-renewal/README.md) - [Register a business](business-registration/README.md) +- [Apply for a reviewed permit](permit-review/README.md) diff --git a/products/platform/examples/service-previews/business-registration/README.md b/products/platform/examples/service-previews/business-registration/README.md index 2357392424..b57d9a5d99 100644 --- a/products/platform/examples/service-previews/business-registration/README.md +++ b/products/platform/examples/service-previews/business-registration/README.md @@ -5,6 +5,12 @@ printed URL, enter a synthetic business name and registration number such as `BR-BROWSER-2026-001` and select **Register business**. The confirmation reads the new business Record from BReg. +The form check and registration fit in one request. A service function +prepares the input and asks BReg to run the registration Action under the +registrar's authority. The function holds no authority of its own. If your +registration procedure must wait for an officer's decision or has steps that +someone needs to review, put those steps in a Coordinator flow. + - [service.yaml](service.yaml) names the register, frontend and function. - [The BReg project](project/registry.yaml) defines the Record, unique registration number, Action and registrar access profile. @@ -12,7 +18,7 @@ the new business Record from BReg. the same Action. - [dev.yaml](dev.yaml) selects the synthetic registrar and permits business reads and the registration function. -- [The registration function](functions/register-business/index.ts) receives - a typed BReg client for the request and invokes the Action as the registrar. +- [The registration service function](functions/register-business/index.ts) + receives a typed BReg client for the request. - [The page code](web/src/page.ts) calls the function and reads the created Record with the generated client. diff --git a/products/platform/examples/service-previews/business-registration/web/public/index.html b/products/platform/examples/service-previews/business-registration/web/public/index.html index 3a3eebfb2f..17b146d9b8 100644 --- a/products/platform/examples/service-previews/business-registration/web/public/index.html +++ b/products/platform/examples/service-previews/business-registration/web/public/index.html @@ -4,8 +4,8 @@ Register a business - - + + diff --git a/products/platform/examples/service-previews/medical-renewal/README.md b/products/platform/examples/service-previews/medical-renewal/README.md index 8cef0bc573..61531f06ad 100644 --- a/products/platform/examples/service-previews/medical-renewal/README.md +++ b/products/platform/examples/service-previews/medical-renewal/README.md @@ -5,14 +5,21 @@ printed URL, review the synthetic holder's medical licence and select **Renew licence**. The confirmation reads the updated expiry of 30 June 2028 from BReg. +The holder reviews the licence before submitting the form. A service function +then prepares the renewal and asks BReg to run the Action under the holder's +authority. The renewal fits in one request. If your renewal procedure must +wait for someone else to decide or has steps that someone needs to review, +put those steps in a Coordinator flow. + - [service.yaml](service.yaml) names the register, frontend and function. - [The BReg project](project/registry.yaml) defines the records, Action and access profiles. [The startup journey](dev-journeys.yaml) issues the licence through BReg before the browser opens. - [dev.yaml](dev.yaml) selects the synthetic holder and permits licence reads, the Action's target-conditions check and the renewal function. -- [The renewal function](functions/renew/index.ts) receives a typed BReg client - for the request. Its [handler](functions/renew/renew.ts) checks the request - and carries the reviewed revision and the same attempt key through a retry. +- [The renewal service function](functions/renew/index.ts) receives a typed BReg + client for the request. Its [handler](functions/renew/renew.ts) checks the + request and carries the reviewed revision and the same attempt key through a + retry. - [The page code](web/src/page.ts) presents the review and confirmation and keeps the attempt key for a retry. diff --git a/products/platform/examples/service-previews/permit-review/README.md b/products/platform/examples/service-previews/permit-review/README.md new file mode 100644 index 0000000000..05c54e72a3 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/README.md @@ -0,0 +1,81 @@ +# Apply for a reviewed permit + +This preview runs one permit application through four products. The applicant +submits it to BReg and starts a Coordinator run that names only the +application. The Coordinator reads the application under its own BReg +profile, asks Casework to review the content it read, and waits. An officer +reads that content in Casework, claims the task and approves it. The run then +asks the `assess-permit` service function for an assessment and records the +decision in BReg. + +Start it using the [preview instructions](../README.md). It also needs +`casework`, `caseworkctl`, `coordinator` and `coordinatorctl` from the same +release. `rstack dev start` prints one URL per actor. Every URL serves the same +built page, and each origin acts for one synthetic person: + +- the applicant's origin submits an application, starts the run and follows it. +- the officer's origin lists the queue with the content under review, claims a + task, approves it, and reads an application from the register. +- the neighbour's origin is a second applicant, whose application the startup + journey submits. It cannot follow the applicant's run. + +From the applicant's origin, enter a task ID in **Decide a review task**. +Casework refuses that decision with 403, because the applicant's Casework +profile may ask for a review but never decide one. + +Serving each actor from its own origin is a development substitution for a +real sign-in. A deployment serves one origin and signs each person in. + +## What the applicant controls + +The applicant chooses which application a run names, and nothing else. The +Coordinator reads that application itself. The review subject, the content the +officer sees, the assessment input and the decision all come from that read. +A run that names another applicant's application reviews and decides that +application as stored, never content the applicant supplied. A deployment's +starting service also checks that the applicant owns the application it names +before it starts the run. This preview leaves that check out. + +The decision Actions take the activity and site the Coordinator read and guard +them, with the submitted status, in the same write. A BReg target-condition +token would pin the exact revision, but the token is opaque and only BReg can +issue it, so the Coordinator cannot derive one from its read. The content guard +binds the decision to the reviewed content instead: no profile can change an +application's activity or site, and a decided application is no longer +submitted. + +Casework requires a sha256 digest of the review subject, and Coordinator +Transforms cannot hash. The `digest-application` service function hashes the +content the Coordinator read, and the Coordinator calls it before it asks for +the review. + +## Files + +- [service.yaml](service.yaml) names the products, the page, the two functions + and each role's access profiles. +- [The BReg project](project/registry.yaml) defines the application Record, + the applicant's submission Action and the two decision Actions that only the + Coordinator's profile may invoke. The applicant reads no application. Its + [native journeys](project/tests/journeys.yaml) show a decision refused for + other content and refused once decided. +- [The Casework project](casework/casework.yaml) defines the review policy, + the officers' queue and the Coordinator as its one trusted producer. Casework + requires a profile that acts as supervisor, so `permit-supervisor` exists + although no person in this preview holds it. +- [The Coordinator project](coordinator/workflow.yaml) reads the application, + digests it, asks for the review, waits for its result, assesses the approved + content and records the decision. Its [fixtures](coordinator/fixtures) cover + the approved and refused paths and an application already decided. +- [The assessment function](functions/assess-permit/index.ts) and [the digest + function](functions/digest-application/index.ts) hold no registry + credential. Each answers only from the content the Coordinator sends. +- [dev.yaml](dev.yaml) declares the synthetic people, binds the Coordinator's + Casework and BReg connections to run-local machine identities and lists each + actor's preview routes. +- [The startup journeys](dev-journeys.yaml) staff the officers' queue and submit + the neighbour's application. +- [The page code](web/src/page.ts) asks its origin which actor it serves and + shows that actor's controls. + +A waiting run does not survive a restart of `rstack dev`, because the restarted +Casework has a new origin. Stop the preview with `--clean` and start again. diff --git a/products/platform/examples/service-previews/permit-review/casework/casework.yaml b/products/platform/examples/service-previews/permit-review/casework/casework.yaml new file mode 100644 index 0000000000..7440ab9026 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/casework/casework.yaml @@ -0,0 +1,78 @@ +# Casework owns the permit review: who may decide, the queue officers work, +# and the one producer it trusts to ask for a review. The Coordinator is that +# producer. Its issuer below is the logical name `rstack dev` rebinds to the +# run issuer under the exact guards in dev.yaml. +apiVersion: id.registrystack.org/formats/casework/project/v1alpha1 +kind: CaseworkProject +project: + id: permit-review + version: "1" +accessProfiles: + permit-officer: + principalClaim: sub + requiredScopes: [casework:permit:decide] + actsAs: staff + permit-supervisor: + principalClaim: sub + requiredScopes: [casework:permit:supervise] + actsAs: supervisor + permit-administrator: + principalClaim: sub + requiredScopes: [casework:permit:admin] + actsAs: administrator + # The applicant may ask for a review but never decide one. The preview keeps + # this profile so the applicant's decision attempt reaches Casework and is + # refused there with 403. + permit-applicant: + principalClaim: sub + requiredScopes: [casework:permit:apply] + actsAs: requester + coordinator-producer: + principalClaim: sub + requiredScopes: [casework:permit:review] + actsAs: requester +queues: + permit-officers: + label: Permit applications awaiting review +reviewPolicies: + permit-review: + version: "1" + purpose: approval + context: {mode: submitted} + stages: + - id: decide + queue: permit-officers + decidingProfiles: [permit-officer] + requiredApprovals: 1 + retention: + terminalRetentionDays: 90 + accountabilityRetentionDays: 365 + displaySchema: + type: object + additionalProperties: false + required: [activity, site] + properties: + activity: {type: string, maxLength: 160} + site: {type: string, maxLength: 160} + outcomes: + approved: + label: Approve the permit + settlement: approved + reasonRequired: false + publicReason: optional + rejected: + label: Refuse the permit + settlement: rejected + reasonRequired: true + publicReason: required +trustedProducers: + coordinator: + profile: coordinator-producer + issuer: https://identity.permit-review.example.test + subject: coordinator-producer + sourceNamespaces: [permits] + reviewPolicies: [permit-review] + retention: {receiptRetentionDays: 30} + completion: + destinationId: coordinator-wake + recipientBinding: coordinator-v1 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/README.md b/products/platform/examples/service-previews/permit-review/coordinator/README.md new file mode 100644 index 0000000000..31870da2d3 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/README.md @@ -0,0 +1,23 @@ +# Permit review workflow + +The Coordinator project for the [permit review preview](../README.md). + +`generated/permits.contract.json` is the BReg-generated Action export for +[the permit register](../project/registry.yaml). From the repository root, +regenerate it into a new directory and copy the export over the committed file: + +```sh +bregctl generate actions products/platform/examples/service-previews/permit-review/project --output /tmp/permits-actions +cp /tmp/permits-actions/generated/action-contracts.json \ + products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json +``` + +The runtime template names HTTPS reference endpoints and secret references. +Under `rstack dev`, the bindings in `dev.yaml` replace the review and permits +connections, and the preview function host replaces the digester's and the +assessor's. + +The run input is only the application ID. Every later step uses the +Coordinator's own read of the application, and the decision Actions guard the +read content, as [the preview README](../README.md#what-the-applicant-controls) +explains. diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml new file mode 100644 index 0000000000..af66282339 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/already-decided-is-not-reviewed.yaml @@ -0,0 +1,28 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: already-decided-is-not-reviewed +admittedAt: '2026-12-01T09:00:00Z' +input: + applicationId: 00000000-0000-4000-8000-000000000001 +replies: + read-application: + - type: success + value: + '@context': https://id.registrystack.org/contexts/registry-record/v1 + data: + recordId: 00000000-0000-4000-8000-000000000001 + revisionId: '1' + domainData: + activity: Night resurfacing + site: North road + office: central + status: approved + meta: + registryId: permit-register + datasetId: applications + recordTypeId: permit-application +expect: + path: [read-application, check-submitted, not-submitted] + state: completed + outcome: {type: named, value: not-submitted} diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml new file mode 100644 index 0000000000..deb180b442 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/approved-assessed-and-recorded.yaml @@ -0,0 +1,89 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: approved-assessed-and-recorded +admittedAt: '2026-12-01T09:00:00Z' +input: + applicationId: 00000000-0000-4000-8000-000000000001 +replies: + read-application: + - type: success + value: + '@context': https://id.registrystack.org/contexts/registry-record/v1 + data: + recordId: 00000000-0000-4000-8000-000000000001 + revisionId: '1' + domainData: + activity: Night resurfacing + site: North road + office: central + status: submitted + meta: + registryId: permit-register + datasetId: applications + recordTypeId: permit-application + digest: + - type: response + value: + status: 200 + body: + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + request-review: + - type: success + value: + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + assess: + - type: response + value: + status: 200 + body: + assessment: conditions + approve: + - type: success + value: + action: approve-application + applicationId: 00000000-0000-4000-8000-000000000002 + results: + decided-application: + recordType: permit-application + recordId: 00000000-0000-4000-8000-000000000001 + revision: 2 +waits: + await-review: + type: event + value: + resultId: 00000000-0000-4000-8000-000000000011 + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + status: approved + outcome: approved + completedAt: '2026-12-02T09:00:00Z' + availableUntil: '2027-01-02T09:00:00Z' +expect: + path: [read-application, check-submitted, digest, request-review, await-review, decide, assess, approve, approved] + state: completed + outcome: {type: named, value: approved} + output: + assessment: conditions + resultId: 00000000-0000-4000-8000-000000000011 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml new file mode 100644 index 0000000000..a98c48b465 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/fixtures/rejected-recorded-without-assessment.yaml @@ -0,0 +1,82 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/fixture/fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/fixture/v1alpha1 +kind: CoordinatorFixture +id: rejected-recorded-without-assessment +admittedAt: '2026-12-01T09:00:00Z' +input: + applicationId: 00000000-0000-4000-8000-000000000001 +replies: + read-application: + - type: success + value: + '@context': https://id.registrystack.org/contexts/registry-record/v1 + data: + recordId: 00000000-0000-4000-8000-000000000001 + revisionId: '1' + domainData: + activity: Night resurfacing + site: North road + office: central + status: submitted + meta: + registryId: permit-register + datasetId: applications + recordTypeId: permit-application + digest: + - type: response + value: + status: 200 + body: + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + request-review: + - type: success + value: + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + refuse: + - type: success + value: + action: refuse-application + applicationId: 00000000-0000-4000-8000-000000000002 + results: + decided-application: + recordType: permit-application + recordId: 00000000-0000-4000-8000-000000000001 + revision: 2 +waits: + await-review: + type: event + value: + resultId: 00000000-0000-4000-8000-000000000011 + requestId: 00000000-0000-4000-8000-000000000010 + subject: + source: permits + type: permit-application + id: 00000000-0000-4000-8000-000000000001 + version: '1' + digest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + policy: + id: permit-review + version: '1' + digest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + submissionDigest: sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc + status: rejected + outcome: rejected + completedAt: '2026-12-02T09:00:00Z' + availableUntil: '2027-01-02T09:00:00Z' +expect: + path: [read-application, check-submitted, digest, request-review, await-review, decide, refuse, refused] + state: completed + outcome: {type: named, value: refused} + output: + resultId: 00000000-0000-4000-8000-000000000011 diff --git a/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai b/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai new file mode 100644 index 0000000000..6c5ead56bd --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/functions.rhai @@ -0,0 +1,59 @@ +// Pure Function ABI: one typed object of named inputs, one typed output. +// Every value below comes from the Coordinator's own read of the +// application, never from the starter's input. + +fn submitted_route(args) { + if args.record.data.domainData.status == "submitted" { "submitted" } else { "not-submitted" } +} + +fn digest_request(args) { + let data = args.record.data; + #{ + applicationId: data.recordId, + revisionId: data.revisionId, + activity: data.domainData.activity, + site: data.domainData.site + } +} + +// Only a well-formed digest settles the call. Anything else is uncertain, +// so the run holds for same-command recovery instead of guessing. +fn digest_outcome(args) { + let response = args.response; + if response.status == 200 && "digest" in response.body { + return #{state: "accepted", result: #{digest: response.body.digest}}; + } + #{state: "uncertain"} +} + +fn review_request(args) { + let data = args.record.data; + #{ + policy: #{id: "permit-review"}, + subject: #{ + source: "permits", + type: "permit-application", + id: data.recordId, + version: data.revisionId, + digest: args.digest.digest + }, + requesterReference: data.recordId, + context: #{ + mode: "submitted", + snapshot: #{activity: data.domainData.activity, site: data.domainData.site} + } + } +} + +fn assess_request(args) { + let data = args.record.data; + #{applicationId: data.recordId, activity: data.domainData.activity, site: data.domainData.site} +} + +fn assess_outcome(args) { + let response = args.response; + if response.status == 200 && "assessment" in response.body { + return #{state: "accepted", result: #{assessment: response.body.assessment}}; + } + #{state: "uncertain"} +} diff --git a/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json b/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json new file mode 100644 index 0000000000..ff00577e62 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/generated/permits.contract.json @@ -0,0 +1 @@ +{"actions":[{"display":{"description":"Record an approved review decision on one submitted application.","label":"Approve application"},"id":"approve-application","input":{"$id":"urn:breg:action:approve-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"applicationId":{"format":"uuid","type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["applicationId","activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"applicationId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["applicationId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"approve-application","x-registry-requiredConditionKeys":["applicationId"]},"mode":"immediate","output":{"$id":"urn:breg:action:approve-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"approve-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:12b02ec4592deda7491b223ae8863241ad3523f244db25f890c300ef74c1eb54"},{"display":{"description":"Record a refused review decision on one submitted application.","label":"Refuse application"},"id":"refuse-application","input":{"$id":"urn:breg:action:refuse-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"applicationId":{"format":"uuid","type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["applicationId","activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{"applicationId":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"}},"required":["applicationId"],"type":"object"}},"required":["input","preconditions"],"type":"object","x-registry-action":"refuse-application","x-registry-requiredConditionKeys":["applicationId"]},"mode":"immediate","output":{"$id":"urn:breg:action:refuse-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"refuse-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"decided-application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["decided-application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:4acdc3bb77437045b615a2db97b63b31cc75369d72a7603de7f4cfebbdb9d72b"},{"display":{"description":"Create a submitted permit application from bounded applicant input.","label":"Submit application"},"id":"submit-application","input":{"$id":"urn:breg:action:submit-application:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"activity":{"maxLength":160,"minLength":1,"type":"string"},"site":{"maxLength":160,"minLength":1,"type":"string"}},"required":["activity","site"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"submit-application","x-registry-requiredConditionKeys":[]},"mode":"immediate","output":{"$id":"urn:breg:action:submit-application:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"submit-application"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"application":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"permit-application"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["application"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"revision":"sha256:cc7a9aa7902efd4871eb5f1b391d153b4194d57634157307cbafcdc5d4c306ce"}],"apiVersion":"id.registrystack.org/formats/breg/action-contracts/v1","kind":"BRegActionContracts"} \ No newline at end of file diff --git a/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml b/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml new file mode 100644 index 0000000000..83ded97e6a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/runtime.yaml @@ -0,0 +1,82 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/runtime/runtime.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +# Deployment references. Under `rstack dev` the bindings in dev.yaml replace +# each connection's address and credential with run-local ones, and the +# preview function host replaces each service function's. +secretProviders: + environment: {} + file: + root: /run/registry-coordinator/secrets +database: + runtimeUrlRef: secret:env/COORDINATOR_DATABASE_URL + migrationUrlRef: secret:env/COORDINATOR_MIGRATION_URL +namespace: coordinator_permits +connections: + review: + type: casework-review-producer + baseUrl: https://casework.example.org + profile: coordinator-producer + producer: coordinator + authorization: + tokenEndpoint: https://identity.permit-review.example.test/oauth/token + clientAssertionAudience: https://identity.permit-review.example.test + clientId: coordinator-producer + signingKeyRef: secret:file/review-client-key + resource: urn:example:permit-review + scopes: [casework:permit:review] + completion: + recipientBinding: coordinator-v1 + hmacSha256KeyRef: secret:file/review-completion-key + permits: + type: breg + baseUrl: https://permits.example.org + profile: permit-coordinator + authorization: + tokenEndpoint: https://identity.permit-review.example.test/oauth/token + clientAssertionAudience: https://identity.permit-review.example.test + clientId: permit-coordinator + signingKeyRef: secret:file/permits-client-key + resource: urn:example:permits + scopes: [registry:permit:decide] + digester: + type: service-function + baseUrl: https://functions.example.org/ + function: digest-application + hostKeyRef: secret:file/function-host-key + responseSchema: {type: object} + assessor: + type: service-function + baseUrl: https://functions.example.org/ + function: assess-permit + hostKeyRef: secret:file/function-host-key + responseSchema: {type: object} +deployment: + databaseId: permit-flow + runtimeRole: coordinator_runtime + packages: + - root: /opt/registry-coordinator/package + expectedDigest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + listener: + bind: 127.0.0.1:8108 + tlsTermination: operator-controlled-upstream + authentication: + issuers: + main: + issuer: https://identity.permit-review.example.test + audience: urn:example:permit-flow + allowedClients: from-access-profiles + accessProfiles: + permit-starter: + requesterClients: [permit-applicant] + subjects: [applicant, neighbour] + requiredScopes: [coordinator:permit:start] + workflows: [permit-flow] + actions: [status, start] + auditFile: /var/lib/registry-coordinator/audit.jsonl + auditKeyRef: secret:file/audit-key + activeStateKey: 1 + stateKeys: + "1": + keyRef: secret:file/state-key-1 + admissionKeyRef: secret:file/admission-key diff --git a/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml b/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml new file mode 100644 index 0000000000..7fb5b2b46d --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/coordinator/workflow.yaml @@ -0,0 +1,293 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json +# One permit application. The starter names only the application; the +# Coordinator reads it under its own BReg profile, and everything it asks +# Casework to review, assesses and decides comes from that read. Casework +# decides, the assess-permit function advises, and BReg records the decision +# only while the stored application still holds the content that was read. +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: permit-flow + version: '1' +contracts: + permits: + type: breg + source: generated/permits.contract.json +types: + workflow-input: + type: object + additionalProperties: false + required: [applicationId] + properties: + applicationId: {type: string, format: uuid} + function-response: + type: object + additionalProperties: false + required: [status, body] + properties: + status: {type: integer, minimum: 200, maximum: 499} + body: {type: object} + digest: + type: object + additionalProperties: false + required: [digest] + properties: + digest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + assessment: + type: object + additionalProperties: false + required: [assessment] + properties: + assessment: {type: string, enum: [standard, conditions]} + digest-outcome: + oneOf: + - type: object + additionalProperties: false + required: [state, result] + properties: + state: {type: string, const: accepted} + result: {typeRef: digest} + - type: object + additionalProperties: false + required: [state] + properties: + state: {type: string, const: uncertain} + assess-outcome: + oneOf: + - type: object + additionalProperties: false + required: [state, result] + properties: + state: {type: string, const: accepted} + result: {typeRef: assessment} + - type: object + additionalProperties: false + required: [state] + properties: + state: {type: string, const: uncertain} +transforms: + submitted-route: + runtime: rhai + source: functions.rhai + entrypoint: submitted_route + inputs: + record: {operationOutput: read-application} + output: {type: string, enum: [submitted, not-submitted]} + digest-request: + runtime: rhai + source: functions.rhai + entrypoint: digest_request + inputs: + record: {operationOutput: read-application} + output: {operationInput: digest-application} + digest-outcome: + runtime: rhai + source: functions.rhai + entrypoint: digest_outcome + inputs: + command: {operationInput: digest-application} + response: {operationOutput: digest-application} + output: {typeRef: digest-outcome} + review-request: + runtime: rhai + source: functions.rhai + entrypoint: review_request + inputs: + record: {operationOutput: read-application} + digest: {typeRef: digest} + output: {operationInput: request-review} + assess-request: + runtime: rhai + source: functions.rhai + entrypoint: assess_request + inputs: + record: {operationOutput: read-application} + output: {operationInput: assess-permit} + assess-outcome: + runtime: rhai + source: functions.rhai + entrypoint: assess_outcome + inputs: + command: {operationInput: assess-permit} + response: {operationOutput: assess-permit} + output: {typeRef: assess-outcome} +operations: + read-application: + uses: breg.read-record/v1 + connection: permits + digest-application: + uses: service.invoke-function/v1 + connection: digester + serviceFunction: digest-application + responseSchema: {typeRef: function-response} + interpret: digest-outcome + request-review: + uses: casework.submit-review-request/v1 + connection: review + assess-permit: + uses: service.invoke-function/v1 + connection: assessor + serviceFunction: assess-permit + responseSchema: {typeRef: function-response} + interpret: assess-outcome + approve-application: + uses: breg.invoke-action/v1 + connection: permits + action: {contract: permits, id: approve-application} + refuse-application: + uses: breg.invoke-action/v1 + connection: permits + action: {contract: permits, id: refuse-application} +workflow: + input: {typeRef: workflow-input} + deadlineSeconds: 2592000 + start: read-application + steps: + read-application: + label: Read the application under the Coordinator's profile + type: call + operation: read-application + input: + type: fields + fields: + collection: {type: literal, value: permit-applications} + recordId: {type: input, path: /applicationId} + next: check-submitted + check-submitted: + type: choose + choose: + type: transform + transform: submitted-route + inputs: + record: {type: step, step: read-application} + cases: + submitted: digest + not-submitted: not-submitted + digest: + label: Digest the content read + type: call + operation: digest-application + input: + type: transform + transform: digest-request + inputs: + record: {type: step, step: read-application} + next: request-review + request-review: + label: Ask Casework for a review + type: call + operation: request-review + input: + type: transform + transform: review-request + inputs: + record: {type: step, step: read-application} + digest: {type: step, step: digest} + next: await-review + await-review: + label: Wait for the officer's decision + type: wait-for + timeoutSeconds: 1209600 + next: decide + onTimeout: review-timed-out + completion: {step: request-review, name: result} + decide: + type: choose + choose: {type: step, step: await-review, path: /status} + cases: + approved: assess + rejected: refuse + changes-requested: not-decided + answered: not-decided + cancelled: not-decided + superseded: not-decided + assess: + label: Assess the approved permit + type: call + operation: assess-permit + input: + type: transform + transform: assess-request + inputs: + record: {type: step, step: read-application} + next: approve + approve: + label: Record the approval in the register + type: call + operation: approve-application + input: + type: fields + fields: + input: + type: fields + fields: + applicationId: {type: step, step: read-application, path: /data/recordId} + activity: {type: step, step: read-application, path: /data/domainData/activity} + site: {type: step, step: read-application, path: /data/domainData/site} + next: approved + refuse: + label: Record the refusal in the register + type: call + operation: refuse-application + input: + type: fields + fields: + input: + type: fields + fields: + applicationId: {type: step, step: read-application, path: /data/recordId} + activity: {type: step, step: read-application, path: /data/domainData/activity} + site: {type: step, step: read-application, path: /data/domainData/site} + next: refused + approved: + type: finish + outcome: approved + output: + type: fields + fields: + assessment: {type: step, step: assess, path: /assessment} + resultId: {type: step, step: await-review, path: /resultId} + refused: + type: finish + outcome: refused + output: + type: fields + fields: + resultId: {type: step, step: await-review, path: /resultId} + not-submitted: + type: finish + outcome: not-submitted + not-decided: + type: finish + outcome: not-decided + output: + type: fields + fields: + status: {type: step, step: await-review, path: /status} + review-timed-out: + type: finish + outcome: review-timed-out + outcomes: + approved: + type: object + additionalProperties: false + required: [assessment, resultId] + properties: + assessment: {type: string, enum: [standard, conditions]} + resultId: {type: string, format: uuid} + refused: + type: object + additionalProperties: false + required: [resultId] + properties: + resultId: {type: string, format: uuid} + not-submitted: + type: 'null' + not-decided: + type: object + additionalProperties: false + required: [status] + properties: + status: {type: string} + review-timed-out: + type: 'null' diff --git a/products/platform/examples/service-previews/permit-review/dev-journeys.yaml b/products/platform/examples/service-previews/permit-review/dev-journeys.yaml new file mode 100644 index 0000000000..a176eeae9d --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/dev-journeys.yaml @@ -0,0 +1,31 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/journeys/journeys.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 +kind: RStackJourneys +journeys: + - id: staff-permit-officers + steps: + # The officer decides only once Casework staffs the queue with that + # person under the run's issuer. + - id: staff-the-queue + product: casework + as: administrator + method: POST + path: /v1/directory/bootstrap + headers: {If-Match: '"0"', Idempotency-Key: staff-permit-officers} + body: + teamId: permit-officers-team + staff: [{issuer: "{{run.issuer}}", subject: officer}] + supervisors: [] + queueId: permit-officers + expect: {status: 200} + - id: neighbour-application + steps: + # Another applicant's application, so the preview has a second record. + - id: neighbour-submits + product: breg + as: neighbour + method: POST + path: /v1/actions/submit-application + headers: {Idempotency-Key: neighbour-application} + body: {input: {activity: Daytime survey, site: Market square}} + expect: {status: 200} diff --git a/products/platform/examples/service-previews/permit-review/dev.yaml b/products/platform/examples/service-previews/permit-review/dev.yaml new file mode 100644 index 0000000000..b8f5e43b3d --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/dev.yaml @@ -0,0 +1,90 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/dev/dev.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: run +audiences: + permits: "urn:example:permits" + casework: "urn:example:permit-review" + permit-flow: "urn:example:permit-flow" +people: + applicant: + subject: applicant + client: permit-applicant + roles: [applicant] + claims: + breg: {registry_office: central} + officer: + subject: officer + client: permit-officer + roles: [officer] + claims: + breg: {registry_office: central} + administrator: + subject: administrator + client: permit-administrator + roles: [administrator] + coordinator-producer: + subject: coordinator-producer + client: coordinator-producer + roles: [coordinator-producer] + neighbour: + subject: neighbour + client: permit-applicant + roles: [applicant] + claims: + breg: {registry_office: central} + coordinator-service: + subject: coordinator-service + client: permit-coordinator + roles: [coordinator-service] + claims: + breg: {registry_office: central} + # The BReg schema tests decide as this person, so the Coordinator's own + # BReg identity stays dedicated to the Coordinator. In development it holds + # the Coordinator's decide authority for those journeys, and a decision it + # makes bypasses review. + register-tester: + subject: register-tester + client: permit-coordinator + roles: [coordinator-service] + claims: + breg: {registry_office: central} +journeyFile: dev-journeys.yaml +bindings: + coordinatorReviewProducer: + connection: review + producer: coordinator + identity: coordinator-producer + completionDestination: coordinator-wake + runIssuerBinding: + producer: + expectedIssuer: https://identity.permit-review.example.test + expectedProfile: coordinator-producer + expectedSubject: coordinator-producer + coordinatorBregClient: + connection: permits + identity: coordinator-service +preview: + page: / + functions: [assess-permit, digest-application] + actors: + # The applicant submits and follows its own run. It reads no + # application from BReg, and Casework refuses its decisions. + applicant: + breg: + post: [/v1/actions/submit-application] + casework: + post: ["/v1/review-tasks/{taskId}/decisions"] + coordinator: + get: [/v1/workflows/permit-flow, "/v1/runs/{runId}"] + post: [/v1/runs] + # A second applicant, to show one applicant cannot follow another's run. + neighbour: + coordinator: + get: ["/v1/runs/{runId}"] + officer: + breg: + get: [/v1/records/permit-applications, "/v1/records/permit-applications/{recordId}"] + casework: + get: [/v1/review-tasks, "/v1/review-tasks/{taskId}/context"] + post: ["/v1/review-tasks/{taskId}/claim", "/v1/review-tasks/{taskId}/decisions"] diff --git a/products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts b/products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts new file mode 100644 index 0000000000..87494b623d --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/assess-permit/assess.ts @@ -0,0 +1,32 @@ +export type Assessment = 'standard' | 'conditions' + +// Night work or work on a public road carries standard conditions. The +// assessment is advice the Coordinator records; it decides nothing. +export function assess(activity: string, site: string): Assessment { + const text = (activity + ' ' + site).toLowerCase() + return /\bnight\b|\broad\b/u.test(text) ? 'conditions' : 'standard' +} + +function bounded(value: unknown, maximumLength: number) { + if (typeof value !== 'string') return undefined + const text = value.trim() + return text.length > 0 && text.length <= maximumLength ? text : undefined +} + +function answer(body: object, status: number) { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +export async function handleAssessment(request: Request) { + if (request.method !== 'POST') return answer({ message: 'Send a POST request.' }, 405) + let submitted: { activity?: unknown; site?: unknown } | null + try { + submitted = await request.json() + } catch { + return answer({ message: 'Send the application details as JSON.' }, 400) + } + const activity = bounded(submitted?.activity, 160) + const site = bounded(submitted?.site, 160) + if (!activity || !site) return answer({ message: 'Send an activity and a site.' }, 400) + return answer({ assessment: assess(activity, site) }, 200) +} diff --git a/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts b/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts new file mode 100644 index 0000000000..69bcc49cf5 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/assess-permit/index.ts @@ -0,0 +1,8 @@ +import { defineFunction } from '../../generated/server.js' +import { handleAssessment } from './assess.js' + +// The Coordinator calls this function with the run host key, which the +// function host replaces with a placeholder. It holds no registry credential: +// it returns an assessment of the content the Coordinator read and records +// nothing itself. +export default defineFunction(async (request) => handleAssessment(request)) diff --git a/products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts b/products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts new file mode 100644 index 0000000000..82024cc1cc --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/digest-application/digest.ts @@ -0,0 +1,33 @@ +function bounded(value: unknown, maximumLength: number) { + return typeof value === 'string' && value.length > 0 && value.length <= maximumLength ? value : undefined +} + +function answer(body: object, status: number) { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +// The digest of the exact application content the Coordinator read, as one +// JSON array, so Casework's review subject names that content. +export async function digestApplication(applicationId: string, revisionId: string, activity: string, site: string) { + const canonical = new TextEncoder().encode(JSON.stringify([applicationId, revisionId, activity, site])) + const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', canonical)) + return 'sha256:' + Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') +} + +export async function handleDigest(request: Request) { + if (request.method !== 'POST') return answer({ message: 'Send a POST request.' }, 405) + let submitted: Record | null + try { + submitted = await request.json() + } catch { + return answer({ message: 'Send the application content as JSON.' }, 400) + } + const applicationId = bounded(submitted?.applicationId, 64) + const revisionId = bounded(submitted?.revisionId, 64) + const activity = bounded(submitted?.activity, 160) + const site = bounded(submitted?.site, 160) + if (!applicationId || !revisionId || !activity || !site) { + return answer({ message: 'Send the application ID, revision, activity and site.' }, 400) + } + return answer({ digest: await digestApplication(applicationId, revisionId, activity, site) }, 200) +} diff --git a/products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts b/products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts new file mode 100644 index 0000000000..e227053bba --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/functions/digest-application/index.ts @@ -0,0 +1,7 @@ +import { defineFunction } from '../../generated/server.js' +import { handleDigest } from './digest.js' + +// The Coordinator calls this function with the run host key, which the +// function host replaces with a placeholder. It holds no registry credential: +// it hashes the content the Coordinator read and returns the digest. +export default defineFunction(async (request) => handleDigest(request)) diff --git a/products/platform/examples/service-previews/permit-review/manifest.yaml b/products/platform/examples/service-previews/permit-review/manifest.yaml new file mode 100644 index 0000000000..ef5633aacc --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/manifest.yaml @@ -0,0 +1,3 @@ +public_services: + - id: review-a-permit + title: Apply for a reviewed permit diff --git a/products/platform/examples/service-previews/permit-review/package-lock.json b/products/platform/examples/service-previews/permit-review/package-lock.json new file mode 100644 index 0000000000..3283b9bd6a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/package-lock.json @@ -0,0 +1,528 @@ +{ + "name": "permit-review", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@registrystack/client": "file:registry-preview-client.tgz" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@registrystack/client": { + "version": "0.50.0", + "resolved": "file:registry-preview-client.tgz", + "integrity": "sha512-NPAHDsmoc12s97/ar9raWVPrmh5BsBsfo1frQSMPFxCKc+6RgPSvhTAs5Pxwk4RCr1GJm0vqzbOfc13UHDQxXA==", + "license": "Apache-2.0", + "dependencies": { + "esbuild": "0.25.12", + "srvx": "1.0.8", + "typescript": "5.9.3", + "yaml": "2.9.1" + }, + "bin": { + "registry-generate": "registry-generate.js", + "registry-preview": "preview/cli.mjs" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/srvx": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/srvx/-/srvx-1.0.8.tgz", + "integrity": "sha512-ngFS/J6St4PJfHRHGjr78xkPPtbyXtdMOLNE4x/XZunEK3OhV7aGUWMHf9WTUEy6wm1U0W4okkd82ZFFWRVQTw==", + "license": "MIT", + "bin": { + "srvx": "bin/srvx.mjs" + }, + "engines": { + "node": ">=20.16.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + } + } +} diff --git a/products/platform/examples/service-previews/permit-review/package.json b/products/platform/examples/service-previews/permit-review/package.json new file mode 100644 index 0000000000..d40b7b9739 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/package.json @@ -0,0 +1,8 @@ +{ + "name": "permit-review", + "private": true, + "type": "module", + "dependencies": { + "@registrystack/client": "file:registry-preview-client.tgz" + } +} diff --git a/products/platform/examples/service-previews/permit-review/project/registry.yaml b/products/platform/examples/service-previews/permit-review/project/registry.yaml new file mode 100644 index 0000000000..a53055da3d --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/project/registry.yaml @@ -0,0 +1,182 @@ +# The permit register owns the authoritative application Record, the +# applicant's submission Action and the decision Action. Only the +# Coordinator's service profile may record a decision. +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: permit-register + canonicalBaseIri: https://permit-register.example.gov + version: 0.1.0 + defaultLanguage: en + display: + label: Permit register + description: Authoritative permit application Records. + +package: + sourceRevision: permit-register-0.1.0 + +datasets: + applications: + display: + label: Permit applications + description: Applications submitted for a permit. + +recordTypes: + permit-application: + route: permit-applications + primaryDataset: applications + mutationMode: mutable + display: + label: Permit application + titleField: activity + description: One application for a permit. + fields: + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: office, type: string, required: true, minimumLength: 1, maximumLength: 40, classification: internal} + - {id: status, type: vocabulary-code, vocabulary: application-status, required: true, classification: internal} + +actions: + submit-application: + display: + label: Submit application + description: Create a submitted permit application from bounded applicant input. + execution: {mode: immediate} + inputs: + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + plan: + type: fixed + effects: + - id: application + target: {recordType: permit-application} + operation: create + set: + activity: {fromInput: activity} + site: {fromInput: site} + office: {value: central} + status: {value: submitted} + approve-application: + display: + label: Approve application + description: Record an approved review decision on one submitted application. + execution: {mode: immediate} + inputs: + - {id: application, apiName: applicationId, type: reference, target: permit-application, required: true, classification: internal} + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + # The caller names the content it read and had reviewed. The write + # applies only while the stored application still holds exactly that + # content and has not been decided. This binds the decision to the review + # only while every field in the review snapshot is guarded here and no + # Action can change a guarded field: add a guard with any new snapshot + # field, and add no Action that edits activity or site. + commitGuards: + targets: + - {input: application, field: status, equals: submitted, reason: not-submitted} + - {input: application, field: activity, equalsFromInput: activity, reason: content-changed} + - {input: application, field: site, equalsFromInput: site, reason: content-changed} + plan: + type: fixed + effects: + - id: decided-application + target: {fromInput: application} + operation: patch + set: + status: {value: approved} + refuse-application: + display: + label: Refuse application + description: Record a refused review decision on one submitted application. + execution: {mode: immediate} + inputs: + - {id: application, apiName: applicationId, type: reference, target: permit-application, required: true, classification: internal} + - {id: activity, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + - {id: site, type: string, required: true, minimumLength: 1, maximumLength: 160, classification: internal} + # The caller names the content it read and had reviewed. The write + # applies only while the stored application still holds exactly that + # content and has not been decided. This binds the decision to the review + # only while every field in the review snapshot is guarded here and no + # Action can change a guarded field: add a guard with any new snapshot + # field, and add no Action that edits activity or site. + commitGuards: + targets: + - {input: application, field: status, equals: submitted, reason: not-submitted} + - {input: application, field: activity, equalsFromInput: activity, reason: content-changed} + - {input: application, field: site, equalsFromInput: site, reason: content-changed} + plan: + type: fixed + effects: + - id: decided-application + target: {fromInput: application} + operation: patch + set: + status: {value: refused} + +accessProfiles: + permit-applicant: + actorKind: human + requesterClients: [permit-applicant] + display: + label: Permit applicant + description: Submits permit applications. Reads none; the applicant follows its review run. + principalClaim: sub + requiredScopes: ["registry:permit:apply"] + permissions: + actions: + - action: submit-application + operations: [invoke] + targets: + - recordType: permit-application + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + results: [application] + permit-reader: + actorKind: human + requesterClients: [permit-officer] + display: + label: Permit reader + description: Reads permit applications in the office. + principalClaim: sub + requiredScopes: ["registry:permit:read"] + permissions: + records: + - recordType: permit-application + operations: [get, list] + readableFields: [activity, site, office, status] + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + permit-coordinator: + actorKind: service + requesterClients: [permit-coordinator] + display: + label: Permit Coordinator + description: Records reviewed decisions on submitted applications. + principalClaim: sub + requiredScopes: ["registry:permit:decide"] + permissions: + records: + - recordType: permit-application + operations: [get] + readableFields: [activity, site, office, status] + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + actions: + - action: approve-application + operations: [invoke] + targets: + - recordType: permit-application + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + results: [decided-application] + - action: refuse-application + operations: [invoke] + targets: + - recordType: permit-application + rowBoundaries: + - {field: office, claim: registry_office, operator: equals} + results: [decided-application] + +vocabularies: + application-status: + values: [submitted, approved, refused] diff --git a/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml b/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml new file mode 100644 index 0000000000..9af2db4729 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/project/tests/journeys.yaml @@ -0,0 +1,115 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: permit-decision + steps: + - id: applicant-submits + actor: applicant + action: submit-application + accessProfile: permit-applicant + claims: + principal: applicant + scopes: [registry:permit:apply] + actorKind: human + requesterClient: permit-applicant + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-application-2026-001 + input: {activity: Night resurfacing, site: North road} + expect: {outcome: success, status: 200} + captureResults: {application: application} + - id: register-tester-reads-approval-conditions + actor: register-tester + action: approve-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: target-conditions + input: {applicationId: {recordCapture: application}} + expect: {outcome: success, status: 200} + capture: approval-condition + - id: register-tester-refused-for-other-content + actor: register-tester + action: approve-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-approve-other-content + input: {applicationId: {recordCapture: application}, activity: Daytime survey, site: North road} + preconditions: + applicationId: {conditionCapture: approval-condition} + expect: {outcome: refusal, status: 412, problemCode: action.guard-failed} + - id: register-tester-approves-the-content-read + actor: register-tester + action: approve-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-approve + input: {applicationId: {recordCapture: application}, activity: Night resurfacing, site: North road} + preconditions: + applicationId: {conditionCapture: approval-condition} + expect: {outcome: success, status: 200} + - id: register-tester-reads-refusal-conditions + actor: register-tester + action: refuse-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: target-conditions + input: {applicationId: {recordCapture: application}} + expect: {outcome: success, status: 200} + capture: refusal-condition + - id: register-tester-cannot-decide-twice + actor: register-tester + action: refuse-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: + type: invoke + idempotencyKey: native-permit-refuse-after-approval + input: {applicationId: {recordCapture: application}, activity: Night resurfacing, site: North road} + preconditions: + applicationId: {conditionCapture: refusal-condition} + expect: {outcome: refusal, status: 412, problemCode: action.guard-failed} + - id: register-tester-reads-the-decision + actor: register-tester + recordType: permit-application + accessProfile: permit-coordinator + claims: + principal: register-tester + scopes: [registry:permit:decide] + actorKind: service + requesterClient: permit-coordinator + directClaims: {registry_office: central} + request: {type: get, recordCapture: application} + expect: {outcome: success, status: 200, fields: {status: approved, activity: Night resurfacing}} diff --git a/products/platform/examples/service-previews/permit-review/service.yaml b/products/platform/examples/service-previews/permit-review/service.yaml new file mode 100644 index 0000000000..9e363a44b2 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/service.yaml @@ -0,0 +1,40 @@ +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +service: {manifest: manifest.yaml, publicService: review-a-permit} +products: + breg: + projects: + permits: {path: project} + casework: {path: casework} + coordinator: + projects: + permit-flow: {path: coordinator} +ui: {project: web, output: dist} +functions: [assess-permit, digest-application] +roles: + applicant: + actorKind: human + claims: [registry_office] + accessProfiles: + breg: [permit-applicant] + casework: [permit-applicant] + coordinator: [permit-starter] + officer: + actorKind: human + claims: [registry_office] + accessProfiles: + breg: [permit-reader] + casework: [permit-officer] + administrator: + actorKind: human + accessProfiles: + casework: [permit-administrator] + coordinator-producer: + actorKind: service + accessProfiles: + casework: [coordinator-producer] + coordinator-service: + actorKind: service + claims: [registry_office] + accessProfiles: + breg: [permit-coordinator] diff --git a/products/platform/examples/service-previews/permit-review/web/public/index.html b/products/platform/examples/service-previews/permit-review/web/public/index.html new file mode 100644 index 0000000000..b1f0960431 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/public/index.html @@ -0,0 +1,73 @@ + + + + + + Apply for a reviewed permit + + + + + +
Registry Stack demonstration
+
Permit review
+
+

Apply for a reviewed permit

+ +

+ + +
+ + diff --git a/products/platform/examples/service-previews/permit-review/web/public/service.css b/products/platform/examples/service-previews/permit-review/web/public/service.css new file mode 100644 index 0000000000..4f0edde4f0 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/public/service.css @@ -0,0 +1,29 @@ +* { box-sizing: border-box; } +body { + margin: 0; + background: #f7f3f3; + color: #2c2c2c; + font: 18px/1.5 system-ui, sans-serif; +} +.skip-link { position: absolute; left: -9999px; } +.skip-link:focus { left: 1rem; top: 1rem; background: white; padding: 0.75rem; } +.official-banner { background: #2c2c2c; color: white; padding: 0.5rem 1.5rem; text-align: center; font-size: 0.8rem; } +header { background: #ffc726; border-bottom: 3px solid #2c2c2c; padding: 1rem 1.5rem; font-size: 1.35rem; font-weight: 700; } +main { max-width: 46rem; margin: 2rem auto; padding: 0 1.5rem; } +h1 { font-size: 2.25rem; line-height: 1.2; } +.field { margin: 1.75rem 0; } +label { display: block; font-size: 1.15rem; font-weight: 700; } +.hint { display: block; color: #595959; font-size: 1rem; margin-bottom: 0.5rem; } +input { width: 100%; max-width: 32rem; border: 2px solid #2c2c2c; padding: 0.65rem; font: inherit; } +input:focus, button:focus, a:focus { outline: 4px solid #ffc726; outline-offset: 2px; } +button { border: 0; background: #00703c; color: white; padding: 0.75rem 1.5rem; font: inherit; font-weight: 700; cursor: pointer; } +button:disabled { opacity: 0.7; cursor: default; } +.error:not(:empty) { border: 4px solid #b71c1c; padding: 1rem; } +.confirmation { margin-top: 2rem; background: #e8f5e9; border-left: 6px solid #00703c; padding: 1rem 1.25rem; } +.confirmation h2 { margin-top: 0; } +dl { background: white; margin-bottom: 0; } +dl div { display: grid; grid-template-columns: minmax(9rem, 1fr) 2fr; gap: 1rem; border-bottom: 1px solid #ddd; padding: 0.75rem; } +dl div:last-child { border-bottom: 0; } +dt { font-weight: 700; } +dd { margin: 0; overflow-wrap: anywhere; } +[hidden], #error:empty, #status:empty { display: none; } diff --git a/products/platform/examples/service-previews/permit-review/web/src/page.ts b/products/platform/examples/service-previews/permit-review/web/src/page.ts new file mode 100644 index 0000000000..69647d6e17 --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/src/page.ts @@ -0,0 +1,210 @@ +// One built page serves every actor. Each actor's gateway origin answers +// /_rstack/actor and relays only that actor's paths with that actor's own +// credential, so the page never holds a credential or chooses a profile. + +type Json = Record + +function element(id: string): T { + const node = document.getElementById(id) + if (!node) throw new Error('The page needs #' + id) + return node as T +} + +function text(value: FormDataEntryValue | null, maximumLength: number) { + if (typeof value !== 'string') return undefined + const bounded = value.trim() + return bounded.length > 0 && bounded.length <= maximumLength ? bounded : undefined +} + +function field(value: unknown, ...path: string[]): unknown { + return path.reduce((node, key) => + typeof node === 'object' && node !== null ? (node as Json)[key] : undefined, value) +} + +async function call(path: string, init: { method?: string; body?: unknown; headers?: Record } = {}) { + const response = await fetch(path, { + method: init.method ?? 'GET', + credentials: 'same-origin', + headers: { + Accept: 'application/json', + 'Registry-Client': 'page', + ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), + ...init.headers, + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }) + const body: unknown = response.status === 204 ? null : await response.json().catch(() => null) + return { status: response.status, body } +} + +const alert = element('error') +const status = element('status') + +async function applicant() { + element('applicant').hidden = false + const form = element('application') + form.addEventListener('submit', async (event) => { + event.preventDefault() + alert.textContent = '' + const data = new FormData(form) + const activity = text(data.get('activity'), 160) + const site = text(data.get('site'), 160) + if (!activity || !site) { + alert.textContent = 'Enter an activity and a site within the stated limits.' + return + } + element('submit').disabled = true + status.textContent = 'Submitting the application.' + try { + const submitted = await call('/registry/permits/v1/actions/submit-application', { + method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, + body: { input: { activity, site } }, + }) + const recordId = field(submitted.body, 'results', 'application', 'recordId') + if (submitted.status !== 200 || typeof recordId !== 'string') throw new Error('submit') + element('application-id').textContent = recordId + + const contract = await call('/registry/permit-flow/v1/workflows/permit-flow') + const workflowRevision = field(contract.body, 'workflowRevision') + if (contract.status !== 200 || typeof workflowRevision !== 'string') throw new Error('workflow') + // The run names only the application. The Coordinator reads it under + // its own profile and reviews and decides only what it read. + const started = await call('/registry/permit-flow/v1/runs', { + method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, + body: { workflow: 'permit-flow', workflowRevision, input: { applicationId: recordId } }, + }) + const runId = field(started.body, 'runId') + if (started.status !== 200 || typeof runId !== 'string') throw new Error('start') + element('run-id').textContent = runId + element('submitted').hidden = false + form.hidden = true + status.textContent = '' + await follow(runId) + } catch { + alert.textContent = 'We could not submit the application and start its review.' + status.textContent = '' + element('submit').disabled = false + } + }) + + // The applicant's own attempt to decide: Casework, not the page, refuses it. + const attempt = element('decision-attempt') + attempt.addEventListener('submit', async (event) => { + event.preventDefault() + const taskId = text(new FormData(attempt).get('taskId'), 64) + if (!taskId) return + const decided = await call('/registry/casework/v1/review-tasks/' + taskId + '/decisions', { + method: 'POST', headers: { 'If-Match': '"1"', 'Idempotency-Key': crypto.randomUUID() }, + body: { decision: { type: 'approve', outcome: 'approved' } }, + }) + element('decision-attempt-result').textContent = decided.status === 403 + ? 'Casework refused the decision (403).' + : 'Casework answered ' + decided.status + '.' + }) +} + +async function follow(runId: string) { + for (;;) { + const run = await call('/registry/permit-flow/v1/runs/' + runId) + const state = field(run.body, 'state') + element('run-step').textContent = String(field(run.body, 'step') ?? '') + element('run-state').textContent = String(state ?? '') + // Every state but these two is terminal or needs an operator. + if (typeof state === 'string' && state !== 'running' && state !== 'cancel-requested') { + element('run-outcome').textContent = String(field(run.body, 'outcome') ?? '') + element('run-assessment').textContent = String(field(run.body, 'output', 'assessment') ?? '') + return + } + await new Promise(resolve => setTimeout(resolve, 1000)) + } +} + +function line(label: string, value: unknown) { + const item = document.createElement('div') + const term = document.createElement('dt') + term.textContent = label + const detail = document.createElement('dd') + detail.textContent = String(value ?? '') + item.append(term, detail) + return item +} + +// The officer sees the content under review before claiming, and claims and +// approves in two separate steps. +async function officer() { + element('officer').hidden = false + const list = element('tasks') + element('refresh').addEventListener('click', async () => { + const tasks = await call('/registry/casework/v1/review-tasks?queue=permit-officers') + const items = field(tasks.body, 'items') + list.replaceChildren() + for (const task of Array.isArray(items) ? items : []) { + const taskId = field(task, 'taskId') + if (typeof taskId !== 'string') continue + const context = await call('/registry/casework/v1/review-tasks/' + taskId + '/context') + const snapshot = field(context.body, 'context', 'snapshot') + const item = document.createElement('li') + item.dataset.taskId = taskId + item.dataset.applicationId = String(field(context.body, 'subject', 'id') ?? '') + const details = document.createElement('dl') + details.append( + line('Activity', field(snapshot, 'activity')), + line('Site', field(snapshot, 'site')), + line('Application', field(context.body, 'subject', 'id')), + ) + let revision = field(task, 'revision') + const claim = document.createElement('button') + claim.textContent = 'Claim' + const approve = document.createElement('button') + approve.textContent = 'Approve' + approve.disabled = true + claim.addEventListener('click', async () => { + claim.disabled = true + const claimed = await call('/registry/casework/v1/review-tasks/' + taskId + '/claim', { + method: 'POST', headers: { 'If-Match': '"' + String(revision) + '"', 'Idempotency-Key': crypto.randomUUID() }, + }) + revision = field(claimed.body, 'revision') + item.dataset.claimed = String(claimed.status) + claim.textContent = claimed.status === 200 ? 'Claimed' : 'Casework answered ' + claimed.status + approve.disabled = claimed.status !== 200 + }) + approve.addEventListener('click', async () => { + approve.disabled = true + const decided = await call('/registry/casework/v1/review-tasks/' + taskId + '/decisions', { + method: 'POST', headers: { 'If-Match': '"' + String(revision) + '"', 'Idempotency-Key': crypto.randomUUID() }, + body: { decision: { type: 'approve', outcome: 'approved' } }, + }) + item.dataset.decided = String(decided.status) + approve.textContent = decided.status === 204 ? 'Approved' : 'Casework answered ' + decided.status + }) + item.append(details, claim, ' ', approve) + list.append(item) + } + }) + + const lookup = element('application-lookup') + lookup.addEventListener('submit', async (event) => { + event.preventDefault() + const recordId = text(new FormData(lookup).get('applicationId'), 64) + if (!recordId) return + const record = await call('/registry/permits/v1/records/permit-applications/' + recordId) + const data = field(record.body, 'data', 'domainData') + element('register-activity').textContent = String(field(data, 'activity') ?? '') + element('register-site').textContent = String(field(data, 'site') ?? '') + element('register-status').textContent = String(field(data, 'status') ?? record.status) + }) +} + +// The page bundles as a classic script, so it starts from one async call. +async function start() { + const whoami = await call('/_rstack/actor') + const actor = field(whoami.body, 'actor') + element('actor').textContent = String(actor ?? '') + if (actor === 'applicant') await applicant() + else if (actor === 'officer') await officer() + else alert.textContent = 'This page has no controls for this person.' +} + +start().catch(() => { + alert.textContent = 'This page could not start.' +}) diff --git a/products/platform/examples/service-previews/permit-review/web/tsconfig.json b/products/platform/examples/service-previews/permit-review/web/tsconfig.json new file mode 100644 index 0000000000..9d2bcc4a8a --- /dev/null +++ b/products/platform/examples/service-previews/permit-review/web/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "lib": ["DOM", "ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmit": true, + "strict": true, + "target": "ES2023" + }, + "include": ["src/**/*.ts"] +} diff --git a/products/platform/examples/session/checked-routes.json b/products/platform/examples/session/checked-routes.json new file mode 100644 index 0000000000..8bfb0ee170 --- /dev/null +++ b/products/platform/examples/session/checked-routes.json @@ -0,0 +1,34 @@ +{ + "apiVersion": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", + "gatewayDigest": "sha256:32c5a92f7b5f7f446b196f96cfab1d856a395cb8587be13dc44de4330ea95091", + "kind": "PlatformSessionRouteInventory", + "modules": [ + { + "id": "businesses", + "prefix": "/registry/businesses/", + "prefixRewrite": "/", + "product": "breg", + "signIns": [ + "registrar" + ] + }, + { + "id": "functions", + "prefix": "/api/functions/", + "prefixRewrite": "/functions/", + "product": "breg", + "signIns": [ + "registrar" + ] + } + ], + "pages": [ + { + "prefix": "/apply/", + "signIn": "registrar" + } + ], + "publicOrigin": "https://127.0.0.1:8443", + "selectedModule": "businesses", + "signInDigest": "sha256:7c31878d23b2a2d12e0766bafa78f8c220d4d05481b1dcc36650030095552ce9" +} diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index e2de0691ec..9ce15fb8db 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -1,5 +1,21 @@ { "$defs": { + "ActorRoutes": { + "additionalProperties": false, + "description": "The product paths one preview actor may reach, grouped by product and\nmethod.", + "properties": { + "breg": { + "$ref": "#/$defs/Routes" + }, + "casework": { + "$ref": "#/$defs/Routes" + }, + "coordinator": { + "$ref": "#/$defs/Routes" + } + }, + "type": "object" + }, "ApplicationPlan": { "additionalProperties": false, "description": "A generic Node application and its configuration command. All artifact paths are relative to the supplied built root.", @@ -274,7 +290,7 @@ }, "Bindings": { "additionalProperties": false, - "description": "Run-local connections between BReg and Casework. Configuring either one requires both products.", + "description": "Run-local connections between products. The BReg and Casework bindings require both products; the Coordinator review producer requires Coordinator and Casework.", "properties": { "bregReviewAuthority": { "$ref": "#/$defs/BregReviewAuthority", @@ -283,6 +299,14 @@ "caseworkContextProvider": { "$ref": "#/$defs/CaseworkContextProvider", "description": "Connects Casework to BReg as a context provider. Casework authenticates to BReg as a machine identity." + }, + "coordinatorBregClient": { + "$ref": "#/$defs/CoordinatorBregClient", + "description": "Gives one Coordinator BReg connection a machine identity on the run's token endpoint, with exactly one test person's BReg grant. BReg's own access profile and Action rules decide every call. Development runs only." + }, + "coordinatorReviewProducer": { + "$ref": "#/$defs/CoordinatorReviewProducer", + "description": "Connects the Coordinator to Casework as one trusted review producer. The Coordinator authenticates to Casework as a machine identity, and Casework wakes its waiting run through a completion hook. Development runs only." } }, "type": "object" @@ -339,6 +363,59 @@ ], "type": "object" }, + "CoordinatorBregClient": { + "additionalProperties": false, + "description": "One Coordinator `breg` connection the run authenticates as one test\nperson. The person's BReg grant is the only source of the connection's\nprofile and scopes; nothing in dev.yaml adds to them.", + "properties": { + "connection": { + "$ref": "#/$defs/LocalId", + "description": "The Coordinator `runtime.yaml` connection of type `breg`, without task authority." + }, + "identity": { + "$ref": "#/$defs/LocalId", + "description": "Name of the test person, in `people`, whose BReg grant the Coordinator uses." + } + }, + "required": [ + "connection", + "identity" + ], + "type": "object" + }, + "CoordinatorReviewProducer": { + "additionalProperties": false, + "description": "The Coordinator's Casework review producer connection that the run binds\nto Casework. Casework trusts exactly the producer the connection names, for\nthe run issuer, only when its pinned issuer, profile and subject match the\nguards; nothing here widens what Casework trusts.", + "properties": { + "completionDestination": { + "$ref": "#/$defs/LocalId", + "description": "The completion `destinationId` the producer names in `casework.yaml`. The run binds it to the Coordinator's completion endpoint with a per-run key." + }, + "connection": { + "$ref": "#/$defs/LocalId", + "description": "The Coordinator `runtime.yaml` connection of type `casework-review-producer`. Its `producer` names the Casework trusted producer." + }, + "identity": { + "$ref": "#/$defs/LocalId", + "description": "Name of the test person, in `people`, whose Casework grant the Coordinator uses to authenticate. Its profile and subject are the producer's." + }, + "producer": { + "$ref": "#/$defs/LocalId", + "description": "The Casework trusted producer in `casework.yaml`. It must be the producer the connection names." + }, + "runIssuerBinding": { + "$ref": "#/$defs/ProducerIssuerBinding", + "description": "The exact source guards for binding this producer to the synthetic run issuer. It has no initiator guard." + } + }, + "required": [ + "connection", + "producer", + "identity", + "completionDestination", + "runIssuerBinding" + ], + "type": "object" + }, "DerivedId": { "description": "A dotted development journey step identifier whose segments are local identifiers.", "maxLength": 64, @@ -390,6 +467,18 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, + "ExternalScheduling": { + "additionalProperties": false, + "properties": { + "taskGrant": { + "$ref": "#/$defs/TaskGrant" + } + }, + "required": [ + "taskGrant" + ], + "type": "object" + }, "Hook": { "additionalProperties": false, "properties": { @@ -415,16 +504,46 @@ "pattern": "^[a-z][a-z0-9_-]{0,63}$", "type": "string" }, + "NamedProjects": { + "additionalProperties": false, + "properties": { + "projects": { + "additionalProperties": { + "$ref": "#/$defs/ProjectReference" + }, + "description": "Projects keyed by project ID. In a service, BReg IDs form the generated client member names.", + "minProperties": 1, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + } + }, + "required": [ + "projects" + ], + "type": "object" + }, "Preview": { "additionalProperties": false, "properties": { "actor": { "$ref": "#/$defs/LocalId", - "description": "Synthetic development identity whose checked BReg grant is used on the server." + "description": "Synthetic development identity whose checked BReg grant is used on the server. Use with `breg`, or use `actors` instead." + }, + "actors": { + "additionalProperties": { + "$ref": "#/$defs/ActorRoutes" + }, + "description": "One to eight synthetic identities, each served on its own loopback gateway origin over the same page, with the product paths it may reach. Use instead of `actor` and `breg`. Every actor needs a BReg grant, and a grant for each other product it reaches.", + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" }, "breg": { "$ref": "#/$defs/Routes", - "description": "BReg paths exposed to the page, grouped by method." + "description": "BReg paths exposed to the page of the single `actor`, grouped by method." }, "functions": { "description": "Declared functions to expose on the loopback preview origin.", @@ -440,13 +559,24 @@ } }, "required": [ - "actor", "page", - "breg", "functions" ], "type": "object" }, + "ProducerIssuerBinding": { + "additionalProperties": false, + "description": "The run issuer guards of a binding that rebinds a producer only, never an\ninitiator.", + "properties": { + "producer": { + "$ref": "#/$defs/RunProducer" + } + }, + "required": [ + "producer" + ], + "type": "object" + }, "Product": { "description": "A product the development run can start.", "enum": [ @@ -463,27 +593,53 @@ ], "type": "string" }, - "ProductPlan": { + "ProductReferences": { "additionalProperties": false, - "description": "One product to start and where its project lives.", + "minProperties": 1, "properties": { - "audience": { - "$ref": "#/$defs/ExternalId", - "description": "Token audience this product accepts: 1 to 256 characters without whitespace or control characters, distinct from the other products' audiences. BReg may instead equal `personAudience`." + "adapter": { + "$ref": "#/$defs/ProjectReference" + }, + "breg": { + "$ref": "#/$defs/NamedProjects" + }, + "casework": { + "$ref": "#/$defs/ProjectReference" }, - "product": { - "$ref": "#/$defs/Product", - "description": "Which product to start." + "coordinator": { + "$ref": "#/$defs/NamedProjects" }, - "project": { - "description": "Relative path from the plan's directory to the product project, or `.` for the plan's own directory. It must contain the product’s project manifest.", + "discovery": { + "$ref": "#/$defs/ProjectReference" + }, + "documents": { + "$ref": "#/$defs/ProjectReference" + }, + "evidence": { + "$ref": "#/$defs/NamedProjects" + }, + "messaging": { + "$ref": "#/$defs/ProjectReference" + }, + "render": { + "$ref": "#/$defs/ProjectReference" + }, + "scheduling": { + "$ref": "#/$defs/ProjectReference" + } + }, + "type": "object" + }, + "ProjectReference": { + "additionalProperties": false, + "properties": { + "path": { + "description": "Directory containing the product's native project file, relative to the file that declares it.", "type": "string" } }, "required": [ - "product", - "project", - "audience" + "path" ], "type": "object" }, @@ -706,34 +862,28 @@ }, "then": { "not": { - "required": [ - "application" + "anyOf": [ + { + "required": [ + "application" + ] + }, + { + "required": [ + "products" + ] + } ] }, "properties": { "issuer": { "const": "run" } - }, - "required": [ - "audiences" - ] + } } } ], "description": "The development plan: the products to start, the test people who call them, and the journeys to run.", - "oneOf": [ - { - "required": [ - "products" - ] - }, - { - "required": [ - "audiences" - ] - } - ], "properties": { "apiVersion": { "const": "id.registrystack.org/formats/rstack/dev/v1alpha1", @@ -748,7 +898,7 @@ "additionalProperties": { "$ref": "#/$defs/ExternalId" }, - "description": "Token audiences keyed by the product IDs declared in service.yaml.", + "description": "Token audiences keyed by project ID: the member name under projects, or the product kind for a single path.", "minProperties": 1, "propertyNames": { "$ref": "#/$defs/LocalId" @@ -768,6 +918,10 @@ "$ref": "#/$defs/Url", "description": "JWKS endpoint for an externally managed issuer. When set, the runner\ndelegates authentication to that issuer and does not mint person tokens." }, + "externalScheduling": { + "$ref": "#/$defs/ExternalScheduling", + "description": "One external task grant and its live status provider for a Scheduling fixture." + }, "issuer": { "anyOf": [ { @@ -811,11 +965,8 @@ "description": "Local browser preview for a composed service and one synthetic actor." }, "products": { - "description": "The products to start, each with its project directory and token audience. List each product at most once.", - "items": { - "$ref": "#/$defs/ProductPlan" - }, - "type": "array" + "$ref": "#/$defs/ProductReferences", + "description": "The products to start, as in service.yaml. Leave it out when a sibling service.yaml declares products." }, "schemaTestPeople": { "additionalProperties": { @@ -847,7 +998,8 @@ "kind", "issuer", "people", - "journeyFile" + "journeyFile", + "audiences" ], "title": "Registry Stack development plan", "type": "object" diff --git a/products/platform/generated/dev/service.v1alpha1.schema.json b/products/platform/generated/dev/service.v1alpha1.schema.json index 3d4879b18c..260d935d50 100644 --- a/products/platform/generated/dev/service.v1alpha1.schema.json +++ b/products/platform/generated/dev/service.v1alpha1.schema.json @@ -39,7 +39,7 @@ "additionalProperties": { "$ref": "#/$defs/ProjectReference" }, - "description": "Projects keyed by service product ID. BReg IDs form the generated client member names.", + "description": "Projects keyed by project ID. In a service, BReg IDs form the generated client member names.", "minProperties": 1, "propertyNames": { "$ref": "#/$defs/LocalId" @@ -56,6 +56,9 @@ "additionalProperties": false, "minProperties": 1, "properties": { + "adapter": { + "$ref": "#/$defs/ProjectReference" + }, "breg": { "$ref": "#/$defs/NamedProjects" }, @@ -65,11 +68,23 @@ "coordinator": { "$ref": "#/$defs/NamedProjects" }, + "discovery": { + "$ref": "#/$defs/ProjectReference" + }, + "documents": { + "$ref": "#/$defs/ProjectReference" + }, "evidence": { "$ref": "#/$defs/NamedProjects" }, "messaging": { "$ref": "#/$defs/ProjectReference" + }, + "render": { + "$ref": "#/$defs/ProjectReference" + }, + "scheduling": { + "$ref": "#/$defs/ProjectReference" } }, "type": "object" @@ -78,7 +93,7 @@ "additionalProperties": false, "properties": { "path": { - "description": "Directory containing the product's native project file, relative to this service file.", + "description": "Directory containing the product's native project file, relative to the file that declares it.", "type": "string" } }, diff --git a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json index 69fd075797..0d59c64a31 100644 --- a/products/platform/generated/mcp-runtime/mcp-runtime.schema.json +++ b/products/platform/generated/mcp-runtime/mcp-runtime.schema.json @@ -310,8 +310,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -836,6 +843,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/generated/runtime-config-blocks.schema.json b/products/platform/generated/runtime-config-blocks.schema.json index 2a274bd183..beb3dd8570 100644 --- a/products/platform/generated/runtime-config-blocks.schema.json +++ b/products/platform/generated/runtime-config-blocks.schema.json @@ -589,8 +589,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -972,6 +979,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ @@ -1014,6 +1027,58 @@ "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", "type": "string" }, + "StrictFileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider without the Compose mount policy.", + "properties": { + "root": { + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "StrictSecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/StrictFileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, "TaskGrantStatusConfig": { "additionalProperties": false, "description": "One task authority whose grants a runtime checks for fresh status, and the\nruntime's own credentials for that check, written as one entry of\n`taskGrantStatus`. The status route and scope default to Casework's.", diff --git a/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json b/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json new file mode 100644 index 0000000000..c43ded35a7 --- /dev/null +++ b/products/platform/generated/session-runtime/session-route-inventory.v1alpha1.schema.json @@ -0,0 +1,143 @@ +{ + "$defs": { + "Digest": { + "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "LocalId": { + "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", + "pattern": "^[a-z][a-z0-9_-]{0,63}$", + "type": "string" + }, + "ModuleProduct": { + "description": "Maintained products a module can declare, independent of the module's id.", + "enum": [ + "adapter", + "breg", + "casework", + "coordinator", + "documents", + "evidence", + "messaging", + "render", + "scheduling" + ], + "type": "string" + }, + "RewritePrefix": { + "maxLength": 256, + "minLength": 1, + "pattern": "^/(?!.*[%\\\\?#])[!-~]*$", + "type": "string" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/session-route-inventory/session-route-inventory.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Every configured module and page in a verified Envoy assembly, with one selected Base Registry Engine browser binding. Routes use the longest matching prefix at a path segment boundary.", + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/session-route-inventory/v1alpha1", + "type": "string" + }, + "gatewayDigest": { + "$ref": "#/$defs/Digest" + }, + "kind": { + "const": "PlatformSessionRouteInventory", + "type": "string" + }, + "modules": { + "items": { + "additionalProperties": false, + "properties": { + "id": { + "$ref": "#/$defs/LocalId" + }, + "prefix": { + "maxLength": 256, + "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$", + "type": "string" + }, + "prefixRewrite": { + "$ref": "#/$defs/RewritePrefix" + }, + "product": { + "$ref": "#/$defs/ModuleProduct" + }, + "signIns": { + "items": { + "$ref": "#/$defs/LocalId" + }, + "maxItems": 64, + "type": "array", + "uniqueItems": true + } + }, + "required": [ + "id", + "prefix", + "signIns" + ], + "type": "object" + }, + "maxItems": 64, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "pages": { + "items": { + "additionalProperties": false, + "properties": { + "prefix": { + "maxLength": 256, + "pattern": "^/(?:(?!\\.\\.?(?:/|$))[A-Za-z0-9._:~-]+(?:/|$))+$", + "type": "string" + }, + "signIn": { + "$ref": "#/$defs/LocalId" + } + }, + "required": [ + "prefix", + "signIn" + ], + "type": "object" + }, + "maxItems": 64, + "type": "array", + "uniqueItems": true + }, + "publicOrigin": { + "$ref": "#/$defs/Url", + "pattern": "^https://127(?:\\.[0-9]{1,3}){3}(?::[0-9]{1,5})?$" + }, + "selectedModule": { + "$ref": "#/$defs/LocalId" + }, + "signInDigest": { + "$ref": "#/$defs/Digest" + } + }, + "required": [ + "apiVersion", + "kind", + "publicOrigin", + "gatewayDigest", + "signInDigest", + "selectedModule", + "modules", + "pages" + ], + "title": "Checked Registry Session route inventory", + "type": "object" +} diff --git a/products/platform/generated/session-runtime/session-runtime.schema.json b/products/platform/generated/session-runtime/session-runtime.schema.json index dcf7cf8336..2b746747f8 100644 --- a/products/platform/generated/session-runtime/session-runtime.schema.json +++ b/products/platform/generated/session-runtime/session-runtime.schema.json @@ -145,8 +145,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -563,6 +570,12 @@ "pattern": "^[!#-\\[\\]-~]+$", "type": "string" }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index c5ec25dbc0..99ad1feebf 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -44,7 +44,7 @@ identity provider. | `rstack-dev.sh` | The `rstack dev` journey, with a recipe per product for the steps from `start` on. | | `own-provider.sh` | The own-provider journey: a stock Keycloak (`--issuer keycloak`) or pinned ThunderID (`--issuer thunderid`) plus a stock PostgreSQL started on loopback, then each product from its starter to authenticated calls and hooks. | | `lib-assists.sh` | The assists, sourced only when `--assist` names one: `sql` (provisioning statements through psql), `certificate` (a private CA and a TLS server certificate for the pg container), `token-type` (Keycloak's at+jwt header setting) and `mapper` (a hardcoded actor-kind claim mapper). The only journey file allowed to call psql, openssl or docker exec. Each use counts as a pass-rule violation. | -| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, paired with a kept Keycloak `own-provider.sh` run directory (`run.json` journey `own-provider` and `own-provider.json` issuer `keycloak`). Mismatched provider run directories (such as `--issuer thunderid`) are refused explicitly. It tries the files in place with no development declaration, compares startup and check diagnostics, and applies each remedy. Casework, Messaging, Scheduling, Documents, and Coordinator inputs that start successfully and pass the production check with zero diagnostics continue to a fresh production process and repeat the authenticated call. A product whose development cell did not finish stops at `input`. | +| `promote.sh` | The promote journey: `promote.sh --from RUN_DIR --bin-dir DIR`, paired with a kept Keycloak `own-provider.sh` run directory (`run.json` journey `own-provider` and `own-provider.json` issuer `keycloak`). Mismatched provider run directories (such as `--issuer thunderid`) are refused explicitly. It tries the files in place with no development declaration, compares startup and check diagnostics, and applies each remedy. Adapter, Casework, Messaging, Scheduling, Documents, Coordinator, and Render inputs that start successfully and pass the production check with zero diagnostics continue to a fresh production process and repeat the authenticated call. A product whose development cell did not finish stops at `input`. | | `keycloak/realm.json` | The realm the Keycloak own-provider journey imports: per product, one caller client with a service account and one API client for the product's audience. Documents also has a service-account client that exercises the human staff profile's refusal. The realm holds no protocol mappers. | | `projects/` | The runtime files and pure-data fixture helpers the own-provider journey uses (Render, Coordinator, loopback hook and source receivers, and the composed BReg + Casework + Scheduling fixture writer). | @@ -108,6 +108,32 @@ and grant exchange, commit a hold and an appointment, and verify a signed appointment hook correlated to that appointment. A skipped hook cannot satisfy the ThunderID cell. +Run the same composed check with a managed Scheduling runtime by passing +`--issuer thunderid --product scheduling --scheduling-runtime managed` to +`own-provider.sh`, using a prebuilt `rstack`, `schedulingctl`, and the composed +fixture tools. Use `expected-failures-thunderid.yaml` for the strict run. The +managed dev plan binds the named `task-agent` client to the exact Casework +assertion issuer and uses a separate status client to check live Casework +grant status. The journey checks the missing and wrong authority, an ordinary +bearer without a grant, and the signed hook for the confirmed appointment. +The generic `rstack-dev.sh` Scheduling smoke reports its hook as unexercised +without this composed fixture. + +## Adapter promotion + +The Adapter facade uses loopback PostgreSQL and a disposable Basic Auth source. +The harness keeps file-backed references in the development run for promotion. +`adapterctl provision` creates the database and roles. The runtime applies its +schema at startup, and `/ready` checks it. The standalone `database.connect` +step and the hook step are marked `unexercised`. The authenticated +`POST /v1/records/person` proves a write and leaves the first authenticated +read measurement empty. + +The development run stops the source after saving the HTTP 201 response. The +production run presents the same request and idempotency key with the source +stopped. It checks HTTP 201 and matches the response body against the saved +development response. + ## Reading the ratchet table A cell fails at its first failing step with one code. The code has one of these @@ -145,9 +171,44 @@ lists the outcome, verdict, and each counter's value, threshold, direction, and status. An unrecorded planted-error measurement is missing. A recorded zero is compared against the minimum. +T1 is captured at the first successful authenticated read. If the local +journey's first operation is a write, its authenticated readback can provide +T1. T2 is captured after the runner has verified the write across a restart +and checked delivery for paths that exercise a hook. The current local T2 +receipts cover BReg, Coordinator, Documents, and Messaging. + Threshold outcomes are report-only in CI. The functional ratchet controls journey acceptance, and comparison code errors fail the harness. Promote -uses its functional ratchet. +uses its functional ratchet. Its `productionRefusals` field counts distinct +codes matched by the initial production startup and check. It is `null` until +the comparison was measured, and `0` when the comparison found no refusals. +`total.refusalsMet` counts blocking or explicitly counted refusals across the +cell, including matched production refusals. An expected HTTP refusal that +satisfies a negative control stays in the step receipt as a passing assertion. + +The stock Keycloak BReg editor requests an optional client scope for the +fixture's static claims. Keycloak keeps the issued `scope` claim unchanged. +The no-mapper control obtains a fresh token for that same service account +without the optional scope and checks the refusal against the response's +trace ID. The foreign caller also gets a fresh token for its exact-record +assertion. + +The managed BReg launcher creates a separate rehearsal package root before `bregctl test`. +The own-provider runner uses the separate rehearsal package and database for both issuers. +Strict Keycloak run `20261201182016-4bf3` passed all ten steps with same-source binaries. +It verified the no-mapper claim refusal, signed delivery, exact editor read and foreign read +refusal. The paired strict promotion run `20261201182055-d29b` verified clean teardown. + +The BReg setup records `fixtureOnlyProducts: ["breg"]` in +`own-provider.json`. Promotion reports `journey.promote.no-input` for this +fixture. A passing BReg input directory that predates the marker is refused as +`legacy-unmarked`. A present marker with any other value is refused as +`invalid-fixture-marker`. These refusals happen before production startup. +An explicitly kept input is still taken over and cleaned up. + +In `rstack-dev`, the run log and `cells.tsv` mark the hook step `unexercised` +when the journey has no hook delivery to check. The cell still runs its later +steps, including retention and cleanup. ## Running the static check diff --git a/products/platform/journeys/concepts.yaml b/products/platform/journeys/concepts.yaml index c1f2249b5a..570f005e74 100644 --- a/products/platform/journeys/concepts.yaml +++ b/products/platform/journeys/concepts.yaml @@ -58,6 +58,8 @@ concepts: meaning: The run identifier and its time to live. - id: header-file meaning: The file that holds a ready authorisation header. + - id: idempotency-key + meaning: The key that identifies the original submission for a receipt read. - id: short-lived-token meaning: A token with a five minute lifetime. - id: runtime-file diff --git a/products/platform/journeys/expected-failures.yaml b/products/platform/journeys/expected-failures.yaml index 9c1984e4ed..753099fc0b 100644 --- a/products/platform/journeys/expected-failures.yaml +++ b/products/platform/journeys/expected-failures.yaml @@ -51,22 +51,6 @@ authenticationStages: [header, algorithm, token-type, key, signature, issuer, au changes: [posture, postgres-tls-requirement, rstack-dev-products, caller-contract] expectedFailures: - - journey: own-provider - product: breg - step: database.connect - code: product.breg.runtime.package-root-unavailable - removedBy: rstack-dev-products - basis: observed - observedOn: "journey run 20261128141250-8151" - reason: "prepare, issuer, and database.provision pass (bregctl provision accepts loopback-plaintext on the reader's plain PostgreSQL server). database.connect runs bregctl test to produce the receipt bregctl package requires, and bregctl test refuses because the package.root directory in runtime.yaml does not exist yet before bregctl package creates it." - - journey: own-provider - product: adapter - step: database.provision - code: product.config.refused - removedBy: rstack-dev-products - basis: observed - observedOn: "PR #2798, journey run 20261128120405-7e2e" - reason: "prepare and issuer pass (adapterctl check of the facade-recovery example with the breg-records profile). adapterctl provision (added in PR #2798) resolves database.migrationUrlRef from the runtime file's secret provider; runtime.example.yaml references secret:env/ADAPTER_DB_MIGRATION while own-provider writes secret files and leaves that environment variable unset, so provision refuses with config.refused." - journey: own-provider product: evidence step: issuer @@ -82,8 +66,8 @@ expectedFailures: code: journey.promote.no-input removedBy: rstack-dev-products basis: observed - observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" - reason: "The development journey did not finish for this product, so there are no files to promote." + observedOn: "v0.49.0 binaries, strict promote run 20261201173525-487a from own-provider run 20261201173442-23a5" + reason: "The stock Keycloak input is marked as a fixture for own-provider verification. Promotion refuses it at input before attempting to start production." - journey: promote product: evidence step: input @@ -92,22 +76,6 @@ expectedFailures: basis: observed observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" reason: "The development journey did not finish for this product, so there are no files to promote." - - journey: promote - product: adapter - step: input - code: journey.promote.no-input - removedBy: rstack-dev-products - basis: observed - observedOn: "origin/main cd83550e, journey run 20261127023442-18b4 against own-provider run 20261127021546-ddef" - reason: "The development journey did not finish for this product, so there are no files to promote." - - journey: promote - product: render - step: refusals - code: journey.promote.nothing-refused - removedBy: rstack-dev-products - basis: observed - observedOn: "PR #2798, promote run 20261128133333-b78e on own-provider run 20261128133312-c739" - reason: "Render passes own-provider with a runtime file that carries no development-only setting (loopback listener, loopback HTTP issuer, explicit allowedClients, no database), so registry-render check and serve accept it under the default production posture and refuse nothing." - journey: promote product: discovery step: input @@ -253,6 +221,22 @@ unreached: # observedOn: "origin/main cd83550e, promote run 20261127025000-816f on own-provider run 20261127024425-265d (assisted: sql, certificate, token-type, mapper)" # reason: "The assisted Scheduling cell reached T1. Started with no development declaration, schedulingctl check (which has no --production flag) lists no refusal and the server starts and answers /readyz, so zero refusals are listed. No shared posture exists on main, so nothing can refuse. The count becomes meaningful once the posture change lands." passes: + - journey: own-provider + product: breg + basis: observed + observedOn: "same-source binaries, strict Keycloak own-provider run 20261201182016-4bf3" + - journey: own-provider + product: adapter + basis: observed + observedOn: "v0.49.0 binaries, own-provider run 20261201143319-b2e1" + - journey: promote + product: adapter + basis: observed + observedOn: "v0.49.0 binaries, promote run 20261201143356-36b6" + - journey: promote + product: render + basis: observed + observedOn: "v0.49.0 binaries, promote run 20261201091716-e777" - journey: own-provider product: casework basis: observed diff --git a/products/platform/journeys/keycloak/realm.json b/products/platform/journeys/keycloak/realm.json index 32ea513be3..8e516a6e67 100644 --- a/products/platform/journeys/keycloak/realm.json +++ b/products/platform/journeys/keycloak/realm.json @@ -23,6 +23,9 @@ {"clientId": "directory-client", "name": "BReg caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, "secret": "${JOURNEY_CLIENT_SECRET_BREG}", "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, + {"clientId": "foreign-directory-client", "name": "BReg outside-jurisdiction caller", "enabled": true, "protocol": "openid-connect", "publicClient": false, + "secret": "${JOURNEY_CLIENT_SECRET_BREG_FOREIGN}", "standardFlowEnabled": false, "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, "serviceAccountsEnabled": true}, {"clientId": "urn:example:casework", "name": "Casework API", "enabled": true, "protocol": "openid-connect", "publicClient": false, "standardFlowEnabled": false, "implicitFlowEnabled": false, "directAccessGrantsEnabled": false, "serviceAccountsEnabled": false}, @@ -78,6 +81,8 @@ "users": [ {"username": "service-account-directory-client", "enabled": true, "serviceAccountClientId": "directory-client", "clientRoles": {"urn:breg:local-directory": ["access"]}}, + {"username": "service-account-foreign-directory-client", "enabled": true, "serviceAccountClientId": "foreign-directory-client", + "clientRoles": {"urn:breg:local-directory": ["access"]}}, {"username": "service-account-casework-client", "enabled": true, "serviceAccountClientId": "casework-client", "clientRoles": {"urn:example:casework": ["access"]}}, {"username": "service-account-case-system", "enabled": true, "serviceAccountClientId": "case-system", diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index d3a7d21a14..bc226f9649 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -1552,6 +1552,7 @@ journey_cell_begin() { _jc_idp=0 _jc_certs=0 _jc_refusals=0 + _jc_production_refusals=null _jc_named=null _jc_assist_count=0 _jc_seconds=0.000 @@ -1771,6 +1772,74 @@ journey_request_contract() { done } +# assert_signed_hook_acceptance LOG_FILE EXPECTED_PATH EXPECTED_TYPE: verify +# the hook receiver logged one value-free acceptance record proving Standard +# Webhooks HMAC-SHA256 receiver authority without inbound credential headers. +assert_signed_hook_acceptance() { + local log_file=$1 expected_path=$2 expected_type=$3 + # shellcheck disable=SC2016 # jq binds its own variables + jq -e -s --arg path "$expected_path" --arg type "$expected_type" ' + length == 1 + and (.[0] | + .event == "signed-hook-accepted" + and .path == $path + and .eventType == $type + and .signatureVerified == true + and .receiverAuthority == "standard-webhooks-hmac-sha256" + and .inboundCredentialHeaders == false + and (.headerNames | type == "array") + and (.headerNames | index("webhook-signature") != null) + and (.headerNames | index("authorization") == null) + and (.headerNames | index("registry-source-authorization") == null) + and (.headerNames | index("proxy-authorization") == null) + and (.headerNames | index("cookie") == null) + ) + ' "$log_file" >/dev/null +} + +# The managed sink authenticates the delivery. Correlate its captured envelope +# and signing headers to the operation, without accepting forwarded credentials. +signed_hook_matches() { + local expected=$1 + shift + jq -e --argjson expected "$expected" 'any(.[]; + . as $capture | (.body | fromjson?) as $event | + $event.type == $expected.type and $event.data == $expected.data and + ($expected.source == null or $event.source == $expected.source) and + ($event.id | type == "string" and length > 0) and + any($capture.headers[]; .name == "webhook-id" and .value == $event.id) and + any($capture.headers[]; .name == "webhook-timestamp" and (.value | test("^[0-9]+$"))) and + any($capture.headers[]; .name == "webhook-signature" and (.value | startswith("v1,"))) and + all($capture.headers[]; .name != "authorization" and .name != "cookie" and + .name != "registry-source-authorization" and .name != "proxy-authorization"))' "$@" >/dev/null +} + +signed_hook_received() { + curl --silent --fail --max-time 3 "$1" | signed_hook_matches "$2" +} + +# Confirm one Scheduling appointment with the caller's already admitted task +# grant. The caller supplies the hold request and chooses how to observe the +# resulting delivery. The grant reaches HTTP by variable name. +journey_scheduling_appointment() { + local origin=$1 work=$2 request=$3 bearer=$4 appointment_var=$5 + local _js_hold='' confirm=$work/appt-request.json + journey_http hook --expect-status 201 --bearer "$bearer" \ + --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-comp-hold-create' \ + --data-file "$request" --capture .holdId _js_hold \ + POST "$origin/v1/holds" || + journey_harness_failure "Scheduling hold creation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" + jq -cn --arg hold "$_js_hold" '{hold:$hold,admission:null}' >"$confirm" || + journey_harness_failure "cannot assemble the Scheduling confirmation request" + journey_http hook --expect-status 201 --bearer "$bearer" \ + --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-comp-appt-confirm' \ + --data-file "$confirm" --capture .appointmentId "$appointment_var" \ + POST "$origin/v1/appointments" || + journey_harness_failure "Scheduling appointment confirmation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" +} + # journey_http STEP [--bearer VAR] [--header 'Name: value']... [--form K=V]... # [--form-secret K=SECRET]... [--data-file FILE] [--cookie-jar NAME] # [--location] [--expect-status NNN] [--capture FILTER VAR]... [--capture-secret FILTER VAR]... @@ -2295,6 +2364,17 @@ journey_unreached() { _jc_reason=$reason } +# journey_unexercised STEP: record an optional step and continue the cell. +journey_unexercised() { + local step=${1:-} + journey__require_step_start "$step" + [[ "$step" != "$_journey_last_step" ]] || + journey__script_error "the final step of $_jc_product cannot be marked unexercised" + journey__record_line "$step" unexercised - 0.000 + _jc_recorded+="$step"$'\n' + journey__say "$_jc_product $step: unexercised" +} + # journey_assist_enabled NAME: true when --assist lists NAME. journey_assist_enabled() { [[ ",$JOURNEY_ASSISTS," == *",${1:-},"* ]] @@ -2342,7 +2422,9 @@ journey_blocker() { # journey_count COUNTER [N]: add N (default 1) to a counted quantity the # library cannot see: identity-provider-changes, certificates, -# documentation-words, refusals or errors-that-say-what-to-change. +# documentation-words, refusals or errors-that-say-what-to-change. The +# production-refusals counter records the initial comparison once and adds +# its measured count to the total refusals. journey_count() { local counter=${1:-} amount=${2:-1} journey__require_cell @@ -2352,6 +2434,12 @@ journey_count() { certificates) _jc_certs=$((_jc_certs + amount)) ;; documentation-words) _jc_doc_words=$((_jc_doc_words + amount)) ;; refusals) _jc_refusals=$((_jc_refusals + amount)) ;; + production-refusals) + [[ "$JOURNEY_NAME" == promote && "$_jc_production_refusals" == null ]] || + journey__script_error "production refusals are recorded once per promote cell" + _jc_production_refusals=$amount + _jc_refusals=$((_jc_refusals + amount)) + ;; errors-that-say-what-to-change) [[ "$_jc_named" != null ]] || _jc_named=0 _jc_named=$((_jc_named + amount)) @@ -2428,6 +2516,7 @@ journey_cell_end() { --arg product "$_jc_product" --arg outcome "$outcome" \ --arg step "${_jc_fail_step:-$_jc_unreached}" --arg code "$_jc_fail_code" --arg reason "$_jc_reason" \ --argjson blockers "$_jc_blockers_json" --argjson t1 "$_jc_t1_json" --argjson t2 "$_jc_t2_json" \ + --arg journey "$JOURNEY_NAME" --argjson productionRefusals "$_jc_production_refusals" \ --argjson total "$total" \ 'def opt: if . == "" then null else . end; { @@ -2444,7 +2533,8 @@ journey_cell_end() { "machine-time-to-t1": (if $t1 == null then null else ($t1.machineSeconds / 60) end), "errors-that-say-what-to-change": $total.errorsThatSayWhatToChange } - }' >"$JOURNEY_OUT/$_jc_product/cell.json" || journey_harness_failure "cannot write the cell of $_jc_product" + } + (if $journey == "promote" then {$productionRefusals} else {} end)' \ + >"$JOURNEY_OUT/$_jc_product/cell.json" || journey_harness_failure "cannot write the cell of $_jc_product" if journey__first_hour_column "$JOURNEY_NAME" >/dev/null; then public="$JOURNEY_OUT/public-cell-receipts/$_jc_product" receipt="$(journey__first_hour_receipt "$JOURNEY_NAME" "$JOURNEY_OUT/$_jc_product/cell.json")" || @@ -2540,8 +2630,7 @@ journey__cleanup_problem() { _journey_cleanup_failures+="$*"$'\n' } -journey__stop_processes() { - local index pid failed=0 +journey__stop_foreground() { if [[ -n "$_journey_watchdog_pid" ]]; then journey__end_watchdog "$_journey_watchdog_pid" _journey_watchdog_pid='' @@ -2550,6 +2639,10 @@ journey__stop_processes() { journey__terminate "$_journey_foreground_pid" "$JOURNEY_KILL_GRACE" _journey_foreground_pid='' fi +} + +journey__stop_processes() { + local index pid failed=0 for ((index = 0; index < ${#_journey_process_pids[@]}; index++)); do pid=${_journey_process_pids[$index]} [[ -n "$pid" ]] || continue @@ -2696,6 +2789,8 @@ journey__dispose_secrets() { journey__cleanup() { local index failed=0 + # A cancelled step can still be writing the state inspected by its cleanup hook. + journey__stop_foreground for ((index = ${#_journey_cleanup_hooks[@]} - 1; index >= 0; index--)); do if ! "${_journey_cleanup_hooks[$index]}"; then journey__cleanup_problem "cleanup hook ${_journey_cleanup_hooks[$index]} failed" diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 73d24db5bf..b78bda8c99 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -28,6 +28,9 @@ # through the admin API at setup and made a default scope of its caller. Each # product counts three identity-provider changes: its caller client, its # audience and its scope. +# BReg's disposable fixture binds exact scopes to two callers and sets its +# authored principal, purpose and jurisdiction with built-in static mappers. +# An editor token issued without the optional mapper scope must be refused. # # What the harness does that the reader does not type, and so is not counted: # - the secret folder of every product is the run's secrets/ folder, so each @@ -111,7 +114,8 @@ select_journey_init_args() { INIT_JOURNEY_NAME=own-provider INIT_DEFAULT_EXPECTED=$JOURNEY_LIB_DIR/expected-failures.yaml select_journey_init_args "$@" -journey_init "$INIT_JOURNEY_NAME" --default-expected "$INIT_DEFAULT_EXPECTED" --value-option issuer -- "$@" +journey_init "$INIT_JOURNEY_NAME" --default-expected "$INIT_DEFAULT_EXPECTED" \ + --value-option issuer --value-option scheduling-runtime -- "$@" REALM=registry-journey POSTGRES_IMAGE=postgres:18.7@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc @@ -138,6 +142,17 @@ keycloak | thunderid) ;; ;; esac +journey_option_value scheduling-runtime SCHEDULING_RUNTIME +SCHEDULING_RUNTIME=${SCHEDULING_RUNTIME:-standalone} +case "$SCHEDULING_RUNTIME" in +standalone) ;; +managed) + [[ "$ISSUER_KIND" == thunderid && $JOURNEY_KEEP -eq 0 && "${JOURNEY_PRODUCTS[*]}" == scheduling ]] || + journey_usage_error "--scheduling-runtime managed requires --issuer thunderid --product scheduling and no --keep" + ;; +*) journey_usage_error "--scheduling-runtime $SCHEDULING_RUNTIME: choose standalone or managed" ;; +esac + KEYCLOAK_IMAGE='' THUNDERID_IMAGE='' JOURNEY_ISSUER_BIN='' @@ -403,6 +418,75 @@ stop_thunderid_sessions() { } journey_at_cleanup stop_thunderid_sessions +COMPOSED_MANAGED_RUN='' +COMPOSED_MANAGED_ROOT=$SECRETS/scheduling-managed + +stop_composed_managed_scheduling() { + local state=$COMPOSED_MANAGED_ROOT/state run_id=$COMPOSED_MANAGED_RUN run + [[ ! -L "$COMPOSED_MANAGED_ROOT" && ! -L "$state" ]] || return 1 + if [[ -z "$run_id" ]]; then + # A launcher can create state before its startup report returns. + # This private directory belongs to this fixture alone. + for run in "$state/"*; do + [[ "${run##*/}" =~ ^[0-9a-f]{32}$ ]] || continue + [[ -d "$run" && ! -L "$run" && -z "$run_id" ]] || return 1 + run_id=${run##*/} + done + fi + [[ -n "$run_id" ]] || return 0 + run=$state/$run_id + if [[ -L "$run" ]] || + ! RSTACK_DEV_STATE_DIR="$state" RSTACK_SCHEDULING_BIN="$SERVER_BIN" RSTACK_SCHEDULINGCTL_BIN="$TOOL_BIN" \ + "$COMPOSED_RSTACK_BIN" --install-root "$COMPOSED_MANAGED_ROOT/install" --format json dev stop "$run_id" >/dev/null || + [[ -e "$run" || -L "$run" ]]; then + printf 'Managed Scheduling did not stop. Recovery state retained at %s.\n' "$run" >&2 + return 1 + fi + COMPOSED_MANAGED_RUN='' +} + +cleanup_composed_managed_scheduling() { + if ! stop_composed_managed_scheduling; then + journey__cleanup_problem "managed Scheduling recovery state retained at $COMPOSED_MANAGED_ROOT" + return 1 + fi + [[ ! -d "$COMPOSED_MANAGED_ROOT" ]] || + python3 -c 'import shutil, sys; shutil.rmtree(sys.argv[1])' "$COMPOSED_MANAGED_ROOT" +} +journey_at_cleanup cleanup_composed_managed_scheduling + +start_composed_managed_scheduling() { + local _cms_project=$1 _cms_report=$2 _cms_url='' + # rstack start can spend up to 60 seconds stopping its supervisor after TERM. + local JOURNEY_KILL_GRACE=$((JOURNEY_KILL_GRACE < 65 ? 65 : JOURNEY_KILL_GRACE)) + IFS= read -r _cms_url <"$ADMIN_URL_FILE" || [[ -n "$_cms_url" ]] || + journey_harness_failure "cannot read the disposable PostgreSQL admin URL" + # env execs rstack in the same PID watched by journey_step. + RSTACK_DEV_DATABASE_URL="$_cms_url?sslmode=disable" RSTACK_DEV_STATE_DIR="$COMPOSED_MANAGED_ROOT/state" \ + RSTACK_SCHEDULING_BIN="$SERVER_BIN" RSTACK_SCHEDULINGCTL_BIN="$TOOL_BIN" \ + journey_step hook --timeout 120 --typed "rstack dev start $_cms_project" -- \ + env -u RSTACK_DEV_DATABASE_CA "$COMPOSED_RSTACK_BIN" --install-root "$COMPOSED_MANAGED_ROOT/install" \ + --format json dev start "$_cms_project" || + journey_harness_failure "managed Scheduling did not start; see $JOURNEY_STEP_STDERR" + COMPOSED_MANAGED_RUN=$(jq -er '.run_id | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || + journey_harness_failure "managed Scheduling start report has no run ID" + copy_file "$JOURNEY_STEP_STDOUT" "$_cms_report" +} + +composed_scheduling_url() { + jq -er '.products.scheduling | select(test("^http://127[.]0[.]0[.]1:[0-9]+$"))' "$1" +} + +assert_composed_scheduling_authority_refused() { + local origin=$1 request=$2 key=$3 + journey_http hook --expect-status 401 --bearer exchanged_token \ + --header 'Content-Type: application/json' --header "Idempotency-Key: $key" \ + --data-file "$request" POST "$origin/v1/holds" || + journey_harness_failure "managed Scheduling did not refuse the exchanged bearer with HTTP 401" + jq -e '.code == "authentication.refused" and .failedCheck == "token-assertion-issuer"' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "managed Scheduling did not refuse at token-assertion-issuer" +} + # read_secret NAME VAR: the value of a generated secret into VAR. read_secret() { local _kc_path @@ -434,6 +518,10 @@ CASEWORK_SUBJECT='' DOCUMENTS_SUBJECT='' COORDINATOR_SUBJECT='' BREG_HOOK_PORT='' +BREG_SCOPE_UNLINKS=0 +BREG_KEYCLOAK_CLAIM_SCOPE='breg-fixture-claims' +BREG_EDITOR_SUBJECT='' +BREG_FOREIGN_SUBJECT='' ADAPTER_SOURCE_PORT='' REACHED_AUTH_PRODUCTS=() THUNDERID_SESSION_IDS=() @@ -506,6 +594,65 @@ keycloak_default_scope() { journey_harness_failure "Keycloak refused to add scope $scope to client $client (HTTP $KC_STATUS)" } +# Keep the built-in scopes that do not appear in the access token's scope +# claim. The BReg schema test compares the caller's entire issued scope set. +breg_keycloak_exact_scope() { + local client=$1 uuid defaults scopes scope_id + keycloak_client_uuid "$client" uuid + keycloak_admin GET "/clients/$uuid/default-client-scopes" + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot list the default scopes of $client" + defaults=$KC_BODY + # Keycloak omits attributes from the per-client scope listing. + keycloak_admin GET /client-scopes + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot read scope attributes" + scopes=$(jq -r --argjson defaults "$defaults" --arg scope "$SCOPE" ' + .[] | .id as $id | select(any($defaults[]; .id == $id)) + | select(.name != $scope and .attributes["include.in.token.scope"] != "false") | .id' <<<"$KC_BODY") || + journey_harness_failure "Keycloak returned an invalid default scope inventory" + while IFS= read -r scope_id; do + [[ -n "$scope_id" ]] || continue + keycloak_admin DELETE "/clients/$uuid/default-client-scopes/$scope_id" + [[ "$KC_STATUS" == 204 ]] || journey_harness_failure "Keycloak refused to unlink a default scope from $client" + BREG_SCOPE_UNLINKS=$((BREG_SCOPE_UNLINKS + 1)) + done <<<"$scopes" +} + +breg_keycloak_mappers() { + jq -cn --arg principal "$1" --arg jurisdiction "$2" ' + {registry_principal: $principal, registry_purpose: "directory-administration", jurisdiction: $jurisdiction} + | to_entries | map({name: .key, protocol: "openid-connect", protocolMapper: "oidc-hardcoded-claim-mapper", + config: {"claim.name": .key, "claim.value": .value, "jsonType.label": "String", "access.token.claim": "true", + "id.token.claim": "false", "userinfo.token.claim": "false", "introspection.token.claim": "false"}})' +} + +breg_keycloak_add_mappers() { + local uuid mappers mapper + keycloak_client_uuid "$1" uuid + mappers=$(breg_keycloak_mappers "$2" "$3" | jq -c '.[]') || journey_harness_failure "cannot assemble BReg's static mappers" + while IFS= read -r mapper; do + keycloak_admin POST "/clients/$uuid/protocol-mappers/models" "$mapper" + [[ "$KC_STATUS" == 201 ]] || journey_harness_failure "Keycloak refused a static BReg mapper (HTTP $KC_STATUS)" + done <<<"$mappers" +} + +# Keep the editor's static mappers on its own optional client scope. Keycloak +# can then issue a fresh unmapped token to the same client and service account. +breg_keycloak_editor_scope() { + local uuid scope_id body + body=$(breg_keycloak_mappers synthetic-directory-editor zone-a | jq -c --arg name "$BREG_KEYCLOAK_CLAIM_SCOPE" ' + {name: $name, protocol: "openid-connect", attributes: {"include.in.token.scope": "false"}, protocolMappers: .}') || + journey_harness_failure "cannot assemble the BReg editor's optional claim scope" + keycloak_admin POST /client-scopes "$body" + [[ "$KC_STATUS" == 201 ]] || journey_harness_failure "Keycloak refused the BReg editor's claim scope (HTTP $KC_STATUS)" + keycloak_admin GET /client-scopes + [[ "$KC_STATUS" == 200 ]] || journey_harness_failure "Keycloak cannot list its client scopes" + scope_id=$(jq -er --arg name "$BREG_KEYCLOAK_CLAIM_SCOPE" '.[] | select(.name == $name) | .id' <<<"$KC_BODY") || + journey_harness_failure "Keycloak did not list the BReg editor's claim scope" + keycloak_client_uuid "$CLIENT" uuid + keycloak_admin PUT "/clients/$uuid/optional-client-scopes/$scope_id" + [[ "$KC_STATUS" == 204 ]] || journey_harness_failure "Keycloak refused to bind the editor's optional scope (HTTP $KC_STATUS)" +} + # keycloak_service_account_subject CLIENT_ID VAR: the `sub` of the client's # service account, which a Coordinator policy names. keycloak_service_account_subject() { @@ -529,6 +676,8 @@ start_keycloak() { done journey_secret_new client-documents-wrong-kind 24 secret_envs+=(--secret-env JOURNEY_CLIENT_SECRET_DOCUMENTS_WRONG_KIND=client-documents-wrong-kind) + journey_secret_new client-breg-foreign 24 + secret_envs+=(--secret-env JOURNEY_CLIENT_SECRET_BREG_FOREIGN=client-breg-foreign) journey_container_run kc --port 8080 \ --env=KC_BOOTSTRAP_ADMIN_USERNAME=admin \ --secret-env KC_BOOTSTRAP_ADMIN_PASSWORD=keycloak-admin "${secret_envs[@]}" \ @@ -885,12 +1034,12 @@ recipe() { CALL_PATH=/v1/workflows/coordinator ;; adapter) + TOOL=adapterctl CLIENT=registry-adapter-example-client + CALL_METHOD=POST CALL_PATH=/v1/records/person if [[ "$ISSUER_KIND" == thunderid ]]; then - TOOL=adapterctl CLIENT=registry-adapter-example-client AUDIENCE=urn:example:adapter SCOPE=records:write - CALL_METHOD=POST CALL_PATH=/v1/records/person + AUDIENCE=urn:example:adapter SCOPE=records:write else - TOOL=adapterctl CLIENT=registry-adapter-example-client AUDIENCE=registry-adapter-example SCOPE=records.write - CALL_PATH=/v1/records/person + AUDIENCE=registry-adapter-example SCOPE=records.write fi ;; evidence) @@ -1003,6 +1152,16 @@ unrecognized_subcommand() { # --------------------------------------------------------------------------- # The steps +# Bind the standalone producer to the issuer and subject this run provisions. +bind_casework_producer() { + local path=$1 issuer=$2 subject=$3 starter_issuer=https://identity.casework.example.test + if ! grep -Fxq " issuer: $starter_issuer" "$path"; then + starter_issuer=http://127.0.0.1:8093 + fi + edit "$path" " issuer: $starter_issuer" " issuer: $issuer" issuer-url + edit "$path" " subject: b75315b2-5854-70f3-8867-511dd771a6da" " subject: $subject" +} + # prepare: the product's starter, its package and its runtime file, with the # paths and ports of this machine. step_prepare() { @@ -1019,20 +1178,17 @@ step_prepare() { edit "$RUNTIME_FILE" " root: /var/lib/breg/secrets" " root: $SECRETS" secret-file edit "$RUNTIME_FILE" " root: /var/lib/breg/package" " root: $WORK/build/package" package edit "$RUNTIME_FILE" " path: /var/log/breg/audit.jsonl" " path: $WORK/audit.jsonl" - if [[ "$ISSUER_KIND" == thunderid ]]; then - free_port BREG_HOOK_PORT - local hook_decl hook_dest - hook_decl=$(printf ' hooks:\n - id: contact-created\n phase: after\n trigger: created\n projection: [name, email, jurisdiction]\n handler: {type: url, destinationId: contact-sink}') - edit "$PROJECT/registry.yaml" $'\nactions:\n' $'\n'"$hook_decl"$'\n\nactions:\n' - hook_dest=$(printf 'destinations:\n hooks:\n contact-sink:\n origin: http://127.0.0.1:%s\n path: /events\n networkProfile: loopback-http\n dnsFamily: dual-stack-strict\n allowedPrivateCidrs: []\n hmacSha256KeyRef: secret:file/contact-sink-hmac\n classificationCeiling: internal\n deliveryCeilings:\n attemptTimeoutMilliseconds: 2000\n maximumAttempts: 5\n' "$BREG_HOOK_PORT") - printf '\n%s' "$hook_dest" >>"$RUNTIME_FILE" - fi + free_port BREG_HOOK_PORT + local hook_decl hook_dest + hook_decl=$(printf ' hooks:\n - id: contact-created\n phase: after\n trigger: created\n projection: [name, email, jurisdiction]\n handler: {type: url, destinationId: contact-sink}') + edit "$PROJECT/registry.yaml" $'\nactions:\n' $'\n'"$hook_decl"$'\n\nactions:\n' + hook_dest=$(printf 'destinations:\n hooks:\n contact-sink:\n origin: http://127.0.0.1:%s\n path: /events\n networkProfile: loopback-http\n dnsFamily: dual-stack-strict\n allowedPrivateCidrs: []\n hmacSha256KeyRef: secret:file/contact-sink-hmac\n classificationCeiling: internal\n deliveryCeilings:\n attemptTimeoutMilliseconds: 2000\n maximumAttempts: 5\n' "$BREG_HOOK_PORT") + printf '\n%s' "$hook_dest" >>"$RUNTIME_FILE" ;; casework) reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" [[ $CELL_OVER -eq 0 ]] || return 0 - edit "$PROJECT/casework.yaml" " issuer: http://127.0.0.1:8093" " issuer: $ACTIVE_ISSUER" issuer-url - edit "$PROJECT/casework.yaml" " subject: b75315b2-5854-70f3-8867-511dd771a6da" " subject: $CASEWORK_SUBJECT" + bind_casework_producer "$PROJECT/casework.yaml" "$ACTIVE_ISSUER" "$CASEWORK_SUBJECT" reader_command prepare --concepts package -- "$TOOL_BIN" package --output "$PROJECT/.casework/package" "$PROJECT" [[ $CELL_OVER -eq 0 ]] || return 0 RUNTIME_FILE=$PROJECT/runtime.yaml @@ -1121,12 +1277,17 @@ step_prepare() { copy_file "$PROJECT/runtime.example.yaml" "$RUNTIME_FILE" [[ $CELL_OVER -eq 0 ]] || return 0 edit "$RUNTIME_FILE" " bind: 127.0.0.1:8080" " bind: 127.0.0.1:$PORT" listener-bind + free_port ADAPTER_SOURCE_PORT + edit "$RUNTIME_FILE" " baseUrl: https://reference.example.invalid" " baseUrl: http://127.0.0.1:$ADAPTER_SOURCE_PORT" if [[ "$ISSUER_KIND" == thunderid ]]; then - free_port ADAPTER_SOURCE_PORT edit "$PROJECT/project.yaml" " scopes: [records.write]" " scopes: [records:write]" scopes - edit "$RUNTIME_FILE" " baseUrl: https://reference.example.invalid" " baseUrl: http://127.0.0.1:$ADAPTER_SOURCE_PORT" edit "$RUNTIME_FILE" " audience: registry-adapter-example" " audience: $AUDIENCE" audience fi + harness_edit "$RUNTIME_FILE" $'\nendpoints:\n' $'\nsecretProviders:\n file:\n root: '"$SECRETS"$'\nendpoints:\n' + harness_edit "$RUNTIME_FILE" secret:env/REFERENCE_USERNAME secret:file/reference-username + harness_edit "$RUNTIME_FILE" secret:env/REFERENCE_PASSWORD secret:file/reference-password + harness_edit "$RUNTIME_FILE" secret:env/ADAPTER_DB_RUNTIME secret:file/runtime-database-url + harness_edit "$RUNTIME_FILE" secret:env/ADAPTER_DB_MIGRATION secret:file/migration-database-url ;; evidence) PRODUCT_KEY_DIRS+=("$PROJECT/.generated/secrets") @@ -1281,9 +1442,10 @@ step_issuer() { case "$product" in breg) edit "$RUNTIME_FILE" " allowedAlgorithm: EdDSA" " allowedAlgorithm: RS256" - if [[ "$ISSUER_KIND" == thunderid ]]; then - edit "$RUNTIME_FILE" " allowedClients: [directory-client]" \ - " allowedClients: [directory-client, foreign-directory-client]" + edit "$RUNTIME_FILE" " allowedClients: [directory-client]" \ + " allowedClients: [directory-client, foreign-directory-client]" + if [[ "$ISSUER_KIND" == keycloak ]]; then + journey_count identity-provider-changes "$((10 + BREG_SCOPE_UNLINKS))" fi reader_command issuer -- "$TOOL_BIN" --format json check "$PROJECT" --runtime-config "$RUNTIME_FILE" ;; @@ -1302,6 +1464,8 @@ step_issuer() { --pack "$PROJECT/pack.yaml" --runtime "$RUNTIME_FILE" ;; evidence) + # The check and package commands resolve their matching runtime as a child. + local -x EVIDENCE_BIN="$SERVER_BIN" if [[ "$ISSUER_KIND" == thunderid ]]; then edit "$RUNTIME_FILE" " uri: http://127.0.0.1:8081/oauth2/jwks" \ " uri: $TID_ISSUER/oauth2/jwks" jwks-uri @@ -1314,7 +1478,7 @@ step_issuer() { reader_command issuer -- "$TOOL_BIN" check "$PROJECT" --target "$RUNTIME_FILE" --posture development --format json [[ $CELL_OVER -eq 0 ]] || return 0 local candidate=$WORK/candidate installed=$WORK/installed-package - reader_command issuer -- env EVIDENCE_BIN="$SERVER_BIN" "$TOOL_BIN" package "$PROJECT" \ + reader_command issuer -- "$TOOL_BIN" package "$PROJECT" \ --target "$RUNTIME_FILE" --output "$candidate" --posture development --format json [[ $CELL_OVER -eq 0 ]] || return 0 SEALED_DIRS+=("$candidate") @@ -1396,88 +1560,90 @@ write_product_secrets() { fi journey_secret_new "$name" "$bytes" done < <(secret_references "$RUNTIME_FILE") - if [[ "$ISSUER_KIND" == thunderid && "$product" == adapter ]]; then - journey_secret_new adapter-reference-username 16 - journey_secret_new adapter-reference-password 24 - fi } -# breg_schema_test_credentials: acquire real client tokens for BReg's schema -# rehearsal and write a schema-test credential binding document covering every -# step of tests/journeys.yaml. +# Get a client-credentials token into the caller's variable. Keep the token +# response and the client secret out of the step output. +breg_keycloak_token() { + local client=$1 ref=$2 variable=$3 claims_scope=${4:-} secret_file response issued + local -a options=() + [[ -z "$claims_scope" ]] || options=(--data-urlencode "scope=$claims_scope") + journey_secret_path "$ref" secret_file + response=$(curl --silent --show-error --fail --max-time 30 \ + --data grant_type=client_credentials --data "client_id=$client" \ + --data-urlencode "client_secret@$secret_file" "${options[@]}" "$KC_ISSUER/protocol/openid-connect/token") || + journey_harness_failure "Keycloak refused the BReg client credentials of $client" + issued=$(jq -er '.access_token | strings | select(length > 0)' <<<"$response") || + journey_harness_failure "Keycloak returned no BReg access token for $client" + printf -v "$variable" '%s' "$issued" + local label=${variable,,} + journey_secret_register "$ref-token-${label//_/-}" "$variable" +} + +# Check issuer-provided identity and the exact scope before BReg sees a token. +# An empty principal represents an editor token issued without the mapper scope. +breg_keycloak_token_matches() { + local variable=$1 client=$2 subject=$3 principal=$4 jurisdiction=$5 + printf '%s' "${!variable}" | perl -MMIME::Base64 -e ' + local $/; my $token = ; + my $payload = (split /\./, $token)[1] // ""; + $payload =~ tr{-_}{+/}; + $payload .= "=" x ((4 - length($payload) % 4) % 4); + print decode_base64($payload);' | + jq -e --arg issuer "$KC_ISSUER" --arg client "$client" --arg subject "$subject" \ + --arg audience "$AUDIENCE" --arg scope "$SCOPE" --arg principal "$principal" --arg zone "$jurisdiction" ' + {issuer: (.iss == $issuer), client: (.azp == $client), subject: (.sub == $subject), + audience: (([.aud] | flatten | index($audience)) != null), scope: (.scope == $scope), + profile: (if $principal == "" then + (has("registry_principal") or has("registry_purpose") or has("jurisdiction") | not) + else + .registry_principal == $principal and .registry_purpose == "directory-administration" and .jurisdiction == $zone + end)} as $checks + | ($checks | to_entries | map(select(.value | not) | .key)) as $mismatches + | if ($mismatches | length) == 0 then true else + "Unexpected Keycloak token fields: \($mismatches | join(", ")); issued scope: \(.scope // "")\n" | halt_error(1) + end' >/dev/null +} + +# Acquire exact credentials for every step in the unmodified BReg fixture suite. breg_schema_test_credentials() { - local credentials_file=$1 secret_file response token + local credentials_file=$1 + # shellcheck disable=SC2034 # Read by name through token fetch and secret helpers. + local breg_schema_token='' breg_foreign_schema_token='' if [[ "$ISSUER_KIND" == thunderid ]]; then - # shellcheck disable=SC2034 # read by name in write_own_secret and thunderid_fetch_token - local breg_schema_token='' breg_foreign_schema_token='' thunderid_fetch_token "$TID_ROOT" "$TID_REGISTRATION" "$CLIENT" breg_schema_token "$AUDIENCE" thunderid_fetch_token "$TID_ROOT" "$TID_REGISTRATION" foreign-directory-client breg_foreign_schema_token "$AUDIENCE" - write_own_secret breg-schema-token breg_schema_token - write_own_secret breg-foreign-schema-token breg_foreign_schema_token - journey_write_file "$credentials_file" --concepts client,grant,scopes,secret-file < <( - perl -MJSON::PP -e ' - my ($path) = @ARGV; - open my $fh, "<", $path or die "cannot read $path: $!\n"; - my ($journey, $step, @bindings); - while (my $line = <$fh>) { - if ($line =~ /^ - id: (\S+)/) { - $journey = $1; - $step = undef; - } elsif (defined $journey && $line =~ /^ - id: (\S+)/) { - $step = $1; - push @bindings, { - journeyId => $journey, - stepId => $step, - credential => { - type => "bearer", - tokenRef => "secret:file/breg-schema-token", - }, - }; - } elsif (@bindings && $line =~ /jurisdiction:\s*zone-b/) { - $bindings[-1]{credential}{tokenRef} = "secret:file/breg-foreign-schema-token"; - } - } - die "no journey steps found in $path\n" unless @bindings; - print JSON::PP->new->utf8->canonical->pretty->encode({ - apiVersion => "id.registrystack.org/formats/breg/schema-test-credentials/v1", - kind => "BRegSchemaTestCredentials", - bindings => \@bindings, - });' "$PROJECT/tests/journeys.yaml" - ) - return 0 + else + breg_keycloak_token "$CLIENT" client-breg breg_schema_token "$BREG_KEYCLOAK_CLAIM_SCOPE" + breg_keycloak_token foreign-directory-client client-breg-foreign breg_foreign_schema_token + breg_keycloak_token_matches breg_schema_token "$CLIENT" "$BREG_EDITOR_SUBJECT" synthetic-directory-editor zone-a || + journey_harness_failure "Keycloak did not issue the exact BReg editor claims and scope" + breg_keycloak_token_matches breg_foreign_schema_token foreign-directory-client "$BREG_FOREIGN_SUBJECT" synthetic-foreign-editor zone-b || + journey_harness_failure "Keycloak did not issue the exact BReg foreign editor claims and scope" fi - journey_secret_path "client-breg" secret_file - response=$(curl --silent --show-error --max-time 30 \ - --data grant_type=client_credentials \ - --data "client_id=$CLIENT" \ - --data-urlencode "client_secret@$secret_file" \ - "$KC_ISSUER/protocol/openid-connect/token") || - journey_harness_failure "Keycloak did not answer for $CLIENT while preparing bregctl test" - token=$(printf '%s' "$response" | jq -r '.access_token // empty') || - journey_harness_failure "Keycloak answered non-JSON for $CLIENT while preparing bregctl test" - [[ -n "$token" ]] || - journey_harness_failure "Keycloak refused client credentials for $CLIENT while preparing bregctl test" - # shellcheck disable=SC2034 # read by name in write_own_secret and journey_secret_register - BREG_SCHEMA_TOKEN=$token - journey_secret_register breg-schema-token BREG_SCHEMA_TOKEN - write_own_secret breg-schema-token BREG_SCHEMA_TOKEN + write_own_secret breg-schema-token breg_schema_token + write_own_secret breg-foreign-schema-token breg_foreign_schema_token journey_write_file "$credentials_file" --concepts client,grant,scopes,secret-file < <( perl -MJSON::PP -e ' my ($path) = @ARGV; open my $fh, "<", $path or die "cannot read $path: $!\n"; - my ($journey, @bindings); + my ($journey, $step, @bindings); while (my $line = <$fh>) { if ($line =~ /^ - id: (\S+)/) { $journey = $1; + $step = undef; } elsif (defined $journey && $line =~ /^ - id: (\S+)/) { + $step = $1; push @bindings, { journeyId => $journey, - stepId => $1, + stepId => $step, credential => { type => "bearer", tokenRef => "secret:file/breg-schema-token", }, }; + } elsif (@bindings && $line =~ /jurisdiction:\s*zone-b/) { + $bindings[-1]{credential}{tokenRef} = "secret:file/breg-foreign-schema-token"; } } die "no journey steps found in $path\n" unless @bindings; @@ -1529,21 +1695,6 @@ step_database() { journey_pass database.connect return 0 fi - if [[ "$ISSUER_KIND" == thunderid && "$product" == adapter ]]; then - local mig_url run_url ref_user ref_pass - mig_url=$(<"$MIGRATION_URL_FILE") - run_url=$(<"$RUNTIME_URL_FILE") - read_secret adapter-reference-username ref_user - read_secret adapter-reference-password ref_pass - ADAPTER_DB_MIGRATION="$mig_url" ADAPTER_DB_RUNTIME="$run_url" \ - REFERENCE_USERNAME="$ref_user" REFERENCE_PASSWORD="$ref_pass" \ - database_step database.provision "$TOOL provision --runtime-config $RUNTIME_FILE --admin-url-file $ADMIN_URL_FILE" -- \ - "$TOOL_BIN" provision --runtime-config "$RUNTIME_FILE" --admin-url-file "$ADMIN_URL_FILE" - [[ $CELL_OVER -eq 0 ]] || return 0 - # Adapter applies its journal and idempotency schema at startup; it has no apply command. - journey_pass database.connect - return 0 - fi database_step database.provision "$TOOL provision --runtime-config $RUNTIME_FILE --admin-url-file $ADMIN_URL_FILE" -- \ "$TOOL_BIN" provision --runtime-config "$RUNTIME_FILE" --admin-url-file "$ADMIN_URL_FILE" [[ $CELL_OVER -eq 0 ]] || return 0 @@ -1566,42 +1717,35 @@ step_database() { breg) local credentials=$WORK/schema-test-credentials.json receipt=$WORK/schema-test-receipt.json build=$WORK/build breg_schema_test_credentials "$credentials" - if [[ "$ISSUER_KIND" == thunderid ]]; then - # bregctl test records an initial activation in its target database, so - # run schema rehearsal against a separate breg_test database while keeping - # the serving breg database empty for bregctl apply --initial. - local test_rt=$WORK/test-runtime.yaml test_pkg=$WORK/test-package - # shellcheck disable=SC2034 # read by name in write_own_secret - local mig_pw run_pw test_url - journey_secret_new breg-test-mig-pw 24 - journey_secret_new breg-test-run-pw 24 - read_secret breg-test-mig-pw mig_pw - read_secret breg-test-run-pw run_pw - test_url="postgresql://breg_test_migration:$mig_pw@127.0.0.1:$PG_PORT/breg_test" - write_own_secret breg-test-migration-database-url test_url - # shellcheck disable=SC2034 # read by name in write_own_secret - test_url="postgresql://breg_test_runtime:$run_pw@127.0.0.1:$PG_PORT/breg_test" - write_own_secret breg-test-runtime-database-url test_url - mkdir -p -- "$test_pkg" - copy_file "$RUNTIME_FILE" "$test_rt" - harness_edit "$test_rt" " databaseId: local-directory-db" " databaseId: local-directory-test-db" - harness_edit "$test_rt" " runtimeUrlRef: secret:file/breg-runtime-database-url" " runtimeUrlRef: secret:file/breg-test-runtime-database-url" - harness_edit "$test_rt" " migrationUrlRef: secret:file/breg-migration-database-url" " migrationUrlRef: secret:file/breg-test-migration-database-url" - harness_edit "$test_rt" " migration: breg_migration" " migration: breg_test_migration" - harness_edit "$test_rt" " runtime: breg_runtime" " runtime: breg_test_runtime" - harness_edit "$test_rt" " root: $build/package" " root: $test_pkg" - reader_command database.connect -- "$TOOL_BIN" provision --runtime-config "$test_rt" --admin-url-file "$ADMIN_URL_FILE" - [[ $CELL_OVER -eq 0 ]] || return 0 - reader_command database.connect \ - --typed "$TOOL test $PROJECT --runtime-config $test_rt --credentials $credentials --output $receipt" -- \ - "$TOOL_BIN" --format json test "$PROJECT" --runtime-config "$test_rt" --credentials "$credentials" --output "$receipt" - [[ $CELL_OVER -eq 0 ]] || return 0 - else - reader_command database.connect \ - --typed "$TOOL test $PROJECT --runtime-config $RUNTIME_FILE --credentials $credentials --output $receipt" -- \ - "$TOOL_BIN" --format json test "$PROJECT" --runtime-config "$RUNTIME_FILE" --credentials "$credentials" --output "$receipt" - [[ $CELL_OVER -eq 0 ]] || return 0 - fi + # bregctl test records an initial activation in its target database, so + # run schema rehearsal against a separate breg_test database while keeping + # the serving breg database empty for bregctl apply --initial. + local test_rt=$WORK/test-runtime.yaml test_pkg=$WORK/test-package + # shellcheck disable=SC2034 # read by name in write_own_secret + local mig_pw run_pw test_url + journey_secret_new breg-test-mig-pw 24 + journey_secret_new breg-test-run-pw 24 + read_secret breg-test-mig-pw mig_pw + read_secret breg-test-run-pw run_pw + test_url="postgresql://breg_test_migration:$mig_pw@127.0.0.1:$PG_PORT/breg_test" + write_own_secret breg-test-migration-database-url test_url + # shellcheck disable=SC2034 # read by name in write_own_secret + test_url="postgresql://breg_test_runtime:$run_pw@127.0.0.1:$PG_PORT/breg_test" + write_own_secret breg-test-runtime-database-url test_url + mkdir -p -- "$test_pkg" + copy_file "$RUNTIME_FILE" "$test_rt" + harness_edit "$test_rt" " databaseId: local-directory-db" " databaseId: local-directory-test-db" + harness_edit "$test_rt" " runtimeUrlRef: secret:file/breg-runtime-database-url" " runtimeUrlRef: secret:file/breg-test-runtime-database-url" + harness_edit "$test_rt" " migrationUrlRef: secret:file/breg-migration-database-url" " migrationUrlRef: secret:file/breg-test-migration-database-url" + harness_edit "$test_rt" " migration: breg_migration" " migration: breg_test_migration" + harness_edit "$test_rt" " runtime: breg_runtime" " runtime: breg_test_runtime" + harness_edit "$test_rt" " root: $build/package" " root: $test_pkg" + reader_command database.connect -- "$TOOL_BIN" provision --runtime-config "$test_rt" --admin-url-file "$ADMIN_URL_FILE" + [[ $CELL_OVER -eq 0 ]] || return 0 + reader_command database.connect \ + --typed "$TOOL test $PROJECT --runtime-config $test_rt --credentials $credentials --output $receipt" -- \ + "$TOOL_BIN" --format json test "$PROJECT" --runtime-config "$test_rt" --credentials "$credentials" --output "$receipt" + [[ $CELL_OVER -eq 0 ]] || return 0 reader_command database.connect --concepts package \ --typed "$TOOL package $PROJECT --test-receipt $receipt --output $build" -- \ "$TOOL_BIN" --format json package "$PROJECT" --test-receipt "$receipt" --output "$build" @@ -1610,7 +1754,8 @@ step_database() { "$TOOL_BIN" --format json apply --initial --runtime-config "$RUNTIME_FILE" --package "$build/package" ;; adapter) - journey_harness_failure "no database.connect recipe is written for adapter: it has no apply command, and its runtime reads the database URLs from secret:env references; extend step_database in own-provider.sh" + # Adapter applies its journal and idempotency schema at startup. + journey_unexercised database.connect ;; esac } @@ -1623,14 +1768,10 @@ serve_command() { casework | messaging | scheduling | documents) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE" serve) ;; render) SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE") ;; adapter) - if [[ "$ISSUER_KIND" == thunderid ]]; then - SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE" - --project "$PROJECT" - --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" - --pack "$PROJECT/pack.yaml") - else - journey_harness_failure "no start recipe is written for $product; add one to serve_command in own-provider.sh" - fi + SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE" + --project "$PROJECT" + --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" + --pack "$PROJECT/pack.yaml") ;; evidence) if [[ "$ISSUER_KIND" == thunderid ]]; then @@ -1703,24 +1844,15 @@ step_start() { local product=$1 status=0 ready_url serve_command "$product" port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; the journey cannot start $product on it" - if [[ "$ISSUER_KIND" == thunderid && "$product" == adapter ]]; then - local mig_url run_url ref_user ref_pass - mig_url=$(<"$MIGRATION_URL_FILE") - run_url=$(<"$RUNTIME_URL_FILE") - read_secret adapter-reference-username ref_user - read_secret adapter-reference-password ref_pass + if [[ "$product" == adapter ]]; then journey_start start adapter-source -- python3 "$PROJECTS_DIR/adapter-source.py" \ "$ADAPTER_SOURCE_PORT" "$SECRETS/adapter-reference-username" "$SECRETS/adapter-reference-password" || journey_harness_failure "the Adapter loopback source failed to start" journey_ready start adapter-source --timeout 30 -- \ curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$ADAPTER_SOURCE_PORT/ready" || journey_harness_failure "the Adapter loopback source did not answer /ready" - ADAPTER_DB_MIGRATION="$mig_url" ADAPTER_DB_RUNTIME="$run_url" \ - REFERENCE_USERNAME="$ref_user" REFERENCE_PASSWORD="$ref_pass" \ - journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? - else - journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? fi + journey_start start server --settle 3 -- "${SERVE_COMMAND[@]}" || status=$? SERVER_LOG_OUT=$JOURNEY_STEP_STDOUT SERVER_LOG_ERR=$JOURNEY_STEP_STDERR if [[ $status -ne 0 ]]; then @@ -1767,10 +1899,15 @@ step_token() { journey_pass token return 0 fi - local token_url=$KC_ISSUER/protocol/openid-connect/token status=0 + local token_url=$KC_ISSUER/protocol/openid-connect/token status=0 typed_scope='' + local -a scope_option=() + if [[ "$CELL" == breg ]]; then + scope_option=(--form "scope=$BREG_KEYCLOAK_CLAIM_SCOPE") + typed_scope=" -d scope=$BREG_KEYCLOAK_CLAIM_SCOPE" + fi journey_http token --concepts client,grant,scopes \ - --typed "curl -X POST $token_url -d grant_type=client_credentials -d client_id=$CLIENT -d client_secret=\$SECRET" \ - --form grant_type=client_credentials --form "client_id=$CLIENT" --form-secret "client_secret=client-$CELL" \ + --typed "curl -X POST $token_url -d grant_type=client_credentials -d client_id=$CLIENT -d client_secret=\$SECRET$typed_scope" \ + --form grant_type=client_credentials --form "client_id=$CLIENT" --form-secret "client_secret=client-$CELL" "${scope_option[@]}" \ --capture-secret .access_token ACCESS_TOKEN POST "$token_url" || status=$? if [[ $status -ne 0 ]]; then journey_harness_failure "Keycloak refused the client credentials of $CLIENT (HTTP $JOURNEY_HTTP_STATUS); the realm is the journey's own setup, see $JOURNEY_STEP_STDOUT" @@ -1868,11 +2005,9 @@ call_request() { options+=(--header 'Content-Type: application/json' --data-file "$WORK/request.json") ;; adapter) - if [[ "$ISSUER_KIND" == thunderid ]]; then - options+=(--header 'Content-Type: application/json' - --header 'Idempotency-Key: journey-adapter-first-call' - --data-file "$WORK/adapter-call-body.json") - fi + options+=(--header 'Content-Type: application/json' + --header 'Idempotency-Key: journey-adapter-first-call' + --data-file "$WORK/adapter-call-body.json") ;; esac local status=0 @@ -1881,8 +2016,13 @@ call_request() { if [[ "$CELL" == scheduling && "$CALL_METHOD" == GET && "$CALL_PATH" == /v1/locations && "$JOURNEY_HTTP_STATUS" == 200 ]]; then scheduling_catalogue_ok=1 fi - if [[ "$ISSUER_KIND" == thunderid && "$CELL" == adapter && "$JOURNEY_HTTP_STATUS" != 201 ]]; then - journey_harness_failure "Adapter POST /v1/records/person returned HTTP $JOURNEY_HTTP_STATUS instead of 201" + if [[ "$CELL" == adapter ]]; then + [[ "$JOURNEY_HTTP_STATUS" == 201 ]] || + journey_harness_failure "Adapter POST /v1/records/person returned HTTP $JOURNEY_HTTP_STATUS instead of 201" + jq -e '.data == {name: "Example Person"} and .meta.recordTypeId == "person"' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "Adapter did not return the source fixture's person record" + cp -- "$JOURNEY_STEP_STDOUT" "$WORK/call.response" || + journey_harness_failure "cannot preserve the Adapter response for promotion" fi journey_request_contract "$CALL_METHOD" "$CALL_PATH" "${options[@]+"${options[@]}"}" >"$WORK/call.contract" journey_claim_names ACCESS_TOKEN >"$WORK/call.claims" @@ -1952,6 +2092,30 @@ check_thunderid_negative_auth() { journey_harness_failure "$CELL did not refuse a wrong-audience ThunderID token with HTTP 401 (got HTTP $JOURNEY_HTTP_STATUS)" } +# Match the claims check to the trace from the control's HTTP response. +breg_claims_refused_at_trace() { + local trace=$1 + shift + jq -Rne --arg trace "$trace" 'any(inputs | fromjson?; + .fields.trace_id == $trace and .fields.decision == "refused" and .fields.failed_check == "token-claims")' "$@" >/dev/null +} + +breg_no_mapper_control() { + # shellcheck disable=SC2034 # Read by name through the token and HTTP helpers. + local control_token='' trace + breg_keycloak_token "$CLIENT" client-breg control_token + breg_keycloak_token_matches control_token "$CLIENT" "$BREG_EDITOR_SUBJECT" '' '' || + journey_harness_failure "Keycloak did not issue the exact stock BReg scope and caller for the no-mapper control" + journey_http call --expect-status 401 --bearer control_token GET "http://127.0.0.1:$PORT$CALL_PATH" && + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == authentication.refused ]] || + journey_harness_failure "BReg's no-mapper control returned HTTP $JOURNEY_HTTP_STATUS ($JOURNEY_HTTP_PROBLEM_CODE)" + trace=$(jq -er '.traceId | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || + journey_harness_failure "BReg's no-mapper response did not include a valid trace ID" + refresh_server_log + breg_claims_refused_at_trace "$trace" "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" || + journey_harness_failure "BReg's no-mapper trace $trace has no refusal at the authored claims check" +} + # call: the first authenticated request. A refusal is named by the HTTP status # and the stage the product logged, by the problem code it answered when its # log names no stage. Optional assists may retry the request. @@ -1968,10 +2132,8 @@ step_call() { journey_harness_failure "cannot build the Render request body; see $JOURNEY_STEP_STDERR" ;; adapter) - if [[ "$ISSUER_KIND" == thunderid ]]; then - journey_write_file "$WORK/adapter-call-body.json" < <(printf '%s\n' \ - '{"data":{"recordId":"person-1","domainData":{"name":"Example Person"}}}') - fi + journey_write_file "$WORK/adapter-call-body.json" < <(printf '%s\n' \ + '{"data":{"recordId":"person-1","domainData":{"name":"Example Person"}}}') ;; esac call_request || status=$? @@ -1981,8 +2143,11 @@ step_call() { REACHED_AUTH_PRODUCTS+=("$CELL") fi check_wrong_kind + if [[ "$CELL" == breg && "$ISSUER_KIND" == keycloak ]]; then + breg_no_mapper_control + fi journey_pass call - journey_reached t1 + [[ "$CALL_METHOD" != GET ]] || journey_reached t1 return 0 fi [[ "$JOURNEY_HTTP_STATUS" != 000 ]] || @@ -2021,7 +2186,7 @@ step_call() { status=0 call_request || status=$? if [[ $status -eq 0 ]]; then - journey_reached t1 + [[ "$CALL_METHOD" != GET ]] || journey_reached t1 return 0 fi # The refusal of this call is logged after the response is written, and @@ -2048,31 +2213,6 @@ step_call() { CELL_OVER=1 } -# assert_signed_hook_acceptance LOG_FILE EXPECTED_PATH EXPECTED_TYPE: verify -# the hook receiver logged one value-free acceptance record proving Standard -# Webhooks HMAC-SHA256 receiver authority without inbound credential headers. -assert_signed_hook_acceptance() { - local log_file=$1 expected_path=$2 expected_type=$3 - # shellcheck disable=SC2016 # jq binds its own variables - jq -e -s --arg path "$expected_path" --arg type "$expected_type" ' - length == 1 - and (.[0] | - .event == "signed-hook-accepted" - and .path == $path - and .eventType == $type - and .signatureVerified == true - and .receiverAuthority == "standard-webhooks-hmac-sha256" - and .inboundCredentialHeaders == false - and (.headerNames | type == "array") - and (.headerNames | index("webhook-signature") != null) - and (.headerNames | index("authorization") == null) - and (.headerNames | index("registry-source-authorization") == null) - and (.headerNames | index("proxy-authorization") == null) - and (.headerNames | index("cookie") == null) - ) - ' "$log_file" >/dev/null -} - # assert_wrong_agent_grant_refused ISSUER_BIN TID_ROOT TASK_CONN CLIENT GRANT_ID: # run `journey-issuer grant` for an unintended agent and succeed only when it # exits non-zero, emits no stdout or header file, and reports the exact @@ -2218,6 +2358,22 @@ breg_hook() { journey_stop hook breg-hook-receiver || journey_harness_failure "the BReg hook receiver ignored SIGTERM" journey_step hook -- assert_signed_hook_acceptance "$receiver_out" /events contact-created || journey_harness_failure "the BReg signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" + if [[ "$ISSUER_KIND" == keycloak ]]; then + journey_http hook --expect-status 200 --bearer ACCESS_TOKEN GET "$origin/v1/records/contacts/$record_id" || + journey_harness_failure "the BReg editor could not read the contact named by the signed hook" + # shellcheck disable=SC2016 # jq binds its own variables. + journey_step hook -- jq -e --arg record "$record_id" '.data.recordId == $record' "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the BReg editor did not receive the exact contact" + local foreign_token='' + breg_keycloak_token foreign-directory-client client-breg-foreign foreign_token + breg_keycloak_token_matches foreign_token foreign-directory-client "$BREG_FOREIGN_SUBJECT" synthetic-foreign-editor zone-b || + journey_harness_failure "Keycloak did not issue the exact BReg foreign caller for the hook assertion" + [[ "$foreign_token" != "$(<"$SECRETS/breg-foreign-schema-token")" ]] || + journey_harness_failure "Keycloak reused the BReg schema test token for the hook assertion" + journey_http hook --expect-status 404 --bearer foreign_token GET "$origin/v1/records/contacts/$record_id" && + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == resource.not-found ]] || + journey_harness_failure "the BReg foreign caller was not concealed from the exact contact" + fi } # composed_scheduling_hook: exercise a real BReg + Casework + Scheduling @@ -2239,6 +2395,7 @@ composed_scheduling_hook() { local breg_final=$comp/breg-final breg_final_rt=$comp/breg-final-runtime.yaml breg_final_build=$comp/breg-final-build local sched_proj=$comp/sched-project sched_pkg=$comp/sched-package sched_rt=$comp/sched-runtime.yaml local task_conn=$comp/task-connection.json receipt=$comp/scheduling-hook.json + local managed_report=$comp/managed-scheduling.json bound_plan=$comp/managed-dev-plan.json local day start_time local breg_url cw_url sched_url comp_hook_out='' comp_cw_out='' # shellcheck disable=SC2034 # journey_process_log sets comp_cw_err while refreshing comp_cw_out @@ -2447,21 +2604,37 @@ JSON # 5) Build, package, provision & apply composed Scheduling with appointment-observer hook. day=$(python3 -c 'from datetime import datetime, timedelta, timezone; print((datetime.now(timezone.utc) + timedelta(days=2)).strftime("%Y-%m-%d"))') start_time="${day}T10:00:00Z" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + mkdir -m 700 -- "$COMPOSED_MANAGED_ROOT" "$COMPOSED_MANAGED_ROOT/state" "$COMPOSED_MANAGED_ROOT/install" + sched_proj=$COMPOSED_MANAGED_ROOT/project + journey_step hook -- "$TOOL_BIN" init --template standalone-exact-time "$COMPOSED_MANAGED_ROOT/starter" || + journey_harness_failure "cannot initialize the managed Scheduling fixture" + mkdir -m 700 -- "$sched_proj" + copy_file "$COMPOSED_MANAGED_ROOT/starter/runtime.example.yaml" "$sched_proj/runtime.example.yaml" + fi python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-project "$sched_proj" --day "$day" || journey_harness_failure "cannot write composed Scheduling project" - journey_step hook -- "$TOOL_BIN" package --output "$sched_pkg" "$sched_proj" || - journey_harness_failure "composed Scheduling package failed; see $JOURNEY_STEP_STDERR" - python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-runtime "$sched_rt" \ - --port "$sched_port" --metrics-port "$sched_metrics_port" --secrets "$SECRETS" \ - --package "$sched_pkg" --audit "$comp/sched-audit.ndjson" \ - --issuer "$comp_tid_issuer" --casework-port "$cw_port" --hook-port "$hook_port" || - journey_harness_failure "cannot write composed Scheduling runtime" - journey_step hook -- "$TOOL_BIN" provision --runtime-config "$sched_rt" --admin-url-file "$ADMIN_URL_FILE" --posture development || - journey_harness_failure "composed Scheduling provision failed; see $JOURNEY_STEP_STDERR" - journey_step hook -- "$TOOL_BIN" apply --runtime-config "$sched_rt" --posture development --format json || - journey_harness_failure "composed Scheduling apply failed; see $JOURNEY_STEP_STDERR" - journey_step hook -- "$TOOL_BIN" records apply --runtime-config "$sched_rt" "$sched_proj/records.yaml" --posture development --format json || - journey_harness_failure "composed Scheduling records apply failed; see $JOURNEY_STEP_STDERR" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-managed-plan "$sched_proj" \ + --issuer "$comp_tid_issuer" --jwks "$comp_tid_issuer/oauth2/jwks" \ + --casework-port "$cw_port" --agent-subject "$agent_sub" --status-key "$SECRETS/comp-sched-status-key" || + journey_harness_failure "cannot write the managed Scheduling plan" + copy_file "$sched_proj/dev.yaml" "$bound_plan" + else + journey_step hook -- "$TOOL_BIN" package --output "$sched_pkg" "$sched_proj" || + journey_harness_failure "composed Scheduling package failed; see $JOURNEY_STEP_STDERR" + python3 "$PROJECTS_DIR/composed_fixtures.py" scheduling-runtime "$sched_rt" \ + --port "$sched_port" --metrics-port "$sched_metrics_port" --secrets "$SECRETS" \ + --package "$sched_pkg" --audit "$comp/sched-audit.ndjson" \ + --issuer "$comp_tid_issuer" --casework-port "$cw_port" --hook-port "$hook_port" || + journey_harness_failure "cannot write composed Scheduling runtime" + journey_step hook -- "$TOOL_BIN" provision --runtime-config "$sched_rt" --admin-url-file "$ADMIN_URL_FILE" --posture development || + journey_harness_failure "composed Scheduling provision failed; see $JOURNEY_STEP_STDERR" + journey_step hook -- "$TOOL_BIN" apply --runtime-config "$sched_rt" --posture development --format json || + journey_harness_failure "composed Scheduling apply failed; see $JOURNEY_STEP_STDERR" + journey_step hook -- "$TOOL_BIN" records apply --runtime-config "$sched_rt" "$sched_proj/records.yaml" --posture development --format json || + journey_harness_failure "composed Scheduling records apply failed; see $JOURNEY_STEP_STDERR" + fi python3 "$PROJECTS_DIR/composed_fixtures.py" task-connection "$task_conn" \ --casework-port "$cw_port" --issuer "$comp_tid_issuer" --secrets "$SECRETS" || @@ -2472,13 +2645,15 @@ JSON cw_url=http://127.0.0.1:$cw_port sched_url=http://127.0.0.1:$sched_port - journey_start hook comp-hook-receiver -- python3 "$PROJECTS_DIR/hook-receiver.py" \ - "$hook_port" /scheduling-events appointment-observer "$SECRETS/comp-sched-hook-hmac" "$receipt" || - journey_harness_failure "composed Scheduling hook receiver failed to start" - comp_hook_out=$JOURNEY_STEP_STDOUT - journey_ready hook comp-hook-receiver --timeout 30 -- \ - curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$hook_port/ready" || - journey_harness_failure "composed Scheduling hook receiver did not answer /ready" + if [[ "$SCHEDULING_RUNTIME" == standalone ]]; then + journey_start hook comp-hook-receiver -- python3 "$PROJECTS_DIR/hook-receiver.py" \ + "$hook_port" /scheduling-events appointment-observer "$SECRETS/comp-sched-hook-hmac" "$receipt" || + journey_harness_failure "composed Scheduling hook receiver failed to start" + comp_hook_out=$JOURNEY_STEP_STDOUT + journey_ready hook comp-hook-receiver --timeout 30 -- \ + curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$hook_port/ready" || + journey_harness_failure "composed Scheduling hook receiver did not answer /ready" + fi journey_start hook comp-breg --settle 2 -- "$breg_bin" --posture development --runtime-config "$breg_final_rt" || journey_harness_failure "composed BReg failed to start" @@ -2497,11 +2672,13 @@ JSON jq -e '[.keys[]? | select(.kid == "journey-task-authority")] | length == 1' >/dev/null || journey_harness_failure "composed Casework did not publish journey-task-authority on /.well-known/jwks.json" - journey_start hook comp-scheduling --settle 2 -- "$SERVER_BIN" --posture development --runtime-config "$sched_rt" serve || - journey_harness_failure "composed Scheduling failed to start" - journey_ready hook comp-scheduling --timeout 90 -- \ - curl --silent --show-error --fail --output /dev/null "$sched_url/ready" || - journey_harness_failure "composed Scheduling did not become ready" + if [[ "$SCHEDULING_RUNTIME" == standalone ]]; then + journey_start hook comp-scheduling --settle 2 -- "$SERVER_BIN" --posture development --runtime-config "$sched_rt" serve || + journey_harness_failure "composed Scheduling failed to start" + journey_ready hook comp-scheduling --timeout 90 -- \ + curl --silent --show-error --fail --output /dev/null "$sched_url/ready" || + journey_harness_failure "composed Scheduling did not become ready" + fi # 7) Bootstrap Casework directory. # shellcheck disable=SC2034 # read by name through journey_http --bearer @@ -2667,6 +2844,15 @@ JSON journey_harness_failure "exchanged Scheduling task grant token lacks scalar Scheduling audience" # 13) Negative check: ordinary task-agent token without a task grant is refused by Scheduling POST /v1/holds. + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + # The same real exchanged bearer must be refused without an explicit + # assertion-authority binding. Use a separate stopped/restarted run. + jq 'del(.externalScheduling)' "$bound_plan" >"$sched_proj/dev.yaml" || + journey_harness_failure "cannot assemble the unbound managed Scheduling control" + start_composed_managed_scheduling "$sched_proj" "$comp/unbound-scheduling.json" + sched_url=$(composed_scheduling_url "$comp/unbound-scheduling.json") || + journey_harness_failure "the unbound Scheduling run has no loopback address" + fi thunderid_fetch_token "$comp_tid_root" "$comp_reg" task-agent ordinary_agent_token "urn:example:journey:scheduling" token_has_scalar_audience ordinary_agent_token "urn:example:journey:scheduling" || journey_harness_failure "composed ordinary task-agent token lacks string scalar Scheduling audience" @@ -2677,49 +2863,102 @@ JSON jq -cn --arg start "$start_time" --arg app "$app_id" --arg duplicate_key "cross-product-$app_id" --argjson rev "$sched_rev" \ '{offering:"application-review",start:$start,party:{recipients:1,attendees:1},channel:"assisted",duplicateKey:$duplicate_key,policyRevision:$rev,windowRevision:null,capabilities:[],prerequisites:[],externalReferences:[{product:"breg",recordType:"application",identifier:$app}]}' \ >"$comp/hold-request.json" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + assert_composed_scheduling_authority_refused "$sched_url" "$comp/hold-request.json" journey-comp-unbound-authority + stop_composed_managed_scheduling || journey_harness_failure "cannot stop the unbound managed Scheduling control" + + # The genuine exchanged token also fails when the same named client is + # bound to a different authority. Only this disposable plan is varied. + jq '.externalScheduling.taskGrant.sourceIssuer = "https://unrelated.casework.journey.example"' \ + "$bound_plan" >"$sched_proj/dev.yaml" || + journey_harness_failure "cannot assemble the wrong-authority managed Scheduling control" + start_composed_managed_scheduling "$sched_proj" "$comp/wrong-authority-scheduling.json" + sched_url=$(composed_scheduling_url "$comp/wrong-authority-scheduling.json") || + journey_harness_failure "the wrong-authority Scheduling run has no loopback address" + assert_composed_scheduling_authority_refused "$sched_url" "$comp/hold-request.json" journey-comp-wrong-authority + stop_composed_managed_scheduling || journey_harness_failure "cannot stop the wrong-authority managed Scheduling control" + + copy_file "$bound_plan" "$sched_proj/dev.yaml" + start_composed_managed_scheduling "$sched_proj" "$managed_report" + sched_url=$(composed_scheduling_url "$managed_report") || + journey_harness_failure "the managed Scheduling run has no loopback address" + local managed_config + managed_config=$(jq -er '.runtimeConfigs.scheduling' "$managed_report") || + journey_harness_failure "the managed Scheduling run did not report its runtime configuration" + jq -e --slurpfile plan "$bound_plan" ' + $plan[0].externalScheduling.taskGrant as $binding | + .authentication.oidc.issuers.main as $issuer | + $issuer.issuer == $plan[0].issuer and $issuer.audience == $plan[0].products[0].audience and + $issuer.allowedClients == [$binding.assertionClient] and + $issuer.assertionIssuers == {($binding.assertionClient): [$binding.sourceIssuer]} and + (.taskGrantStatus | type == "array" and length == 1) and + (.taskGrantStatus[0] | .sourceIssuer == $binding.sourceIssuer and .baseUrl == $binding.statusUrl and + .tokenEndpoint == $binding.tokenEndpoint and .clientAssertionAudience == $issuer.issuer and + .clientId == $binding.statusClient and .statusResource == $binding.statusResource and + (.privateKeyRef | startswith("secret:file/")))' "$managed_config" >"$comp/managed-status-binding.json" || + journey_harness_failure "managed Scheduling did not project the exact live Casework status binding" + journey_http hook --bearer ordinary_agent_token GET "$sched_url/v1/scheduling" || + journey_harness_failure "the managed Scheduling policy metadata request failed" + jq -e --argjson revision "$sched_rev" '.policyRevision == $revision' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the managed Scheduling run did not load the same booking policy revision" + fi journey_http hook --expect-status 403 --bearer ordinary_agent_token \ --header 'Content-Type: application/json' \ --header 'Idempotency-Key: journey-comp-hold-no-grant' \ --data-file "$comp/hold-request.json" \ POST "$sched_url/v1/holds" || journey_harness_failure "composed Scheduling did not refuse grantless hold with HTTP 403 (got HTTP $JOURNEY_HTTP_STATUS)" + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == operation.not-authorized ]] || + journey_harness_failure "composed Scheduling returned an unexpected grantless hold problem code" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + jq -e '.failedCheck == "task-grant-missing"' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "managed Scheduling grantless hold did not refuse at task-grant-missing" + fi # 14) Positive check: create hold and confirm appointment with the exchanged grant, # then verify signed Standard Webhooks appointment-observer delivery. - local hold_id='' appt_id='' - journey_http hook --expect-status 201 --bearer exchanged_token \ - --header 'Content-Type: application/json' \ - --header 'Idempotency-Key: journey-comp-hold-create' \ - --data-file "$comp/hold-request.json" \ - --capture .holdId hold_id \ - POST "$sched_url/v1/holds" || - journey_harness_failure "composed Scheduling hold creation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" - jq -cn --arg hold "$hold_id" '{hold:$hold,admission:null}' >"$comp/appt-request.json" - journey_http hook --expect-status 201 --bearer exchanged_token \ - --header 'Content-Type: application/json' \ - --header 'Idempotency-Key: journey-comp-appt-confirm' \ - --data-file "$comp/appt-request.json" \ - --capture .appointmentId appt_id \ - POST "$sched_url/v1/appointments" || - journey_harness_failure "composed Scheduling appointment confirmation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" + local appt_id='' + journey_scheduling_appointment "$sched_url" "$comp" "$comp/hold-request.json" exchanged_token appt_id [[ -n "$appt_id" ]] || journey_harness_failure "composed Scheduling appointment response carried no appointmentId" - journey_ready hook comp-hook-receiver --timeout 45 -- test -s "$receipt" || - journey_harness_failure "composed Scheduling hook receiver did not accept the signed appointment-observer hook" - # shellcheck disable=SC2016 # jq binds its own variables - journey_step hook -- jq -e --arg appt "$appt_id" \ - '.type == "appointment-observer" and .data.appointmentId == $appt and .data.state == "confirmed"' \ - "$receipt" || - journey_harness_failure "composed Scheduling signed hook did not carry appointment-observer for appointment $appt_id" + if [[ "$SCHEDULING_RUNTIME" == managed ]]; then + local sink expected + sink=$(jq -er '.hookSinks.scheduling.receivedUrl | select(test("^http://127[.]0[.]0[.]1:[0-9]+/received$"))' "$managed_report") || + journey_harness_failure "managed Scheduling did not report a loopback hook sink" + expected=$(jq -cn --arg id "$appt_id" '{type:"appointment-observer", source:"urn:registrystack:scheduling:journey-composed-scheduling",data:{appointmentId:$id,state:"confirmed"}}') + journey_poll 45 -- signed_hook_received "$sink" "$expected" || + journey_harness_failure "the managed Scheduling hook sink did not receive the signed appointment" + journey_http hook GET "$sink" || journey_harness_failure "the managed Scheduling hook sink did not answer" + signed_hook_matches "$expected" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the managed Scheduling hook receipt does not match the confirmed appointment" + # A subsequent write with the same issued bearer needs a fresh status + # result. Stop our disposable Casework after proving the appointment. + journey_stop hook comp-casework || journey_harness_failure "composed Casework ignored SIGTERM" + journey_http hook --expect-status 503 --bearer exchanged_token \ + --header 'Content-Type: application/json' --header 'Idempotency-Key: journey-comp-status-unavailable' \ + --data-file "$comp/hold-request.json" POST "$sched_url/v1/holds" || + journey_harness_failure "managed Scheduling returned HTTP $JOURNEY_HTTP_STATUS when live status was unavailable" + [[ "$JOURNEY_HTTP_PROBLEM_CODE" == service.unavailable ]] || + journey_harness_failure "managed Scheduling did not report service.unavailable for the stopped status authority" + stop_composed_managed_scheduling || journey_harness_failure "managed Scheduling did not stop" + else + journey_ready hook comp-hook-receiver --timeout 45 -- test -s "$receipt" || + journey_harness_failure "composed Scheduling hook receiver did not accept the signed appointment-observer hook" + # shellcheck disable=SC2016 # jq binds its own variables + journey_step hook -- jq -e --arg appt "$appt_id" \ + '.type == "appointment-observer" and .data.appointmentId == $appt and .data.state == "confirmed"' \ + "$receipt" || + journey_harness_failure "composed Scheduling signed hook did not carry appointment-observer for appointment $appt_id" + journey_stop hook comp-scheduling || journey_harness_failure "composed Scheduling ignored SIGTERM" + journey_stop hook comp-hook-receiver || journey_harness_failure "composed Scheduling hook receiver ignored SIGTERM" + journey_step hook -- assert_signed_hook_acceptance "$comp_hook_out" /scheduling-events appointment-observer || + journey_harness_failure "composed Scheduling signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" + journey_stop hook comp-casework || journey_harness_failure "composed Casework ignored SIGTERM" + fi # 15) Stop composed processes and composed ThunderID session cleanly, then # restore the outer standalone session variables. - journey_stop hook comp-scheduling || journey_harness_failure "composed Scheduling ignored SIGTERM" - journey_stop hook comp-casework || journey_harness_failure "composed Casework ignored SIGTERM" journey_stop hook comp-breg || journey_harness_failure "composed BReg ignored SIGTERM" - journey_stop hook comp-hook-receiver || journey_harness_failure "composed Scheduling hook receiver ignored SIGTERM" - journey_step hook -- assert_signed_hook_acceptance "$comp_hook_out" /scheduling-events appointment-observer || - journey_harness_failure "composed Scheduling signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" stop_thunderid_session "$comp_tid_root" || journey_harness_failure "cannot stop composed ThunderID session" TID_ROOT=$saved_tid_root @@ -2736,13 +2975,8 @@ JSON step_hook() { case "$CELL" in breg) - if [[ "$ISSUER_KIND" == thunderid ]]; then - breg_hook - journey_pass hook - else - journey_unreached hook "The product delivers hooks, and this journey does not start a hook receiver yet." - CELL_OVER=1 - fi + breg_hook + journey_pass hook ;; scheduling) [[ $scheduling_catalogue_ok -eq 1 ]] || @@ -2759,12 +2993,13 @@ step_hook() { documents_hook journey_pass hook ;; + adapter) journey_unexercised hook ;; *) journey_pass hook ;; esac } step_stop() { - if [[ "$ISSUER_KIND" == thunderid && "$CELL" == adapter ]] && journey_process_running adapter-source; then + if [[ "$CELL" == adapter ]] && journey_process_running adapter-source; then journey_stop stop adapter-source || journey_harness_failure "the Adapter loopback source ignored SIGTERM" fi if journey_stop stop server; then @@ -2886,7 +3121,9 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then fi done fi + [[ "$SCHEDULING_RUNTIME" != managed ]] || BIN_OPTS+=(--package registry-rstack) journey_resolve_binaries ${BIN_OPTS[@]+"${BIN_OPTS[@]}"} "${PRIMARY[@]}" + [[ "$SCHEDULING_RUNTIME" != managed ]] || journey_bin rstack COMPOSED_RSTACK_BIN if [[ "$ISSUER_KIND" == thunderid && $NEEDS_ISSUER -eq 1 ]]; then journey_resolve_example registry-thunderid-tooling session journey-issuer JOURNEY_ISSUER_BIN fi @@ -2907,6 +3144,15 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then recipe "$product" keycloak_default_scope "$CLIENT" "$SCOPE" case "$product" in + breg) + keycloak_default_scope foreign-directory-client "$SCOPE" + breg_keycloak_exact_scope "$CLIENT" + breg_keycloak_exact_scope foreign-directory-client + keycloak_service_account_subject "$CLIENT" BREG_EDITOR_SUBJECT + keycloak_service_account_subject foreign-directory-client BREG_FOREIGN_SUBJECT + breg_keycloak_editor_scope + breg_keycloak_add_mappers foreign-directory-client synthetic-foreign-editor zone-b + ;; casework) keycloak_default_scope "$CLIENT" casework:staff keycloak_service_account_subject "$CLIENT" CASEWORK_SUBJECT @@ -2921,12 +3167,13 @@ if [[ ${#PRIMARY[@]} -gt 0 ]]; then fi jq -n --arg issuer "$ISSUER_KIND" --arg image "$KEYCLOAK_IMAGE" --arg realm "$REALM" \ --arg issuerUrl "$KC_ISSUER" --arg postgres "$POSTGRES_IMAGE" --arg pgPort "$PG_PORT" \ - --arg port "$PORT" --arg metricsPort "$METRICS_PORT" \ + --arg port "$PORT" --arg metricsPort "$METRICS_PORT" --args \ 'def opt: if . == "" then null else . end; {schema: "registry.journey-own-provider/v1", issuer: $issuer, issuerImage: $image, realm: $realm, issuerUrl: ($issuerUrl | opt), postgresImage: $postgres, postgresPort: ($pgPort | opt | if . == null then null else tonumber end), productPort: ($port | tonumber), productMetricsPort: ($metricsPort | tonumber), - containers: {issuer: "kc", postgres: "pg"}}' >"$JOURNEY_OUT/own-provider.json" || + fixtureOnlyProducts: [$ARGS.positional[] | select(. == "breg")], + containers: {issuer: "kc", postgres: "pg"}}' "${PRIMARY[@]}" >"$JOURNEY_OUT/own-provider.json" || journey_harness_failure "cannot write $JOURNEY_OUT/own-provider.json" else jq -n --arg issuer "$ISSUER_KIND" --arg image "$THUNDERID_IMAGE" \ diff --git a/products/platform/journeys/projects/check-private-postgres.py b/products/platform/journeys/projects/check-private-postgres.py new file mode 100644 index 0000000000..ec575be2e5 --- /dev/null +++ b/products/platform/journeys/projects/check-private-postgres.py @@ -0,0 +1,32 @@ +"""Check both BReg child URL references without reporting credential values.""" + +import json +import sys +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + + +def check(config_path, address): + config = json.loads(config_path.read_text(encoding="utf-8")) + database = config["database"] + if database["transport"] != "private-network-plaintext": + raise ValueError("unexpected PostgreSQL transport") + root = Path(config["secretProviders"]["file"]["root"]).resolve(strict=True) + for role in ("runtime", "migration"): + prefix, name = database[role + "UrlRef"].rsplit("/", 1) + if prefix != "secret:file" or not name: + raise ValueError("expected a local file reference for each database role") + secret = (root / name).resolve(strict=True) + if secret.parent != root: + raise ValueError("database URL file must be inside the run's secret directory") + url = urlsplit(secret.read_text(encoding="utf-8").strip()) + if url.hostname != address or url.port != 5432 or parse_qs(url.query) != {"sslmode": ["disable"]}: + raise ValueError("database role did not pin the expected private endpoint and transport") + + +if __name__ == "__main__": + try: + check(Path(sys.argv[1]), sys.argv[2]) + except (OSError, KeyError, TypeError, ValueError): + raise SystemExit("BReg's generated PostgreSQL roles did not use the checked private Compose transport") from None + print(json.dumps({"transport": "private-network-plaintext", "rolesPinned": ["runtime", "migration"]})) diff --git a/products/platform/journeys/projects/composed_fixtures.py b/products/platform/journeys/projects/composed_fixtures.py index 01889f2300..5e1ab947c2 100644 --- a/products/platform/journeys/projects/composed_fixtures.py +++ b/products/platform/journeys/projects/composed_fixtures.py @@ -7,7 +7,10 @@ import hashlib import json import os +import shutil +import stat from pathlib import Path +from urllib.parse import urlsplit SOURCE = "journey-source" AUTHORITY = "https://casework.journey.example" @@ -740,6 +743,69 @@ def cmd_scheduling_project(args: argparse.Namespace) -> None: ) +def cmd_scheduling_managed_plan(args: argparse.Namespace) -> None: + root = Path(args.directory) + issuer = urlsplit(args.issuer) + jwks = urlsplit(args.jwks) + if (issuer.scheme != "http" or issuer.hostname != "127.0.0.1" or not issuer.port + or issuer.path or issuer.query or issuer.fragment or issuer.username + or (jwks.scheme, jwks.netloc) != (issuer.scheme, issuer.netloc) + or not jwks.path or jwks.query or jwks.fragment): + raise SystemExit("managed Scheduling requires the exact numeric loopback issuer and its same-origin JWKS") + + example = root / "runtime.example.yaml" + example_source = example.read_text(encoding="utf-8") + empty_destinations = "\ndestinations: {}\n" + if example_source.count(empty_destinations) != 1: + raise SystemExit("managed Scheduling needs the starter's empty runtime destinations") + + fixture = root / "fixture" + key_name = "scheduling-status.jwk" + with os.fdopen(os.open(args.status_key, os.O_RDONLY | os.O_NOFOLLOW), "rb") as source: + metadata = os.fstat(source.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() or metadata.st_mode & 0o077: + raise SystemExit("managed Scheduling needs an owner-only fixture status key") + fixture.mkdir(mode=0o700) + fd = os.open(fixture / key_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "wb") as destination: + shutil.copyfileobj(source, destination) + + example.write_text(example_source.replace(empty_destinations, """ +destinations: + hooks: + appointment-events: + url: http://127.0.0.1:1/events + hmacSha256KeyRef: secret:file/unused-example-hook-key + attemptTimeoutMilliseconds: 2000 + maximumAttempts: 5 +"""), encoding="utf-8") + write_json(root / "dev-journeys.yaml", { + "apiVersion": "id.registrystack.org/formats/rstack/journeys/v1alpha1", + "kind": "RStackJourneys", "journeys": [], + }) + write_json(root / "dev.yaml", { + "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", + "kind": "RStackDev", + "issuer": args.issuer, + "externalJwksUri": args.jwks, + "products": [{"product": "scheduling", "project": ".", "audience": SCHEDULING_RESOURCE}], + "people": {"task-agent": { + "subject": args.agent_subject, "client": "task-agent", + "grants": {"scheduling": {"profile": "reader", "scopes": ["scheduling:read"]}}, + }}, + "journeyFile": "dev-journeys.yaml", + "externalScheduling": {"taskGrant": { + "sourceIssuer": AUTHORITY, + "assertionClient": "task-agent", + "statusUrl": f"http://127.0.0.1:{args.casework_port}", + "tokenEndpoint": f"{args.issuer}/oauth2/token", + "statusClient": "scheduling-status", + "statusKeyRef": f"secret:file/{key_name}", + "statusResource": CASEWORK_RESOURCE, + }}, + }) + + def cmd_scheduling_runtime(args: argparse.Namespace) -> None: runtime = { "apiVersion": "id.registrystack.org/formats/scheduling/runtime/v1alpha1", @@ -885,6 +951,15 @@ def main() -> None: p.add_argument("--day", required=True) p.set_defaults(func=cmd_scheduling_project) + p = sub.add_parser("scheduling-managed-plan") + p.add_argument("directory") + p.add_argument("--issuer", required=True) + p.add_argument("--jwks", required=True) + p.add_argument("--casework-port", type=int, required=True) + p.add_argument("--agent-subject", required=True) + p.add_argument("--status-key", required=True) + p.set_defaults(func=cmd_scheduling_managed_plan) + p = sub.add_parser("scheduling-runtime") p.add_argument("output") p.add_argument("--port", type=int, required=True) diff --git a/products/platform/journeys/projects/hook-receiver.py b/products/platform/journeys/projects/hook-receiver.py index 3d7a7a2295..fdacbbb3f3 100644 --- a/products/platform/journeys/projects/hook-receiver.py +++ b/products/platform/journeys/projects/hook-receiver.py @@ -62,7 +62,9 @@ def verify_signed_delivery(path, expected_path, headers, body, key, expected_typ return 204, record -def main(port, expected_path, expected_type, key_path, receipt): +def main(port, expected_path, expected_type, key_path, receipt, bind_address="127.0.0.1"): + if bind_address not in ("127.0.0.1", "0.0.0.0"): + raise SystemExit("receiver must bind loopback or the Compose container interface") key = Path(key_path).read_bytes() path = Path(receipt) @@ -105,7 +107,7 @@ def do_POST(self): pending.replace(path) self.reply(204) - with HTTPServer(("127.0.0.1", int(port)), Receiver) as server: + with HTTPServer((bind_address, int(port)), Receiver) as server: server.serve_forever() diff --git a/products/platform/journeys/projects/rstack-attachments.compose.yaml b/products/platform/journeys/projects/rstack-attachments.compose.yaml new file mode 100644 index 0000000000..37b93f249f --- /dev/null +++ b/products/platform/journeys/projects/rstack-attachments.compose.yaml @@ -0,0 +1,29 @@ +services: + db: + image: postgres:18.7@sha256:e754b839f447639b7004895f4d8a4bfcb4e9dbe3a1bc035f27f646562a16fd61 + pull_policy: never + environment: + POSTGRES_PASSWORD_FILE: /run/secrets/db-password + secrets: [db-password] + healthcheck: + test: [CMD, pg_isready, --host, 127.0.0.1, --username, postgres] + interval: 1s + timeout: 1s + retries: 20 + tmpfs: [/var/lib/postgresql] + receiver: + image: mcr.microsoft.com/playwright:v1.60.0-noble@sha256:9bd26ad900bb5e0f4dee75839e957a89ae89c2b7ab1e76050e559790e946b948 + pull_policy: never + user: "${RSTACK_JOURNEY_RECEIVER_USER:?}" + entrypoint: [python3, /receiver.py] + command: ["8109", /events, contact-created, /run/secrets/hook-key, /receipts/event.json, "0.0.0.0"] + ports: ["127.0.0.1::8109"] + volumes: + - "${RSTACK_JOURNEY_RECEIVER_SCRIPT:?}:/receiver.py:ro" + - "${RSTACK_JOURNEY_RECEIVER_RECEIPTS:?}:/receipts" + secrets: [hook-key] +secrets: + db-password: + file: "${RSTACK_JOURNEY_DB_PASSWORD_FILE:?}" + hook-key: + file: "${RSTACK_JOURNEY_HOOK_KEY_FILE:?}" diff --git a/products/platform/journeys/projects/rstack-attachments.sh b/products/platform/journeys/projects/rstack-attachments.sh new file mode 100644 index 0000000000..8ec8e27614 --- /dev/null +++ b/products/platform/journeys/projects/rstack-attachments.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +set -euo pipefail + +ATTACHMENT_COMPOSE_ACTIVE=0 +ATTACHMENT_COMPOSE_PROJECT='' +ATTACHMENT_HOOK_KEY='' +ATTACHMENT_DB_PASSWORD='' +ATTACHMENT_FIXTURE_KEY='' +ATTACHMENT_RECEIPTS='' + +attachment_compose() { + RSTACK_JOURNEY_RECEIVER_USER="$(id -u):$(id -g)" \ + RSTACK_JOURNEY_RECEIVER_SCRIPT="$JOURNEY_LIB_DIR/projects/hook-receiver.py" \ + RSTACK_JOURNEY_RECEIVER_RECEIPTS="$ATTACHMENT_RECEIPTS" \ + RSTACK_JOURNEY_DB_PASSWORD_FILE="$ATTACHMENT_DB_PASSWORD" \ + RSTACK_JOURNEY_HOOK_KEY_FILE="$ATTACHMENT_HOOK_KEY" \ + docker compose --env-file /dev/null --project-name "$ATTACHMENT_COMPOSE_PROJECT" \ + --file "$JOURNEY_LIB_DIR/projects/rstack-attachments.compose.yaml" "$@" +} + +stop_compose_attachments() { + local status=0 + if [[ "$ATTACHMENT_COMPOSE_ACTIVE" == 1 ]]; then + attachment_compose down || status=1 + fi + if [[ -n "$ATTACHMENT_FIXTURE_KEY" && -e "$ATTACHMENT_FIXTURE_KEY" ]]; then + rm -- "$ATTACHMENT_FIXTURE_KEY" || status=1 + fi + return "$status" +} + +prepare_compose_attachments() { + local project=$1 work=$2 origin existing + ATTACHMENT_COMPOSE_PROJECT="$JOURNEY_CONTAINER_PREFIX-attachments-$JOURNEY_RUN_ID" + ATTACHMENT_RECEIPTS=$work/receiver + mkdir -m 700 -- "$ATTACHMENT_RECEIPTS" "$project/fixture" + journey_secret_new compose-hook-key 32 + journey_secret_new compose-db-password 24 + journey_secret_path compose-hook-key ATTACHMENT_HOOK_KEY + journey_secret_path compose-db-password ATTACHMENT_DB_PASSWORD + ATTACHMENT_FIXTURE_KEY=$project/fixture/contact-hmac + install -m 600 -- "$ATTACHMENT_HOOK_KEY" "$ATTACHMENT_FIXTURE_KEY" + + existing=$(docker ps -aq --filter "label=com.docker.compose.project=$ATTACHMENT_COMPOSE_PROJECT") || + journey_harness_failure "cannot check ownership of the disposable Compose project" + [[ -z "$existing" ]] || journey_harness_failure "the Compose project name already exists" + existing=$(docker network ls -q --filter "name=^${ATTACHMENT_COMPOSE_PROJECT}_default$") || + journey_harness_failure "cannot check ownership of the disposable Compose network" + [[ -z "$existing" ]] || journey_harness_failure "the Compose network name already exists" + ATTACHMENT_COMPOSE_ACTIVE=1 + attachment_compose up --wait --wait-timeout 60 || journey_harness_failure "the disposable Compose services did not start" + origin=$(attachment_compose port receiver 8109) || journey_harness_failure "the sibling hook receiver has no port" + [[ "$origin" =~ ^127\.0\.0\.1:[0-9]+$ ]] || journey_harness_failure "the sibling receiver must publish loopback only" + journey_poll 30 -- curl --silent --fail --max-time 2 --output /dev/null "http://$origin/ready" || + journey_harness_failure "the sibling hook receiver did not become ready" + local unsigned + unsigned=$(curl --silent --show-error --max-time 5 --output /dev/null --write-out '%{http_code}' \ + --json '{}' "http://$origin/events") || journey_harness_failure "the unsigned hook control could not reach the receiver" + [[ "$unsigned" == 403 && ! -e "$ATTACHMENT_RECEIPTS/event.json" ]] || + journey_harness_failure "the sibling receiver did not refuse the unsigned control without a capture" + printf '%s\n' 'The sibling receiver refused the unsigned hook with HTTP 403.' + cat >>"$project/dev.yaml" </dev/null || + journey_harness_failure "the sibling hook run unexpectedly started an internal BReg sink" + # shellcheck disable=SC2016 # jq binds $id. + journey_poll 45 -- jq -e --arg id "$expected" ' + .type == "contact-created" and .data.recordId == $id and .data.values.name == "A retained contact"' \ + "$ATTACHMENT_RECEIPTS/event.json" >/dev/null || + journey_harness_failure "the sibling receiver did not capture the signed event for the exact contact" + jq -e --arg id "$expected" 'select(.data.recordId == $id)' "$ATTACHMENT_RECEIPTS/event.json" \ + >"$ATTACHMENT_RECEIPTS/$phase-event.json" || journey_harness_failure "the sibling receiver capture changed before readback" + event=$(jq -er '.id | strings | select(length > 0)' "$ATTACHMENT_RECEIPTS/$phase-event.json") || + journey_harness_failure "the sibling receiver capture has no event ID" + attachment_compose logs --no-color --no-log-prefix receiver | + jq -Rc --arg id "$event" 'fromjson? | select(.eventId == $id)' >"$report" || + journey_harness_failure "cannot read the sibling receiver acceptance log" + assert_signed_hook_acceptance "$report" /events contact-created || + journey_harness_failure "the sibling receiver did not confirm signature verification without caller credentials" +} + +verify_compose_services_running() { + local service + for service in db receiver; do + [[ -n "$(attachment_compose ps --status running --quiet "$service")" ]] || + journey_harness_failure "stopping rstack also stopped the developer-owned Compose $service" + done + printf '%s\n' 'Both developer-owned Compose services remained running after rstack stopped.' +} + +private_compose_database_address() { + local container=$1 network=$2 + docker inspect "$container" | jq -er --arg network "$network" ' + .[0] | select((.NetworkSettings.Networks | keys) == [$network]) + | select([(.HostConfig.PortBindings // {})[]? | .[]?] == []) + | select([(.NetworkSettings.Ports // {})[]? | .[]?] == []) + | .NetworkSettings.Networks[$network].IPAddress + | select(test("^(10\\.|172\\.(1[6-9]|2[0-9]|3[01])\\.|192\\.168\\.)[0-9.]+$"))' +} + +expect_implicit_compose_refusal() { + local project=$1 reply status=0 run + reply=$(rstack_dev start "$project") || status=$? + if [[ "$status" == 0 ]]; then + run=$(jq -er '.run_id' <<<"$reply") || return 1 + rstack_dev stop "$run" >/dev/null || return 1 + printf '%s\n' 'Private plaintext unexpectedly started without an explicit transport selector.' >&2 + return 1 + fi + printf '%s\n' "$reply" + [[ "$status" == 1 ]] && jq -e ' + .error.class == "domain" and (.error.message | contains("numeric loopback"))' <<<"$reply" >/dev/null +} + +attach_compose_database() { + # shellcheck disable=SC2034 # issue_token and --bearer read token by name. + local project=$1 work=$2 container address password admin_base origin token='' contact='' + stop_live_runs || journey_harness_failure "cannot stop the managed run before Compose attachment" + container=$(attachment_compose ps --quiet db) || journey_harness_failure "cannot locate the Compose database" + [[ "$container" =~ ^[0-9a-f]{64}$ ]] || journey_harness_failure "expected one disposable Compose database" + address=$(private_compose_database_address "$container" "${ATTACHMENT_COMPOSE_PROJECT}_default") || + journey_harness_failure "the Compose database must have one numeric private address and no published port" + IFS= read -r password <"$ATTACHMENT_DB_PASSWORD" + admin_base="postgresql://postgres:$password@$address:5432/postgres" + RSTACK_DEV_DATABASE_URL="$admin_base?sslmode=disable" \ + journey_step attach --typed 'rstack dev start with implicit private plaintext' -- \ + expect_implicit_compose_refusal "$project" || + journey_harness_failure "implicit private plaintext did not return the expected loopback refusal" + RSTACK_DEV_DATABASE_URL="$admin_base?transport=private-network-plaintext" start_run attach "$project" || + journey_harness_failure "explicit private Compose attachment did not start; see $JOURNEY_STEP_STDOUT" + local config + config=$(jq -er '.runtimeConfigs.breg' "$START_FILE") || journey_harness_failure "the attached run names no BReg config" + journey_step attach -- python3 "$JOURNEY_LIB_DIR/projects/check-private-postgres.py" "$config" "$address" || + journey_harness_failure "BReg did not pin the private Compose address for both database roles" + origin=$(run_url breg) + issue_token attach "$RUN" editor token || journey_harness_failure "cannot issue the attached BReg editor credential" + journey_http attach --expect-status 201 --bearer token --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-compose-attached-contact' --data-file "$work/keep-body.json" \ + --capture .data.recordId contact POST "$origin/v1/records/contacts" || unexpected_answer attach + verify_sibling_hook "$contact" attached + journey_http attach --expect-status 200 --bearer token GET "$origin/v1/records/contacts/$contact" || unexpected_answer attach + jq -e --arg id "$contact" '.data.recordId == $id' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the attached BReg read did not return the contact written on the Compose database" + journey_pass attach +} diff --git a/products/platform/journeys/promote.sh b/products/platform/journeys/promote.sh index 41d0f250a5..6f996fca9a 100755 --- a/products/platform/journeys/promote.sh +++ b/products/platform/journeys/promote.sh @@ -21,8 +21,8 @@ # production check and the list from the start. The two # lists must be equal, or the run stops as a harness # failure. The explicit production-compatible cases can continue -# with zero diagnostics. The count goes to refusalsMet -# in summary.json. +# with zero diagnostics. The number of distinct matched +# codes goes to productionRefusals in summary.json. # fix each refusal is fixed by the function fix_. A # code with no function is a harness failure that names # it, so a new refusal is looked at and never recorded @@ -36,7 +36,8 @@ # http... # same-contract the request line, the headers other than the token # and the token's claim names equal the original authenticated -# call's recorded contract and claim names. +# call's recorded contract and claim names. Adapter also +# replays the original HTTP 201 response with the source stopped. # # The input. --from RUN_DIR is a run directory of own-provider.sh that ended # with --keep, under the same JOURNEY_CONTAINER_PREFIX. Without --from this run @@ -155,6 +156,21 @@ input_outcome() { elif .[0].outcome == "pass" or (.[0].outcome == "unreached" and .[0].toT1 != null) then "finished" else .[0].outcome end' "$FROM/summary.json") || journey_harness_failure "cannot read the cell of $1 in $FROM/summary.json" + if [[ "$value" == finished && "$1" == breg ]]; then + # A passing BReg summary alone cannot authorize reuse of the fixture. + if [[ ! -e "$FROM/own-provider.json" ]]; then + value=legacy-unmarked + else + value=$(jq -er ' + if type != "object" then "invalid-fixture-marker" + elif has("fixtureOnlyProducts") | not then "legacy-unmarked" + elif .fixtureOnlyProducts == ["breg"] then "fixture-only" + else "invalid-fixture-marker" end' "$FROM/own-provider.json" 2>/dev/null) || value=invalid-fixture-marker + fi + elif [[ "$value" == finished && -f "$FROM/own-provider.json" ]] && jq -e --arg product "$1" ' + .fixtureOnlyProducts | type == "array" and index($product) != null' "$FROM/own-provider.json" >/dev/null; then + value=fixture-only + fi printf -v "$2" '%s' "$value" } @@ -211,6 +227,12 @@ recipe() { case "$product" in breg | coordinator) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE") ;; casework | messaging | scheduling | documents) SERVE_COMMAND=("$SERVER_BIN" --runtime-config "$RUNTIME_FILE" serve) ;; + adapter) + SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE" + --project "$PROJECT" + --profile "$JOURNEY_ROOT/products/adapter/profiles/breg-records/profile.yaml" + --pack "$PROJECT/pack.yaml") + ;; render) SERVE_COMMAND=("$SERVER_BIN" serve --runtime-config "$RUNTIME_FILE") ;; *) journey_harness_failure "no start recipe is written for $product; add one to recipe in promote.sh" ;; esac @@ -263,44 +285,56 @@ port_is_free() { # attempt has an answer, so a refused start is an observation. # shellcheck disable=SC2329 # run through journey_step production_start() { - local pid attempt=0 state='' + local stop_grace=$1 pid deadline interrupted=0 state='' + # Record signals even between starting the server and saving its PID. + # This watched shell owns the child until it has reaped it. + trap 'interrupted=129' HUP + trap 'interrupted=130' INT + trap 'interrupted=143' TERM "${SERVE_COMMAND[@]}" & pid=$! - while ((attempt < 60)); do - if ! kill -0 "$pid" 2>/dev/null; then + deadline=$((SECONDS + 30)) + while ((interrupted == 0 && SECONDS < deadline)); do + if ! journey__process_alive "$pid"; then state=refused break fi - if curl --silent --fail --output /dev/null "http://127.0.0.1:$PORT$READY_PATH"; then + if curl --silent --fail --max-time 1 --output /dev/null "http://127.0.0.1:$PORT$READY_PATH"; then state=started break fi sleep 0.5 - attempt=$((attempt + 1)) done - if [[ -z "$state" ]]; then - printf 'the product neither answered %s nor exited within 30 seconds\n' "$READY_PATH" >&2 - kill -TERM "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true - return 1 - fi if [[ "$state" == refused ]]; then wait "$pid" 2>/dev/null || printf 'the product exited with status %s\n' "$?" >&2 else - kill -TERM "$pid" - for attempt in $(seq 1 100); do - kill -0 "$pid" 2>/dev/null || break - sleep 0.1 + while :; do + journey__terminate "$pid" "$stop_grace" + # A trapped signal can interrupt wait before the child exits. + journey__process_alive "$pid" || break done - if kill -0 "$pid" 2>/dev/null; then - kill -KILL "$pid" + # shellcheck disable=SC2154 # journey__terminate sets this status. + if [[ $_journey_terminate_killed -eq 1 ]]; then printf 'the product ignored SIGTERM and was killed\n' >&2 + return "$((interrupted == 0 ? 1 : interrupted))" fi - wait "$pid" 2>/dev/null || true + fi + ((interrupted == 0)) || return "$interrupted" + if [[ -z "$state" ]]; then + printf 'the product neither answered %s nor exited within 30 seconds\n' "$READY_PATH" >&2 + return 1 fi printf '%s\n' "$state" >"$STATE_FILE" } +observe_production_start() { + local stop_grace=$JOURNEY_KILL_GRACE + # Leave the wrapper enough time to finish a readiness probe, then stop + # and reap the server before its own watchdog can escalate. + local JOURNEY_KILL_GRACE=$((stop_grace + 4)) + journey_step start-as-production --timeout 90 --typed "${SERVE_COMMAND[*]##*/}" -- production_start "$stop_grace" +} + # production_check: the production check, whatever it answers. Its exit status # goes to stderr; its report is the step's stdout. # shellcheck disable=SC2329 # run through journey_step @@ -310,6 +344,20 @@ production_check() { printf 'check exit status %s\n' "$status" >&2 } +adapter_check_envelope() { + jq -e -s --arg exit "$2" ' + ({"0":"complete","1":"domain-refusal","2":"usage-error","3":"operational-failure"}[$exit]) as $status | + length == 1 and (.[0] | + type == "object" and + .apiVersion == "id.registrystack.org/formats/adapter/ctl-report/v1alpha1" and + .kind == "AdapterCtlReport" and .command == "check" and + $status != null and .status == $status and .ok == ($exit == "0") and + (.diagnostics | type == "array" and ($exit == "0" or length > 0) and + all(.[]; type == "object" and (.code | type == "string" and length > 0) and + (.message | type == "string") and + ($exit == "0" or (.suggestedAction | type == "string" and length > 0)))))' "$1" >/dev/null 2>&1 +} + # The stock own-provider paths for these products use narrow loopback transport # and explicit clients, both permitted in production. Any actual refusal still # takes the remediation path, even for these products. @@ -319,7 +367,7 @@ production_outcome() { printf '%s\n' remediate elif [[ "$state" == started && "$status" == 0 && -z "$codes" ]]; then case "$product" in - casework | messaging | scheduling | documents | coordinator) printf '%s\n' compatible ;; + casework | messaging | scheduling | documents | coordinator | render | adapter) printf '%s\n' compatible ;; *) printf '%s\n' missing-refusal ;; esac else @@ -379,6 +427,16 @@ call_recipe() { CLIENT="coordinator-producer" CALL_PATH=/v1/workflows/coordinator ;; + adapter) + CLIENT=registry-adapter-example-client + CALL_METHOD=POST + CALL_PATH=/v1/records/person + [[ -f "$FROM/work/adapter/adapter-call-body.json" ]] || + journey_harness_failure "the Adapter input holds no request body" + CALL_OPTIONS=(--header 'Content-Type: application/json' + --header 'Idempotency-Key: journey-adapter-first-call' + --data-file "$FROM/work/adapter/adapter-call-body.json") + ;; render) CLIENT="portal" CALL_METHOD=POST @@ -463,7 +521,7 @@ promote_call_failure() { } walk_product() { - local product=$1 tier outcome count code dev_claims dev_contract check_status production_case + local product=$1 tier outcome count=0 code dev_claims dev_contract check_status production_case journey_product_field "$product" tier tier CELL=$product journey_cell_begin "$product" @@ -476,7 +534,23 @@ walk_product() { # input input_outcome "$product" outcome if [[ "$outcome" != finished ]]; then - printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 + case "$outcome" in + fixture-only | legacy-unmarked | invalid-fixture-marker) + # An explicitly kept fixture still needs cleanup when no cell can use it. + if [[ -f "$FROM/kept" ]]; then + take_over_input + fi + if [[ "$outcome" == fixture-only ]]; then + printf 'promote: %s %s input refused (fixture-only). This fixture is scoped to own-provider verification\n' "$INPUT_JOURNEY" "$product" >&2 + else + printf 'promote: %s %s input refused (%s). Use the current own-provider runner to record the BReg fixture marker\n' \ + "$INPUT_JOURNEY" "$product" "$outcome" >&2 + fi + ;; + *) + printf 'promote: the %s journey did not finish for %s (cell outcome %s); nothing to promote\n' "$INPUT_JOURNEY" "$product" "$outcome" >&2 + ;; + esac journey_fail input journey.promote.no-input journey_cell_end return 0 @@ -490,7 +564,7 @@ walk_product() { # start-as-production STATE_FILE=$JOURNEY_OUT/$product/production-start.state port_is_free "$PORT" || journey_harness_failure "port $PORT is in use; promote cannot start $product on it" - journey_step start-as-production --timeout 90 --typed "${SERVE_COMMAND[*]##*/}" -- production_start || + observe_production_start || journey_harness_failure "the start of $product neither answered nor exited; see $JOURNEY_STEP_STDERR" [[ -f "$STATE_FILE" ]] || journey_harness_failure "the start attempt of $product left no state; see $JOURNEY_STEP_STDERR" START_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") @@ -505,30 +579,33 @@ walk_product() { # refusals journey_step refusals --typed "${CHECK_COMMAND[*]##*/}" -- production_check || journey_harness_failure "the production check of $product did not run; see $JOURNEY_STEP_STDERR" - CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") + check_status=$(sed -n 's/^check exit status \([0-9][0-9]*\)$/\1/p' "$JOURNEY_STEP_STDERR") + if [[ "$product" == adapter ]]; then + adapter_check_envelope "$JOURNEY_STEP_STDOUT" "$check_status" || + journey_harness_failure "Adapter production check report must be one check envelope matching its exit status; see $JOURNEY_STEP_STDOUT" + CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT") + else + CHECK_CODES=$(diagnostic_codes "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR") + fi if [[ "$CHECK_CODES" != "$START_CODES" ]]; then journey_harness_failure "the production check of $product lists [${CHECK_CODES//$'\n'/ }] and its start lists [${START_CODES//$'\n'/ }]; the two lists must be equal (see $JOURNEY_STEP_STDOUT)" fi - check_status=$(sed -n 's/^check exit status \([0-9][0-9]*\)$/\1/p' "$JOURNEY_STEP_STDERR") production_case=$(production_outcome "$product" "$(<"$STATE_FILE")" "$check_status" "$CHECK_CODES") case "$production_case" in invalid) journey_harness_failure "the production check of $product returned status $check_status for diagnostic codes [$CHECK_CODES]; see $JOURNEY_STEP_STDERR" ;; - missing-refusal) - journey_fail refusals journey.promote.nothing-refused - journey_cell_end - return 0 - ;; - compatible) - count=0 - printf 'promote: %s passed the production check with zero diagnostics; no remediation required\n' "$product" - ;; remediate) count=$(printf '%s\n' "$CHECK_CODES" | wc -l | tr -d ' ') ;; esac - journey_count refusals "$count" + journey_count production-refusals "$count" + printf 'promote: %s measured %s production refusal(s)\n' "$product" "$count" + if [[ "$production_case" == missing-refusal ]]; then + journey_fail refusals journey.promote.nothing-refused + journey_cell_end + return 0 + fi journey_pass refusals # fix: first the contract as the development files give it (the claim names @@ -545,6 +622,9 @@ walk_product() { elif [[ "$production_case" == compatible ]]; then journey_harness_failure "the production-compatible case for $product requires the original development request and claim names; rerun own-provider" fi + if [[ "$product" == adapter && ! -s "$recorded/call.response" ]]; then + journey_harness_failure "Adapter promotion requires the recorded development response; rerun own-provider" + fi if [[ "$production_case" == remediate ]]; then while IFS= read -r code; do apply_fix "$code" @@ -586,6 +666,12 @@ walk_product() { journey_harness_failure "the token claims of $product differ between the development files and the production start" fi [[ "$(journey_request_contract "$CALL_METHOD" "$CALL_PATH" "${CALL_OPTIONS[@]+"${CALL_OPTIONS[@]}"}")" == "$dev_contract" ]] || journey_harness_failure "the request of $product changed between the development files and the production start" + if [[ "$product" == adapter ]]; then + [[ "$JOURNEY_HTTP_STATUS" == 201 ]] || + journey_harness_failure "the promoted Adapter returned HTTP $JOURNEY_HTTP_STATUS instead of 201" + cmp -s -- "$recorded/call.response" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the promoted Adapter response differs from the development response" + fi journey_stop same-contract server || journey_harness_failure "the server of $product ignored SIGTERM" journey_pass same-contract journey_cell_end diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index 215fafa518..a9a9a8b442 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -21,13 +21,40 @@ # Run it from anywhere: # products/platform/journeys/rstack-dev.sh --bin-dir DIR [--product ID]... # [--out DIR] [--expected FILE [--strict]] [--keep] +# Use --product breg --attachments compose for the sibling receiver and +# unpublished private PostgreSQL attachment proof. +# Use --product casework --planted-error casework-missing-scope for the +# disposable scope diagnostic probe after T1. set -euo pipefail # shellcheck disable=SC1091 # lib.sh is checked on its own source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" -journey_init rstack-dev -- "$@" +journey_init rstack-dev --value-option attachments --value-option planted-error -- "$@" +journey_option_value planted-error RSTACK_PLANTED_ERROR +case "$RSTACK_PLANTED_ERROR" in +'') ;; +casework-missing-scope) + [[ "${JOURNEY_PRODUCTS[*]}" == casework && "$JOURNEY_KEEP" == 0 ]] || + journey_usage_error "--planted-error casework-missing-scope requires --product casework and no --keep" + ;; +*) journey_usage_error "--planted-error $RSTACK_PLANTED_ERROR: choose casework-missing-scope" ;; +esac +journey_option_value attachments RSTACK_ATTACHMENTS +RSTACK_ATTACHMENTS=${RSTACK_ATTACHMENTS:-loopback} +case "$RSTACK_ATTACHMENTS" in +loopback) ;; +compose) + [[ "${JOURNEY_PRODUCTS[*]}" == breg && "$JOURNEY_KEEP" == 0 ]] || + journey_usage_error "--attachments compose requires --product breg and no --keep" + docker compose version >/dev/null || journey_usage_error "--attachments compose requires Docker Compose" + # shellcheck source=/dev/null # The opt-in fixture shares this runner's lifecycle. + source "$JOURNEY_LIB_DIR/projects/rstack-attachments.sh" + journey_at_cleanup stop_compose_attachments + ;; +*) journey_usage_error "--attachments $RSTACK_ATTACHMENTS: choose loopback or compose" ;; +esac journey_require_docker # The tools every selected product's init needs, and rstack itself. @@ -50,6 +77,8 @@ for name in breg casework evidence messaging scheduling documents coordinator ad export "RSTACK_${upper}CTL_BIN=$JOURNEY_BIN_DIR/${name}ctl" done export RSTACK_RENDER_BIN=$JOURNEY_BIN_DIR/registry-render +# Evidence's authoring CLI invokes the runtime when checking the selected target. +export EVIDENCE_BIN=$JOURNEY_BIN_DIR/evidence # Runs this script started and has not yet stopped, one id per line. LIVE_RUNS='' @@ -187,13 +216,19 @@ init_command() { # allows, so a refusal is about the product and not about the plan's other # parts. write_probe_plan() { - local product=$1 project=$2 + local product=$1 project=$2 inventory + case "$product" in + breg | coordinator | evidence) inventory="{projects: {$product: {path: .}}}" ;; + *) inventory="{path: .}" ;; + esac journey_write_file "$project/dev.yaml" --concepts development-plan,issuer-name,audience <>"$target" + sed -n '/^hooks:$/,$p' "$starter" >>"$target" + fi +} + # The Adapter starter writes two effects to an authored reference endpoint. # Speak the documented fixture's two replies over a disposable local socket. start_adapter_source() { @@ -386,9 +433,11 @@ write_keep() { field='.requestId' ;; messaging) - KEEP_PATH=/v1/messages/$message_id - KEEP_EXPECT=$message_id - return + path=/v1/messages + body=$CALL_BODY + field='.id' + options+=(--expect-status 202 + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-keep' --json '$body' $url$path") ;; scheduling) local config @@ -399,11 +448,6 @@ write_keep() { KEEP_EXPECT=retained-counter return ;; - documents) - path=/v1/documents - body='{"policyId":"institutional-custody","expectedDigest":"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","length":1,"mediaType":"application/pdf","label":"Retained document","custodian":{"subject":"starter-citizen"}}' - field='.document.id' - ;; coordinator) path=/v1/runs send_after=$(python3 -c 'from datetime import datetime, timedelta, timezone; print((datetime.now(timezone.utc) + timedelta(days=1)).isoformat(timespec="seconds"))') @@ -424,20 +468,23 @@ write_keep() { [[ "$product" != casework ]] || write_path="$path?accessProfile=requester" journey_http "$step" "${options[@]}" --data-file "$work/keep-body.json" --capture "$field" saved_id "$method" "$url$write_path" || unexpected_answer "$step" case "$product" in - breg | documents | coordinator) KEEP_PATH=$path/$saved_id ;; + breg | coordinator | messaging) KEEP_PATH=$path/$saved_id ;; casework) KEEP_PATH=$path/$saved_id ;; adapter) KEEP_PATH=$path ;; esac KEEP_EXPECT=$saved_id + if [[ "$product" == messaging && "$saved_id" == "$message_id" ]]; then + journey_harness_failure "the retention send did not create a distinct message" + fi } # start_run STEP PROJECT: `rstack dev start` on PROJECT as part of STEP. Sets # RUN, BASE_URL and START_FILE (the report) on success. Returns the command's # status; the caller records the outcome. start_run() { - local step=$1 project=$2 status=0 - journey_step "$step" --timeout 240 --concepts run-id-and-ttl,journey-file \ - --typed "rstack dev start $project" -- rstack_dev start "$project" || status=$? + local step=$1 project=$2 status=0 project_arg=./${2##*/} + journey_step "$step" --cwd "${project%/*}" --timeout 240 --concepts run-id-and-ttl,journey-file \ + --typed "rstack dev start $project_arg" -- rstack_dev start "$project_arg" || status=$? START_FILE=$JOURNEY_STEP_STDOUT if [[ $status -eq 0 ]]; then RUN=$(jq -er '.run_id' "$START_FILE") || journey_harness_failure "the start report of $CELL names no run id; see $START_FILE" @@ -468,6 +515,43 @@ issue_token() { journey_secret_register "token-$variable" "$variable" } +# Scope fixtures share an inert scope so both signed tokens remain access +# tokens. Their only authorization difference is the required staff scope. +prepare_casework_scope_probe() { + perl -0pi -e ' + my $entry = qr/^ staff:\n((?:^ {4}[^\n]*\n)+)/m; + !/^ staff-missing-scope:/m && /$entry/ or die "expected a generated staff plan entry\n"; + my $staff = $1; + my $control = $staff; + my $required = " - casework:staff\n"; + my $shared = " - casework:diagnostic-control\n"; + $control =~ s/^\Q$required\E/$shared/m or die "generated staff scope is missing\n"; + $staff =~ s/^\Q$required\E/$required$shared/m or die "generated staff scope is missing\n"; + s/$entry/ staff:\n$staff staff-missing-scope:\n$control/; + ' "$1" +} + +record_casework_scope_probe() { + # shellcheck disable=SC2034 # issue_token and --bearer use control by name. + local run=$1 url=$2 path=$3 work=$4 control='' trace + issue_token call "$run" staff-missing-scope control || + journey_harness_failure "cannot issue the Casework missing-scope control" + journey_http call --expect-status 403 --bearer control GET "$url$path" || + journey_harness_failure "Casework did not refuse the missing-scope control with HTTP 403" + journey_count errors-that-say-what-to-change 0 + trace=$(jq -er 'select(.code == "profile.not-authorized" and .failedCheck == "scope") + | .traceId | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || return 0 + # shellcheck disable=SC2016 # jq binds $trace. + if journey_poll 5 -- jq -Rse --arg trace "$trace" ' + first(split("\n")[] | fromjson? | .fields | + select(.trace_id == $trace and .failed_check == "scope" + and .scope_claim == "scope" and .required_scope == "casework:staff") | + {trace_id, failed_check, scope_claim, required_scope})' \ + "$STATE_DIR/$run/logs/casework-runtime.log" >"$work/casework-scope-diagnostic.json"; then + journey_count errors-that-say-what-to-change + fi +} + # unexpected_answer STEP: the call answered with a status this journey has no # code for. It is a harness failure so that a new kind of refusal is looked at # and named, never recorded under a code the product did not print. @@ -479,6 +563,7 @@ unexpected_answer() { walk_product() { # shellcheck disable=SC2034 # token and token2 are set by name through issue_token local product=$1 work project tier plan_capable status=0 url message_id='' token='' token2='' workflow_revision='' uses_postgres + local first_read=0 documents_receipt='' standalone_plan_check=0 journey_product_field "$product" tier tier journey_product_field "$product" rstackDevPlan plan_capable journey_product_field "$product" usesPostgres uses_postgres @@ -493,8 +578,8 @@ walk_product() { project=$work/project # init: the product's own init. - init_command "$product" "$project" - journey_step init --concepts project -- "${INIT_COMMAND[@]}" || status=$? + init_command "$product" ./project + journey_step init --cwd "$work" --concepts project -- "${INIT_COMMAND[@]}" || status=$? if [[ $status -ne 0 ]]; then fail_with_product_code init "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" journey_cell_end @@ -502,31 +587,42 @@ walk_product() { fi journey_pass init - # plan: `rstack dev check` on the project init wrote. A product that init - # gave no plan for, and that the plan format cannot name, is given the plan - # a reader would write first. + # A generated plan is validated by start. Products without a supported + # starter still need a separate check to report what stops the reader. if [[ ! -f "$project/dev.yaml" && "$plan_capable" != true ]]; then write_probe_plan "$product" "$project" fi - journey_step plan --concepts development-plan --typed "rstack dev check $project" -- rstack_dev check "$project" || status=$? - if [[ $status -ne 0 ]]; then - if [[ ! -f "$project/dev.yaml" ]]; then - journey_needs plan hand-written-plan - else - fail_with_product_code plan "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" + if [[ ! -f "$project/dev.yaml" || "$plan_capable" != true ]]; then + standalone_plan_check=1 + journey_step plan --concepts development-plan --typed "rstack dev check $project" -- rstack_dev check "$project" || status=$? + if [[ $status -ne 0 ]]; then + if [[ ! -f "$project/dev.yaml" ]]; then + journey_needs plan hand-written-plan + else + fail_with_product_code plan "$JOURNEY_STEP_STDOUT" "$JOURNEY_STEP_STDERR" + fi + journey_cell_end + return 0 fi - journey_cell_end - return 0 + journey_pass plan fi - journey_pass plan # start: one command, after supplying the optional fixture endpoints. case "$product" in - breg) add_contact_hook "$project" ;; + breg) + add_contact_hook "$project" + [[ "$RSTACK_ATTACHMENTS" != compose ]] || prepare_compose_attachments "$project" "$work" + ;; + documents) add_documents_hooks "$project" ;; casework) - # Use the generated test person's issuer for the starter's - # trusted producer on this disposable project. - perl -pi -e 's@^ issuer: http://127[.]0[.]0[.]1:8093$@ issuer: https://identity.casework.example.test@' "$project/casework.yaml" + # Released starters can still name the old loopback issuer. + if grep -Fxq ' issuer: http://127.0.0.1:8093' "$project/casework.yaml"; then + perl -pi -e 's@^ issuer: http://127[.]0[.]0[.]1:8093$@ issuer: https://identity.casework.example.test@' "$project/casework.yaml" + fi + if [[ "${RSTACK_PLANTED_ERROR:-}" == casework-missing-scope ]]; then + prepare_casework_scope_probe "$project/dev.yaml" || + journey_harness_failure "cannot prepare the Casework missing-scope control" + fi ;; adapter) start_adapter_source "$project" "$work" ;; evidence) start_evidence_source "$project" ;; @@ -541,27 +637,28 @@ walk_product() { if ! jq -e 'all(.scenarios[]; .result == "passed")' "$START_FILE" >/dev/null; then journey_harness_failure "the start report of $product holds a journey that did not pass; see $START_FILE" fi + [[ $standalone_plan_check -eq 1 ]] || journey_pass plan journey_pass start local run=$RUN url=$(run_url "$product") recipe "$product" - # issuer: the issuer the run gave the product, read from the runtime file - # the report names. + # Check the issuer the runner generated before sending the request. The + # reader uses the header file from `dev token` directly. local runtime_file runtime_file=$(jq -er --arg product "$product" '.runtimeConfigs[$product]' "$START_FILE") || journey_harness_failure "the start report names no runtime file for $product" if [[ "$product" == evidence ]]; then - journey_step issuer --concepts issuer-url,jwks-uri,audience,allowed-clients,scope-claim -- \ - "$JOURNEY_BIN_DIR/evidence" check --posture development --runtime-config "$runtime_file" --format json + # Start already checks the Evidence target, activates its authority and + # runs the authenticated scenario against the generated YAML configuration. + [[ -s "$runtime_file" ]] || journey_harness_failure "the checked Evidence runtime file is missing or empty" elif [[ "$product" == discovery ]]; then printf '%s\n' "Discovery's public index has no issuer." else - journey_step issuer --concepts issuer-url,jwks-uri,audience,allowed-clients,scope-claim \ - --typed "jq read issuer settings $runtime_file" -- \ - jq -e '(.authentication.oidc // .deployment.authentication // .oidc).issuers + jq -e '(.authentication.oidc // .deployment.authentication // .oidc).issuers | select(type == "object" and length > 0) - | map_values({issuer, audience, allowedClients, scopeClaim, jwksSource: .jwksSource.type})' "$runtime_file" || + | map_values({issuer, audience, allowedClients, scopeClaim, jwksSource: .jwksSource.type})' \ + "$runtime_file" >"$work/issuer.json" || journey_harness_failure "cannot read the issuer of $product from $runtime_file" fi journey_pass issuer @@ -586,30 +683,64 @@ walk_product() { case "$product" in coordinator) call_options+=(--capture '.workflowRevision' workflow_revision) ;; casework) CALL_PATH+='?accessProfile=staff' ;; + messaging) + # Start already submitted the exact starter request. The receipt route + # uses its original request and key and does not submit another message. + printf '%s\n' "$CALL_BODY" >"$work/call-body.json" + call_options+=(--expect-status 200 --header 'Content-Type: application/json' --header 'Idempotency-Key: send-a-reminder-sms' + --data-file "$work/call-body.json" --capture '.id | strings | select(length > 0)' message_id --concepts idempotency-key + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:send-a-reminder-sms' --json '$CALL_BODY' $url$CALL_PATH") + ;; esac - if [[ -n "$CALL_BODY" ]]; then - printf '%s\n' "$CALL_BODY" | journey_write_file "$work/call-body.json" - call_options+=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-first-call' --data-file "$work/call-body.json" --capture '.id' message_id) - fi journey_http call "${call_options[@]}" "$CALL_METHOD" "$url$CALL_PATH" || status=$? if [[ $status -ne 0 ]]; then unexpected_answer call fi + if [[ "$product" == messaging ]]; then + jq -e --arg id "$message_id" '.links.self == ("/v1/messages/" + $id)' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the starter message receipt did not identify its retained message" + fi + if [[ "$product" == messaging || ("$CALL_METHOD" == GET && -n "$PERSON") ]]; then + journey_reached t1 + first_read=1 + fi + if [[ "$product" == casework && "${RSTACK_PLANTED_ERROR:-}" == casework-missing-scope ]]; then + record_casework_scope_probe "$run" "$url" "$CALL_PATH" "$work" + fi journey_pass call - journey_reached t1 - # hook: BReg's keep write also triggers its local sink. - if [[ "$product" == breg ]]; then + # The BReg and Documents writes also test retention after restart. + case "$product" in + breg) local sink write_keep "$product" "$work" "$project" "$url" "$run" - sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") - journey_poll 30 -- hook_received "$sink" "A retained contact" - journey_http hook GET "$sink" || unexpected_answer hook - fi - journey_pass hook + if [[ "$RSTACK_ATTACHMENTS" == compose ]]; then + verify_sibling_hook "$KEEP_EXPECT" managed + else + sink=$(jq -er '.bregHookSink.receivedUrl' "$START_FILE") + journey_poll 30 -- hook_received "$sink" "$KEEP_EXPECT" || + journey_harness_failure "the BReg hook sink did not receive the retained contact's creation event" + journey_http hook GET "$sink" || unexpected_answer hook + breg_hook_matches "$KEEP_EXPECT" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the BReg hook receipt does not contain the retained contact's creation event" + fi + journey_pass hook + ;; + documents) + documents_ready_hook "$work" "$url" token documents_receipt + journey_pass hook + ;; + scheduling) + # The named reader has catalogue access. Booking needs an exchanged task + # grant and a trusted assertion issuer binding on the managed runtime. + printf '%s\n' 'Scheduling appointment observer needs a verified task grant and its assertion issuer binding.' + journey_unexercised hook + ;; + *) journey_unexercised hook ;; + esac if [[ "$uses_postgres" == true ]]; then - if [[ "$product" != breg ]]; then + if [[ "$product" != breg && "$product" != documents ]]; then write_keep "$product" "$work" "$project" "$url" "$run" fi local audit='' first_start_file=$START_FILE @@ -661,10 +792,25 @@ walk_product() { fi jq -e --arg expected "$KEEP_EXPECT" '[.. | strings] | index($expected) != null' "$JOURNEY_STEP_STDOUT" >/dev/null || journey_harness_failure "the retained $product response did not contain the written record" - journey_reached t2 + if [[ "$product" == documents ]]; then + documents_ready_matches "$documents_receipt" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the retained document no longer identifies the ready version" + fi + if [[ "$product" == messaging ]]; then + jq -e --arg id "$KEEP_EXPECT" '.id == $id' "$JOURNEY_STEP_STDOUT" >/dev/null || + journey_harness_failure "the retained read did not return the distinct message sent before restart" + fi + if [[ "$method" == GET && $first_read -eq 0 ]]; then + journey_reached t1 + fi if [[ -n "$audit" ]]; then journey_step keep -- audit_was_appended "$work/audit-before-restart.jsonl" "$audit" fi + # These paths have written and read back a record across a restart. + # BReg and Documents also delivered an observer hook before the restart. + case "$product" in + breg | coordinator | documents | messaging) journey_reached t2 ;; + esac else printf '%s\n' "$product has no PostgreSQL state to retain." fi @@ -672,7 +818,11 @@ walk_product() { # attach: only products with a database accept a PostgreSQL server. if [[ "$uses_postgres" == true ]]; then - attach_database "$project" || status=$? + if [[ "$RSTACK_ATTACHMENTS" == compose ]]; then + attach_compose_database "$project" "$work" || status=$? + else + attach_database "$project" || status=$? + fi if [[ $status -ne 0 ]]; then stop_live_runs journey_cell_end @@ -691,6 +841,7 @@ walk_product() { journey_poll 30 -- state_is_empty || journey_harness_failure "the state of run $last did not go after its stop" journey_check_absent "$(run_containers "$last" | head -n 1)" "$(run_containers "$last" | tail -n 1)" || journey_harness_failure "a container of run $last remains after its stop" + [[ "$RSTACK_ATTACHMENTS" != compose ]] || verify_compose_services_running journey_pass stop [[ "$product" != evidence ]] || stop_evidence_source journey_cell_end @@ -737,8 +888,76 @@ assert all(json.loads(line)["eventId"] for line in after[len(before):].splitline PYAUDIT } +# breg_hook_matches RECORD_ID [FILE]: find the exact creation event in the +# sink's capture. Without FILE, read the current poll response from stdin. +breg_hook_matches() { + local record_id=$1 + shift + jq -e --arg record "$record_id" 'any(.[] | .body | fromjson?; + .type == "contact-created" and .data.recordId == $record and + .data.values.name == "A retained contact")' "$@" >/dev/null +} + hook_received() { - curl --silent --fail --max-time 3 "$1" | jq -e --arg name "$2" 'any(.[] | .body | fromjson? | .. | strings; . == $name)' >/dev/null + curl --silent --fail --max-time 3 "$1" | breg_hook_matches "$2" +} + +managed_hook_url() { + local product=$1 value + value=$(jq -er --arg product "$product" '.hookSinks[$product].receivedUrl | strings | select(length > 0)' "$START_FILE") || + journey_harness_failure "the local $product run did not report its hook sink" + printf -v "$2" '%s' "$value" +} + +check_managed_hook() { + local product=$1 sink=$2 expected=$3 + journey_poll 45 -- signed_hook_received "$sink" "$expected" || + journey_harness_failure "the local $product hook sink did not receive the expected event" + journey_http hook GET "$sink" || unexpected_answer hook + signed_hook_matches "$expected" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the local $product hook receipt did not contain the expected event" +} + +documents_ready_matches() { + jq -e --argjson event "$1" ' + .id == $event.data.documentId and .version.id == $event.data.versionId and + .version.expectedDigest == $event.data.versionDigest and .version.status == "ready"' "$2" >/dev/null +} + +# Reserve and upload the synthetic PDF, then read the same ready version. +# Leave its path and ID for the retained read rather than reserving a second document. +documents_ready_hook() { + local work=$1 origin=$2 bearer=$3 result=$4 + local pdf=$work/retained.pdf reserve=$work/document-reserve.json + local digest document='' version='' upload='' ready_event sink + managed_hook_url documents sink + journey_write_file "$pdf" < <(printf '%%PDF-1.7\n%%%%EOF\n') + digest=$(perl -MDigest::SHA -e 'print "sha256:", Digest::SHA->new(256)->addfile($ARGV[0], "b")->hexdigest' "$pdf") || + journey_harness_failure "cannot digest the synthetic document" + journey_write_file "$reserve" < <( + jq -cn --arg digest "$digest" --argjson length "$(wc -c <"$pdf")" \ + '{policyId:"institutional-custody", custodian:{subject:"starter-citizen"}, + expectedDigest:$digest, length:$length, mediaType:"application/pdf"}' + ) + journey_http hook --expect-status 201 --bearer "$bearer" --header 'Content-Type: application/json' \ + --header 'Idempotency-Key: journey-document-reservation' --data-file "$reserve" \ + --capture .uploadPath upload --capture .document.id document --capture .document.version.id version \ + POST "$origin/v1/documents" || unexpected_answer hook + [[ "$upload" =~ ^/v1/uploads/[0-9a-f-]+/content$ ]] || + journey_harness_failure "the document reservation returned an invalid upload path" + journey_http hook --expect-status 200 --bearer "$bearer" --header 'Content-Type: application/pdf' \ + --data-file "$pdf" PUT "$origin$upload" || unexpected_answer hook + ready_event=$(jq -cn --arg document "$document" --arg version "$version" --arg digest "$digest" \ + '{source:"urn:registrystack:documents:civil-registry-documents", type:"document-version-ready", + data:{documentId:$document, versionId:$version, versionDigest:$digest, policyId:"institutional-custody", policyVersion:"1"}}') + check_managed_hook documents "$sink" "$ready_event" + KEEP_PERSON=$PERSON + KEEP_PATH=/v1/documents/$document + KEEP_EXPECT=$document + journey_http hook --expect-status 200 --bearer "$bearer" GET "$origin$KEEP_PATH" || unexpected_answer hook + documents_ready_matches "$ready_event" "$JOURNEY_STEP_STDOUT" || + journey_harness_failure "the document read did not return the exact ready version from the hook" + printf -v "$result" '%s' "$ready_event" } # attach_database PROJECT: start PROJECT against a PostgreSQL server the reader diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 50d1a89fcb..205ed2ad4c 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -18,6 +18,7 @@ import json import os import re +import signal import subprocess import tempfile import time @@ -186,6 +187,59 @@ def test_scheduling_rejects_missing_proof_even_when_stop_passes(self): self.assertIn(diagnostic, result.stdout + result.stderr) self.assertEqual("cell ended" in result.stdout, code == 0) + def test_book_and_confirm_use_the_same_named_grant(self): + driver = r""" +source "$1/lib.sh" +scratch=$2 mode=$3 +appointment='' +printf '%s\n' '{"offering":"application-review"}' >"$scratch/hold-request.json" +journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } +journey_http() { + [[ "$1 $2 $3 $4 $5" == 'hook --expect-status 201 --bearer approved_booking' ]] + local request_file capture + while [[ $# -gt 2 ]]; do + case "$1" in + --data-file) request_file=$2; shift 2 ;; + --capture) capture=$3; shift 3 ;; + *) shift ;; + esac + done + [[ "$1" == POST ]] + case "$2" in + http://127.0.0.1:49192/v1/holds) + [[ "$request_file" == "$scratch/hold-request.json" ]] + printf '%s\n' 'hold requested' + if [[ "$mode" == refuse ]]; then + JOURNEY_HTTP_STATUS=403 JOURNEY_HTTP_PROBLEM_CODE=operation.not-authorized + return 1 + fi + printf -v "$capture" '%s' held-id + ;; + http://127.0.0.1:49192/v1/appointments) + jq -e '. == {hold:"held-id",admission:null}' "$request_file" >/dev/null + printf '%s\n' 'appointment confirmed' + printf -v "$capture" '%s' confirmed-id + ;; + *) return 1 ;; + esac +} +journey_scheduling_appointment http://127.0.0.1:49192 "$scratch" "$scratch/hold-request.json" approved_booking appointment +printf '%s\n' "$appointment" +""" + for mode, code, steps in ( + ("approve", 0, ["hold requested", "appointment confirmed", "confirmed-id"]), + ("refuse", 3, ["hold requested"]), + ): + with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", driver, "scheduling-booking", str(TABLES), directory, mode], + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, code, result.stderr) + self.assertEqual(result.stdout.splitlines(), steps) + if mode == "refuse": + self.assertIn("HTTP 403, operation.not-authorized", result.stderr) + class PassRule(unittest.TestCase): @classmethod @@ -352,6 +406,45 @@ def test_realm_import_has_no_protocol_mappers(self): class KeycloakRecipe(unittest.TestCase): + def test_breg_refusal_requires_the_control_trace(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + function = re.search(r"^breg_claims_refused_at_trace\(\) \{\n.*?^\}\n", script, re.S | re.M) + self.assertIsNotNone(function) + trace = "01a2329737512fef4af31980675d47a2" + other = "01a23294626136512634d9f00f1cf6ee" + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "server.log" + for second_check, accepted in (("token-time", False), ("token-claims", True)): + records = [{"fields": {"trace_id": id_, "decision": "refused", "failed_check": check}} + for id_, check in ((other, "token-claims"), (trace, second_check))] + log.write_text("non-JSON output\n" + "\n".join(map(json.dumps, records)) + "\n", encoding="utf-8") + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", function.group(0) + '\nbreg_claims_refused_at_trace "$@"', + "breg-control-trace", trace, str(log)], capture_output=True, text=True, timeout=5, + ) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + + def test_breg_mappers_are_static_and_only_set_authored_claims(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + match = re.search(r"^breg_keycloak_mappers\(\) \{\n.*?^\}\n", script, re.S | re.M) + self.assertIsNotNone(match) + for principal, zone in (("synthetic-directory-editor", "zone-a"), + ("synthetic-foreign-editor", "zone-b")): + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", match.group(0) + '\nbreg_keycloak_mappers "$1" "$2"', + "breg-keycloak-mappers", principal, zone], capture_output=True, text=True, timeout=5, + ) + self.assertEqual(result.returncode, 0, result.stderr) + mappings = json.loads(result.stdout) + self.assertEqual({m["config"]["claim.name"]: m["config"]["claim.value"] for m in mappings}, + {"registry_principal": principal, "registry_purpose": "directory-administration", + "jurisdiction": zone}) + self.assertEqual(len(mappings), 3) + for mapper in mappings: + self.assertEqual(mapper["protocolMapper"], "oidc-hardcoded-claim-mapper") + self.assertEqual(mapper["config"]["access.token.claim"], "true") + self.assertEqual(mapper["config"]["jsonType.label"], "String") + def test_documents_realm_provisions_custodian_and_wrong_kind_service_clients(self): realm = json.loads((TABLES / "keycloak" / "realm.json").read_text(encoding="utf-8")) clients = {client["clientId"]: client for client in realm["clients"]} @@ -497,6 +590,35 @@ def test_change_in_request_bytes_changes_contract_without_exposing_body(self): class ProductionOutcome(unittest.TestCase): + def test_scoped_fixture_input_cannot_be_promoted(self): + script = (TABLES / "promote.sh").read_text(encoding="utf-8") + function = re.search(r"^input_outcome\(\) \{\n.*?^\}\n", script, re.S | re.M) + self.assertIsNotNone(function) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + (path / "summary.json").write_text(json.dumps({"cells": [ + {"product": product, "outcome": "pass"} for product in ("breg", "adapter") + ]}), encoding="utf-8") + provider = path / "own-provider.json" + cases = ( + (None, "legacy-unmarked"), + ({}, "legacy-unmarked"), + ({"fixtureOnlyProducts": ["breg"]}, "fixture-only"), + ({"fixtureOnlyProducts": []}, "invalid-fixture-marker"), + ({"fixtureOnlyProducts": "breg"}, "invalid-fixture-marker"), + ({"fixtureOnlyProducts": ["breg", 1]}, "invalid-fixture-marker"), + ({"fixtureOnlyProducts": None}, "invalid-fixture-marker"), + ) + for metadata, expected_breg in cases: + if metadata is not None: + provider.write_text(json.dumps(metadata), encoding="utf-8") + result = subprocess.check_output( + ["bash", "-euo", "pipefail", "-c", function.group(0) + '\nFROM=$1\n' + 'input_outcome breg breg; input_outcome adapter adapter; printf "%s\\n" "$breg" "$adapter"', + "promote-input", str(path)], text=True, timeout=5, + ) + self.assertEqual(result.splitlines(), [expected_breg, "finished"]) + def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self): script = (TABLES / "promote.sh").read_text(encoding="utf-8") function = re.search(r"^production_outcome\(\) \{\n.*?^\}\n", script, re.S | re.M) @@ -507,7 +629,12 @@ def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self) ("messaging", "started", 0, "", "compatible"), ("scheduling", "started", 0, "", "compatible"), ("coordinator", "started", 0, "", "compatible"), - ("render", "started", 0, "", "missing-refusal"), + ("render", "started", 0, "", "compatible"), + ("adapter", "started", 0, "", "compatible"), + ("adapter", "refused", 1, "config.refused", "remediate"), + ("adapter", "started", 1, "", "invalid"), + ("render", "refused", 1, "render.config.refused", "remediate"), + ("breg", "started", 0, "", "missing-refusal"), ("messaging", "started", 1, "", "invalid"), ("scheduling", "refused", 1, "", "invalid"), ("coordinator", "refused", 1, "config.dev-only", "remediate"), @@ -523,6 +650,164 @@ def test_zero_diagnostics_requires_a_successful_check_and_an_explicit_case(self) self.assertEqual(result.strip(), expected) +class AdapterPromotion(unittest.TestCase): + def run_promotion(self, mode, check_report="", check_exit=0, stubborn=False): + source = (TABLES / "promote.sh").read_text(encoding="utf-8") + start = source[source.index("# diagnostic_codes FILE"): + source.index("# FIX_TABLE:")] + walk = re.search(r"^walk_product\(\) \{\n.*?^\}\n", source, re.M | re.S) + self.assertIsNotNone(walk) + driver = r""" +source "$1/lib.sh" +journey_init promote -- --product adapter --out "$FIXTURE/run" +FROM=$FIXTURE/input +recorded=$FROM/work/adapter +mkdir -p "$recorded" +printf 'fixture response\n' >"$recorded/call.response" +printf 'fixture contract\n' >"$recorded/call.contract" +printf 'aud\n' >"$recorded/call.claims" +input_outcome() { printf -v "$2" finished; } +locate_input() { PORT=12345; READY_PATH=/ready; } +recipe() { SERVE_COMMAND=("$FIXTURE/adapter"); CHECK_COMMAND=(fixture_check); } +call_recipe() { CALL_METHOD=POST; CALL_PATH=/v1/records/person; CALL_OPTIONS=(); } +take_over_input() { :; } +curl() { [[ "$MODE" == check && -f "$FIXTURE/pid" ]]; } +fixture_check() { printf '%s' "$CHECK_REPORT"; return "$CHECK_EXIT"; } +fetch_token() { printf -v "$2" fixture; } +apply_fix() { [[ "$1" == adapter.config.invalid-fixture ]]; } +journey_claim_names() { printf 'aud\n'; } +journey_request_contract() { printf 'fixture contract\n'; } +journey_start() { :; } +journey_ready() { :; } +journey_http() { JOURNEY_HTTP_STATUS=201; JOURNEY_STEP_STDOUT=$recorded/call.response; } +journey_stop() { :; } +if [[ "$MODE" == timeout ]]; then + eval "$(declare -f journey__watchdog | sed '1s/journey__watchdog/fixture_watchdog/')" + journey__watchdog() { + [[ "$2" != 90 ]] || set -- "$1" 2 "$3" "$4" + fixture_watchdog "$@" + } +fi +""" + start + "\nport_is_free() { :; }\n" + walk.group(0) + "\nwalk_product adapter\njourney_finish\n" + adapter = r"""#!/usr/bin/env python3 +import os +import signal +import sys +import time +from pathlib import Path + +if os.environ["MODE"] == "refusal": + print("error[adapter.config.invalid-fixture] synthetic refusal", file=sys.stderr) + sys.exit(1) + +fixture = Path(os.environ["FIXTURE"]) + +def terminate(_signal, _frame): + (fixture / "term").touch() + if os.environ["STUBBORN"] != "1": + sys.exit(143) + +signal.signal(signal.SIGTERM, terminate) +(fixture / "pid.tmp").write_text(str(os.getpid())) +(fixture / "pid.tmp").rename(fixture / "pid") +time.sleep(8) +""" + with tempfile.TemporaryDirectory() as directory: + fixture = Path(directory) + executable = fixture / "adapter" + executable.write_text(adapter, encoding="utf-8") + executable.chmod(0o700) + with subprocess.Popen( + ["bash", "-euo", "pipefail", "-c", driver, "promote-adapter", str(TABLES)], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES), + "JOURNEY_KILL_GRACE": "1", "FIXTURE": directory, "MODE": mode, + "CHECK_REPORT": check_report, "CHECK_EXIT": str(check_exit), + "STUBBORN": str(int(stubborn))}, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True, + ) as process: + try: + pid_file = fixture / "pid" + if mode == "cancel": + deadline = time.monotonic() + 8 + while not pid_file.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + self.assertTrue(pid_file.exists(), "Adapter never reached startup") + process.terminate() + _, errors = process.communicate(timeout=14) + run = fixture / "run" + report = json.loads((run / "run.json").read_text(encoding="utf-8")) + if mode in ("timeout", "cancel"): + self.assertTrue(pid_file.exists(), errors) + status = subprocess.run( + ["ps", "-o", "stat=", "-p", pid_file.read_text()], + capture_output=True, text=True, + ).stdout.strip() + self.assertEqual( + ((fixture / "term").exists(), bool(status and not status.startswith("Z"))), + (True, False), errors, + ) + self.assertFalse((run / "adapter/production-start.state").exists()) + self.assertEqual(report["cleanup"]["failures"], [], errors) + summary = run / "summary.json" + return report, json.loads(summary.read_text()) if summary.exists() else None + finally: + # The group contains only the fixture, including an escaped + # fake Adapter when the runner under test is broken. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + self.assertIsNotNone(process.poll()) + + def test_startup_watchdog_stops_the_server(self): + report, _ = self.run_promotion("timeout") + self.assertEqual(report["exitStatus"], 3) + self.assertIn("did not finish within 90 seconds", report["harnessFailure"]) + + def test_cancellation_reaps_the_server_even_if_term_is_ignored(self): + report, _ = self.run_promotion("cancel", stubborn=True) + self.assertEqual(report["exitStatus"], 143) + + @staticmethod + def envelope(**fields): + return json.dumps({ + "apiVersion": "id.registrystack.org/formats/adapter/ctl-report/v1alpha1", + "kind": "AdapterCtlReport", "command": "check", "status": "complete", + "ok": True, "diagnostics": [], **fields, + }) + + def test_unmatched_check_envelope_fails_before_refusal_count(self): + valid = self.envelope() + cases = { + "blank": "", "malformed": '{"ok":', "two objects": valid + "\n" + valid, + "wrong command": self.envelope(command="provision"), + "wrong outcome": self.envelope(ok=False), + "wrong diagnostics": self.envelope(diagnostics={}), + "malformed diagnostic": self.envelope(diagnostics=[{"code": "bad", "message": 1}]), + } + for label, output in cases.items(): + with self.subTest(label=label): + report, summary = self.run_promotion("check", output) + self.assertEqual(report["exitStatus"], 3) + self.assertIn("Adapter production check report", report["harnessFailure"]) + self.assertIsNone(summary) + + def test_valid_check_counts_distinct_matched_refusals(self): + refusal = {"code": "adapter.config.invalid-fixture", "message": "synthetic refusal", + "suggestedAction": "Correct the fixture."} + cases = ( + ("check", self.envelope(), 0, 0), + ("refusal", self.envelope(ok=False, status="domain-refusal", + diagnostics=[refusal, refusal]), 1, 1), + ) + for mode, output, exit_status, count in cases: + with self.subTest(mode=mode): + report, summary = self.run_promotion(mode, output, check_exit=exit_status) + self.assertEqual(report["exitStatus"], 0, report["harnessFailure"]) + cell, = summary["cells"] + self.assertEqual(cell["productionRefusals"], count) + self.assertEqual(cell["total"]["refusalsMet"], count) + + class LoggedStage(unittest.TestCase): """`logged_stage` maps the last refusal line's `failed_check` label onto a stage word.""" @@ -829,6 +1114,595 @@ def test_promote_refuses_thunderid_run_directory(self): self.assertIn("keycloak", result.stderr) +class CaseworkProducerFixture(unittest.TestCase): + def test_planted_scope_counts_only_the_correlated_actionable_diagnostic(self): + source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + probe = re.search(r"^record_casework_scope_probe\(\) \{\n.*?^\}\n", source, re.M | re.S) + self.assertIsNotNone(probe) + driver = r""" +STATE_DIR=$1 +JOURNEY_STEP_STDOUT=$1/response.json +issue_token() { :; } +journey_http() { [[ "$*" == "call --expect-status 403 --bearer control GET http://localhost/read" ]]; } +journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } +journey_poll() { shift 2; "$@"; } +journey_count() { printf '%s\n' "${2:-1}"; } +record_casework_scope_probe sample http://localhost /read "$1" +""" + trace = "01a2333e0412314aaf6d6dbbe6fd98c0" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "response.json").write_text(json.dumps({ + "code": "profile.not-authorized", "failedCheck": "scope", "traceId": trace, + }), encoding="utf-8") + logs = root / "sample/logs" + logs.mkdir(parents=True) + for label, overrides, count in (("matching", {}, "0\n1"), ("other trace", {"trace_id": "other"}, "0"), + ("missing remedy", {"required_scope": ""}, "0")): + with self.subTest(label=label): + (logs / "casework-runtime.log").write_text(json.dumps({"fields": { + "trace_id": trace, "failed_check": "scope", "scope_claim": "scope", + "required_scope": "casework:staff", **overrides, + }}), encoding="utf-8") + result = subprocess.check_output( + ["bash", "-eu", "-c", probe.group(0) + driver, "casework-scope-count", directory], + text=True, timeout=5, + ) + self.assertEqual(result.strip(), count) + + def test_planted_scope_fixture_preserves_staff_authority_and_only_omits_required_scope(self): + source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + prepare = re.search(r"^prepare_casework_scope_probe\(\) \{\n.*?^\}\n", source, re.M | re.S) + self.assertIsNotNone(prepare) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "dev.yaml" + original = {"client": "staff", "subject": "staff", "grants": {"casework": { + "claims": {"registry_actor_kind": "human"}, "profile": "staff", "scopes": ["casework:staff"], + }}} + path.write_text(yaml.safe_dump({"people": {"staff": original, "supervisor": {"client": "supervisor"}}, + "products": [{"product": "casework"}]}), encoding="utf-8") + subprocess.run( + ["bash", "-eu", "-c", prepare.group(0) + '\nprepare_casework_scope_probe "$1"', + "casework-scope-probe", str(path)], check=True, timeout=5, + ) + people = yaml.safe_load(path.read_text(encoding="utf-8"))["people"] + staff, control = people["staff"], people["staff-missing-scope"] + scopes = staff["grants"]["casework"].pop("scopes") + control_scopes = control["grants"]["casework"].pop("scopes") + self.assertEqual(staff, control) + self.assertEqual(set(scopes) - set(control_scopes), {"casework:staff"}) + self.assertTrue(control_scopes and set(control_scopes) < set(scopes)) + self.assertEqual(people["supervisor"], {"client": "supervisor"}) + + def test_managed_starter_only_rewrites_the_released_issuer(self): + source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + start = source[source.index("# start: one command"):source.index("start_run start")] + case = re.search(r"^\tcasework\)\n(.*?)^\t\t;;", start, re.M | re.S) + self.assertIsNotNone(case) + legacy = "http://127.0.0.1:8093" + aligned = "https://identity.casework.example.test" + for issuer in (legacy, aligned): + with self.subTest(issuer=issuer), tempfile.TemporaryDirectory() as directory: + project = Path(directory) + policy = project / "casework.yaml" + policy.write_text(f" issuer: {issuer}\n subject: fixture-subject\n", encoding="utf-8") + inode = policy.stat().st_ino + subprocess.run( + ["bash", "-eu", "-c", 'project=$1\n' + case.group(1), "casework-starter", directory], + check=True, timeout=5, + ) + self.assertEqual(policy.read_text(), f" issuer: {aligned}\n subject: fixture-subject\n") + if issuer == aligned: + self.assertEqual(policy.stat().st_ino, inode) + + def test_binds_either_standalone_starter_issuer(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + functions = [] + for name in ("harness_edit", "bind_casework_producer"): + match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) + self.assertIsNotNone(match, name) + functions.append(match.group(0)) + driver = r""" +journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } +edit() { harness_edit "$1" "$2" "$3"; } +bind_casework_producer "$1" http://127.0.0.1:19000/realms/registry fixture-subject +""" + for issuer in ("http://127.0.0.1:8093", "https://identity.casework.example.test"): + with self.subTest(issuer=issuer), tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "casework.yaml" + path.write_text( + "trustedProducers:\n requester:\n profile: requester\n" + f" issuer: {issuer}\n subject: b75315b2-5854-70f3-8867-511dd771a6da\n" + " sourceNamespaces: [standalone]\n", encoding="utf-8", + ) + result = subprocess.run( + ["bash", "-eu", "-c", "\n".join(functions) + driver, "casework-producer", str(path)], + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(yaml.safe_load(path.read_text(encoding="utf-8"))["trustedProducers"]["requester"], { + "profile": "requester", "issuer": "http://127.0.0.1:19000/realms/registry", + "subject": "fixture-subject", "sourceNamespaces": ["standalone"], + }) + + +class LocalHookWalk(unittest.TestCase): + def walk(self, product, delivered): + script = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") + functions = [] + for name in ( + "walk_product", "recipe", "hook_received", "breg_hook_matches", + "managed_hook_url", "check_managed_hook", + "documents_ready_hook", "documents_ready_matches", + ): + match = re.search(rf"^{name}\(\) \{{\n.*?^\}}\n", script, re.M | re.S) + self.assertIsNotNone(match, name) + functions.append(match.group(0)) + driver = r""" +source "$1/lib.sh" +scratch=$2 product=$3 delivered=$4 +trace=$scratch/trace +LIVE_RUNS='' +RSTACK_ATTACHMENTS=loopback +[[ "$delivered" != sibling-attachments ]] || RSTACK_ATTACHMENTS=compose +printf '{"authentication":{"oidc":{"issuers":{"fixture":{}}}},"audit":{"path":"%s/audit.jsonl"}}\n' \ + "$scratch" >"$scratch/runtime.json" +: >"$scratch/audit.jsonl" +: >"$scratch/audit.schedulingctl.jsonl" +write_starter() { mkdir -p "$1"; : >"$1/dev.yaml"; } +init_command() { INIT_COMMAND=(write_starter "$2"); } +add_contact_hook() { :; } +add_documents_hooks() { :; } +prepare_compose_attachments() { printf '%s\n' 'prepare Compose attachments' >>"$trace"; } +verify_sibling_hook() { printf 'check sibling hook %s\n' "$1" >>"$trace"; } +verify_compose_services_running() { printf '%s\n' 'Compose services outlive rstack' >>"$trace"; } +start_evidence_source() { :; } +stop_evidence_source() { :; } +measure_reader_action() { + if [[ "$delivered" == first-hour ]]; then + journey_step "$1" -- true + fi +} +start_run() { + local result=passed + measure_reader_action "$1" + [[ "$1" != keep ]] || result=skipped + RUN=$1-run + START_FILE=$scratch/$1.json + jq -n --arg product "$CELL" --arg runtime "$scratch/runtime.json" --arg result "$result" \ + --arg delivered "$delivered" ' + {runtimeConfigs: {($product): $runtime}, scenarios: [{id: "starter", result: $result}], + bregHookSink: {receivedUrl: "http://127.0.0.1:49191/received"}} + + if $delivered == "no-sink" then {} else + {hookSinks: {documents: {receivedUrl: "http://127.0.0.1:49191/received"}}} + end' >"$START_FILE" + LIVE_RUNS+="$RUN"$'\n' +} +run_url() { printf '%s\n' 'http://127.0.0.1:49192'; } +issue_token() { measure_reader_action "$1"; } +write_keep() { + KEEP_PERSON=$PERSON + KEEP_PATH=/retained + KEEP_EXPECT=retained-id + printf 'write %s\n' "$1" >>"$trace" +} +sink_response() { + local record + if [[ "$CELL" == documents ]]; then + jq -nc --arg digest "$(<"$scratch/digest")" --arg mode "$delivered" ' + {id: "evt-1", source: "urn:registrystack:documents:civil-registry-documents", + type: "document-version-ready", data: {documentId: "retained-id", + versionId: (if $mode == "other-version" then "other" else "version-id" end), + versionDigest: $digest, policyId: "institutional-custody", policyVersion: "1"}} as $event | + [{body: ($event | tojson), headers: ([ + {name: "webhook-id", value: "evt-1"}, + {name: "webhook-timestamp", value: "1"}, + {name: "webhook-signature", value: "v1,fixture"} + ] + (if $mode == "forwarded-auth" then [{name: "authorization", value: "fixture"}] else [] end))}]' + return + fi + case "$delivered" in + yes | missing-on-read) record=retained-id ;; + wrong-record) record=other-id ;; + *) printf '%s\n' '[]'; return ;; + esac + jq -nc --arg record "$record" '[{body: ({type: "contact-created", data: { + recordId: $record, values: {name: "A retained contact"}}} | tojson)}]' +} +curl() { + [[ "${!#}" == http://127.0.0.1:49191/received ]] + printf '%s\n' 'poll sink' >>"$trace" + sink_response +} +journey_poll() { + # One deterministic poll attempt runs the real predicate and models a timeout on failure. + shift 2 + "$@" +} +document_view() { + jq -nc --arg digest "$(<"$scratch/digest")" --arg version "$1" \ + '{id:"retained-id", version:{id:$version, status:"ready", expectedDigest:$digest}}' +} +documents_http() { + local request=${@: -2:1} url=${!#} + case "$request $url" in + 'POST http://127.0.0.1:49192/v1/documents') + local expected actual + expected=$(jq -er '.expectedDigest' "$work/document-reserve.json") + actual=$(perl -MDigest::SHA -e 'print "sha256:", Digest::SHA->new(256)->addfile($ARGV[0], "b")->hexdigest' "$work/retained.pdf") + [[ "$expected" == "$actual" ]] + printf '%s' "$expected" >"$scratch/digest" + document=retained-id version=version-id upload=/v1/uploads/abcd/content + printf '%s\n' 'reserve document' >>"$trace" + ;; + 'PUT http://127.0.0.1:49192/v1/uploads/abcd/content') + printf '%s\n' 'upload document' >>"$trace" + ;; + 'GET http://127.0.0.1:49192/v1/documents/retained-id') + printf '%s\n' 'read ready document' >>"$trace" + if [[ "$1" == keep && "$delivered" == changed-after-restart ]]; then + document_view other-version >"$JOURNEY_STEP_STDOUT" + else + document_view version-id >"$JOURNEY_STEP_STDOUT" + fi + ;; + *) return 1 ;; + esac +} +journey_http() { + JOURNEY_STEP_STDOUT=$scratch/response.json + if [[ "$CELL" == documents ]]; then + case "${!#}" in + http://127.0.0.1:49192/v1/documents* | http://127.0.0.1:49192/v1/uploads/*) + documents_http "$@" + return + ;; + esac + fi + case "$1" in + call) + measure_reader_action "$1" + JOURNEY_STEP_STDOUT=$scratch/response.json + if [[ "$CELL" == messaging ]]; then + case "${@: -2:1} ${!#}" in + 'POST http://127.0.0.1:49192/v1/messages/receipt') + [[ " $* " == *' Idempotency-Key: send-a-reminder-sms '* ]] + [[ " $* " == *' --concepts idempotency-key '* ]] + message_id=starter-message + printf '%s\n' 'read starter message receipt' >>"$trace" + jq -c . "$work/call-body.json" >>"$trace" + ;; + *) return 1 ;; + esac + printf '%s\n' '{"id":"starter-message","links":{"self":"/v1/messages/starter-message"}}' >"$JOURNEY_STEP_STDOUT" + else + printf '%s\n' '{}' >"$JOURNEY_STEP_STDOUT" + fi + ;; + hook) + [[ "${!#}" == http://127.0.0.1:49191/received ]] + printf '%s\n' 'read sink' >>"$trace" + if [[ "$delivered" == missing-on-read ]]; then + printf '%s\n' '[]' >"$JOURNEY_STEP_STDOUT" + else + sink_response >"$JOURNEY_STEP_STDOUT" + fi + ;; + keep) + printf '%s\n' 'read retained record' >>"$trace" + if [[ "$CELL" == messaging ]]; then + printf '%s\n' '{"id":"retained-id"}' >"$JOURNEY_STEP_STDOUT" + else + printf '%s\n' '{"recordId":"retained-id"}' >"$JOURNEY_STEP_STDOUT" + fi + ;; + *) return 1 ;; + esac +} +rstack_dev() { :; } +state_is_empty() { :; } +edit_for_restart() { :; } +audit_was_appended() { :; } +attach_database() { journey_pass attach; } +attach_compose_database() { printf '%s\n' 'attach private Compose database' >>"$trace"; journey_pass attach; } +run_containers() { printf '%s\n' 'fake-container'; } +journey_check_absent() { :; } + +options=() +[[ "$delivered" != first-hour ]] || options+=(--timed) +journey_init rstack-dev -- --product "$product" --out "$scratch/run" "${options[@]}" +JOURNEY_BIN_DIR=$scratch +printf '%s\n' '#!/usr/bin/env bash' 'exit 0' >"$scratch/evidence" +chmod +x "$scratch/evidence" +if [[ "$delivered" == terminal-step ]]; then + journey_cell_begin "$product" + journey_unexercised stop +else + walk_product "$product" +fi +if [[ "$delivered" == first-hour ]]; then + jq -r '.toT1.steps' "$scratch/run/$product/cell.json" >>"$trace" +fi +journey_finish +""" + with tempfile.TemporaryDirectory() as directory: + scratch = Path(directory) + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", "\n".join(functions) + driver, + "local-hook-walk", str(TABLES), directory, product, delivered], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES)}, + capture_output=True, text=True, timeout=15, + ) + cells = (scratch / "run" / "cells.tsv").read_text(encoding="utf-8") + outcomes = [tuple(row.split("\t")[1:3]) for row in cells.splitlines()[1:]] + trace_file = scratch / "trace" + trace = trace_file.read_text(encoding="utf-8").splitlines() if trace_file.exists() else [] + return result, outcomes, trace + + def test_starter_first_read_uses_four_reader_commands(self): + result, outcomes, trace = self.walk("scheduling", "first-hour") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(trace[-1], "4") + self.assertIn(("plan", "pass"), outcomes) + self.assertIn(("issuer", "pass"), outcomes) + + def test_breg_compose_attachments_requires_the_sibling_hook_and_private_database(self): + result, outcomes, trace = self.walk("breg", "sibling-attachments") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(("hook", "pass"), outcomes) + self.assertIn(("attach", "pass"), outcomes) + self.assertEqual(trace, ["prepare Compose attachments", "write breg", "check sibling hook retained-id", + "read retained record", "attach private Compose database", + "Compose services outlive rstack"]) + + def test_messaging_reads_the_starter_receipt_in_four_reader_commands(self): + result, _, trace = self.walk("messaging", "first-hour") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(trace[0], "read starter message receipt") + example = REPO / "products/messaging/examples/starter/dev-journeys.yaml" + starter = yaml.safe_load(example.read_text(encoding="utf-8")) + journey = next(journey for journey in starter["journeys"] if journey["id"] == "send-a-reminder-sms") + self.assertEqual(json.loads(trace[1]), journey["steps"][0]["body"]) + self.assertEqual(trace[2], "write messaging") + self.assertEqual(trace[-1], "4") + + def test_evidence_first_read_uses_the_checked_start(self): + result, outcomes, trace = self.walk("evidence", "first-hour") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(trace[-1], "4") + self.assertIn(("issuer", "pass"), outcomes) + + def test_scheduling_reports_unexercised_and_keeps_walking(self): + result, outcomes, trace = self.walk("scheduling", "no") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("needs a verified task grant and its assertion issuer binding", result.stdout) + self.assertEqual([row for row in outcomes if row[0] == "hook"], [("hook", "unexercised")]) + self.assertIn("scheduling hook: unexercised", result.stderr) + self.assertEqual(outcomes[-3:], [("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) + self.assertEqual(trace, ["write scheduling", "read retained record"]) + + def test_breg_passes_hook_after_payload_arrives(self): + result, outcomes, trace = self.walk("breg", "yes") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([row for row in outcomes if row[0] == "hook"], [("hook", "pass")]) + self.assertEqual(outcomes[-3:], [("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) + self.assertEqual(trace, ["write breg", "poll sink", "read sink", "read retained record"]) + + def test_breg_does_not_pass_hook_without_payload(self): + for delivered in ("no", "wrong-record", "missing-on-read"): + with self.subTest(delivered=delivered): + result, outcomes, trace = self.walk("breg", delivered) + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertFalse(any(step in {"hook", "keep", "stop"} for step, _ in outcomes)) + expected = ["write breg", "poll sink"] + if delivered == "missing-on-read": + expected.append("read sink") + self.assertEqual(trace, expected) + + def test_final_step_cannot_be_unexercised(self): + result, outcomes, _ = self.walk("scheduling", "terminal-step") + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertIn("the final step of scheduling cannot be marked unexercised", result.stderr) + self.assertEqual(outcomes, []) + + def test_documents_keeps_the_same_ready_version_after_one_upload(self): + result, outcomes, trace = self.walk("documents", "yes") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(outcomes[-4:], [("hook", "pass"), ("keep", "pass"), ("attach", "pass"), ("stop", "pass")]) + self.assertEqual(trace, ["reserve document", "upload document", "poll sink", "read sink", + "read ready document", "read ready document"]) + + def test_documents_refuses_unmatched_capture_or_readback(self): + for delivered, diagnostic in ( + ("no-sink", "did not report its hook sink"), + ("other-version", "did not receive the expected event"), + ("forwarded-auth", "did not receive the expected event"), + ("changed-after-restart", "no longer identifies the ready version"), + ): + with self.subTest(delivered=delivered): + result, outcomes, trace = self.walk("documents", delivered) + self.assertEqual(result.returncode, 3, result.stdout + result.stderr) + self.assertIn(diagnostic, result.stderr) + self.assertNotIn(("keep", "pass"), outcomes) + if delivered == "no-sink": + self.assertEqual(trace, []) + + +class DevelopmentAttachments(unittest.TestCase): + def test_compose_keeps_postgres_unpublished_and_receiver_loopback_only(self): + fixture = yaml.safe_load((TABLES / "projects/rstack-attachments.compose.yaml").read_text()) + database = fixture["services"]["db"] + receiver = fixture["services"]["receiver"] + self.assertNotIn("ports", database) + self.assertNotIn("network_mode", database) + self.assertNotIn("network_mode", receiver) + self.assertEqual(receiver["ports"], ["127.0.0.1::8109"]) + self.assertEqual(database["secrets"], ["db-password"]) + self.assertEqual(receiver["secrets"], ["hook-key"]) + for service in (database, receiver): + self.assertRegex(service["image"], r"@sha256:[0-9a-f]{64}$") + self.assertEqual(service["pull_policy"], "never") + + def test_private_postgres_check_requires_the_exact_endpoint_for_both_roles(self): + script = TABLES / "projects/check-private-postgres.py" + address = "172.20.0.4" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config = root / "runtime.json" + for role in ("runtime", "migration"): + (root / role).write_text(f"postgresql://test:test@{address}:5432/fixture?sslmode=disable") + config.write_text(json.dumps({ + "secretProviders": {"file": {"root": str(root)}}, + "database": {"transport": "private-network-plaintext", "runtimeUrlRef": "secret:file/runtime", + "migrationUrlRef": "secret:file/migration"}, + })) + command = ["python3", str(script), str(config), address] + accepted = subprocess.run(command, check=True, capture_output=True, text=True) + self.assertEqual(json.loads(accepted.stdout)["rolesPinned"], ["runtime", "migration"]) + (root / "migration").write_text("postgresql://test:test@172.20.0.5:5432/fixture?sslmode=disable") + refused = subprocess.run(command, capture_output=True, text=True) + self.assertNotEqual(refused.returncode, 0) + self.assertNotIn("postgresql://", refused.stderr) + + +class ManagedSchedulingStartup(unittest.TestCase): + def run_interrupted_start(self, mode, stop_failure=False): + source = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + managed = source[source.index("COMPOSED_MANAGED_RUN=''\n"): + source.index("composed_scheduling_url() {")] + driver = r""" +source "$1/lib.sh" +journey_init own-provider -- --product scheduling --out "$FIXTURE/run" +journey_cell_begin scheduling +SECRETS=$JOURNEY_OUT/secrets +ADMIN_URL_FILE=$FIXTURE/admin-url +COMPOSED_RSTACK_BIN=$FIXTURE/launcher +SERVER_BIN=$COMPOSED_RSTACK_BIN TOOL_BIN=$COMPOSED_RSTACK_BIN +if [[ "$2" == timeout ]]; then + eval "$(declare -f journey__watchdog | sed '1s/journey__watchdog/fixture_watchdog/')" + journey__watchdog() { + [[ "$2" != 120 ]] || set -- "$1" 2 "$3" "$4" + fixture_watchdog "$@" + } +fi +""" + managed + r""" +start_composed_managed_scheduling "$FIXTURE" "$FIXTURE/start.json" +journey_finish +""" + launcher = r"""#!/usr/bin/env python3 +import os +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + +fixture = Path(os.environ["FIXTURE"]) +run = Path(os.environ["RSTACK_DEV_STATE_DIR"]) / ("a" * 32) +if sys.argv[6] == "stop": + if os.environ.get("RSTACK_SCHEDULINGCTL_BIN") != sys.argv[0]: + sys.exit(6) + if sys.argv[7] != run.name or not (run / "recovery").exists(): + sys.exit(7) + if not (fixture / "term").exists() or not (fixture / "child-stopped").exists(): + sys.exit(8) + (fixture / "stop").touch() + if os.environ["STOP_FAILURE"] == "1": + sys.exit(9) + shutil.rmtree(run) + sys.exit(0) + +child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(8)"]) + +def terminate(_signal, _frame): + (fixture / "term").touch() + sys.exit(143) + +signal.signal(signal.SIGTERM, terminate) +try: + run.mkdir(parents=True) + (run / "recovery").write_text("owned recovery fixture", encoding="utf-8") + (fixture / "pids.tmp").write_text(f"{os.getpid()} {child.pid}", encoding="utf-8") + (fixture / "pids.tmp").rename(fixture / "pids") + time.sleep(7) +finally: + child.terminate() + child.wait(timeout=2) + (fixture / "child-stopped").touch() +""" + with tempfile.TemporaryDirectory() as directory: + fixture = Path(directory) + (fixture / "admin-url").write_text("postgresql://fixture@127.0.0.1/test") + executable = fixture / "launcher" + executable.write_text(launcher, encoding="utf-8") + executable.chmod(0o700) + pids = fixture / "pids" + with subprocess.Popen( + ["bash", "-euo", "pipefail", "-c", driver, + "managed-scheduling-start", str(TABLES), mode], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES), + "FIXTURE": directory, "STOP_FAILURE": str(int(stop_failure))}, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + start_new_session=True, + ) as process: + try: + deadline = time.monotonic() + 8 + while not pids.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + if not pids.exists(): + _, errors = process.communicate(timeout=10) + self.fail(f"managed launcher never reached startup: {errors}") + if mode == "cancel": + process.terminate() + _, errors = process.communicate(timeout=10) + term_seen = (fixture / "term").exists() + stop_seen = (fixture / "stop").exists() + managed_root = fixture / "run/secrets/scheduling-managed" + retained = (managed_root / "state" / ("a" * 32) / "recovery").is_file() + live = [] + for pid in pids.read_text(encoding="utf-8").split(): + status = subprocess.run( + ["ps", "-o", "stat=", "-p", pid], capture_output=True, text=True, + ).stdout.strip() + if status and not status.startswith("Z"): + live.append(pid) + report = json.loads((fixture / "run/run.json").read_text(encoding="utf-8")) + self.assertEqual(process.returncode, 143 if mode == "cancel" else 3, errors) + if mode == "timeout": + self.assertIn("did not finish within 120 seconds", report["harnessFailure"]) + self.assertFalse((fixture / "start.json").exists(), "unexpected start report") + self.assertEqual( + (term_seen, stop_seen, live, retained), + (True, True, [], stop_failure), errors, + ) + self.assertEqual(managed_root.exists(), stop_failure) + failures = report["cleanup"]["failures"] + self.assertEqual( + "cleanup hook cleanup_composed_managed_scheduling failed" in failures, + stop_failure, failures, + ) + if not stop_failure: + self.assertEqual(failures, [], errors) + else: + self.assertIn(f"managed Scheduling recovery state retained at {managed_root}", failures) + finally: + # The group contains only the fixture. Reap any escaped + # fake launcher and child when running against a broken runner. + subprocess.run( + ["kill", "-TERM", "--", f"-{process.pid}"], capture_output=True, + ) + + def test_startup_timeout_reaches_launcher_and_waits_for_child(self): + self.run_interrupted_start("timeout") + + def test_cancellation_before_run_id_stops_owned_state_after_launcher(self): + self.run_interrupted_start("cancel") + + def test_failed_shutdown_keeps_owned_recovery_state(self): + self.run_interrupted_start("cancel", stop_failure=True) + + class HookReceiverAndAdapterSource(unittest.TestCase): def test_hook_receiver_signature_verification(self): spec = importlib.util.spec_from_file_location( @@ -867,9 +1741,9 @@ def test_hook_receiver_signature_verification(self): self.assertEqual(wrong_key_status, 403) def test_assert_signed_hook_acceptance_validates_value_free_record(self): - script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + script = (TABLES / "lib.sh").read_text(encoding="utf-8") match = re.search(r"^assert_signed_hook_acceptance\(\) \{\n.*?^\}\n", script, re.S | re.M) - self.assertIsNotNone(match, "own-provider must define assert_signed_hook_acceptance") + self.assertIsNotNone(match, "lib must define assert_signed_hook_acceptance") good = { "event": "signed-hook-accepted", "path": "/scheduling-events", @@ -946,6 +1820,57 @@ def test_composed_fixtures_writes_valid_registration_and_runtimes(self): self.assertEqual(cw_rt["listener"]["bind"], "0.0.0.0:18100") self.assertEqual(cw_rt["listener"]["networkExposure"], "container-private") + def test_managed_scheduling_fixture_names_one_grant_and_live_status_client(self): + script = TABLES / "projects" / "composed_fixtures.py" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + key = root / "status-input" + key.write_bytes(b"fixture status key\n") + key.chmod(0o600) + issuer = "http://127.0.0.1:18080" + jwks = issuer + "/oauth2/jwks" + project = root / "managed" + project.mkdir() + example = project / "runtime.example.yaml" + example.write_text("kind: SchedulingRuntimeConfig\ndestinations: {}\n", encoding="utf-8") + command = ["python3", str(script), "scheduling-managed-plan", str(project), + "--issuer", issuer, "--jwks", jwks, "--casework-port", "18100", + "--agent-subject", "fixture-agent", "--status-key", str(key)] + rejected = command.copy() + rejected[rejected.index(jwks)] = "http://127.0.0.1:18009/oauth2/jwks" + result = subprocess.run(rejected, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("same-origin JWKS", result.stderr) + key.chmod(0o640) + result = subprocess.run(command, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("owner-only fixture status key", result.stderr) + self.assertFalse((project / "fixture").exists()) + self.assertFalse((project / "dev.yaml").exists()) + key.chmod(0o600) + subprocess.run(command, check=True, capture_output=True) + plan = json.loads((project / "dev.yaml").read_text(encoding="utf-8")) + self.assertEqual(plan["externalJwksUri"], jwks) + self.assertEqual(plan["products"], [{"product": "scheduling", "project": ".", + "audience": "urn:example:journey:scheduling"}]) + self.assertEqual(plan["people"], {"task-agent": { + "subject": "fixture-agent", "client": "task-agent", + "grants": {"scheduling": {"profile": "reader", "scopes": ["scheduling:read"]}}, + }}) + self.assertEqual(plan["externalScheduling"], {"taskGrant": { + "sourceIssuer": "https://casework.journey.example", "assertionClient": "task-agent", + "statusUrl": "http://127.0.0.1:18100", "tokenEndpoint": issuer + "/oauth2/token", + "statusClient": "scheduling-status", "statusKeyRef": "secret:file/scheduling-status.jwk", + "statusResource": "urn:example:journey:casework", + }}) + self.assertEqual(json.loads((project / plan["journeyFile"]).read_text())["journeys"], []) + copied = project / "fixture/scheduling-status.jwk" + self.assertEqual(copied.read_bytes(), key.read_bytes()) + self.assertEqual(copied.stat().st_mode & 0o777, 0o600) + self.assertEqual(copied.parent.stat().st_mode & 0o777, 0o700) + destinations = yaml.safe_load(example.read_text())["destinations"] + self.assertEqual(set(destinations["hooks"]), {"appointment-events"}) + class TokenAudienceAndWrongAgentChecks(unittest.TestCase): @staticmethod @@ -1011,6 +1936,32 @@ def test_token_has_audience_and_scope_handles_keycloak_array_and_string_shapes(s ) self.assertEqual(result.returncode == 0, should_pass, f"{label}: {result.stderr}") + def test_breg_keycloak_checks_exact_scope_and_distinguishes_the_unmapped_control(self): + fn = self._extract_functions("breg_keycloak_token_matches") + claims = {"iss": "https://keycloak.example.test", "aud": "urn:example:api", + "azp": "directory-client", "sub": "keycloak-service-account", + "scope": "registry:directory:write"} + mapped = dict(claims, registry_principal="synthetic-directory-editor", + registry_purpose="directory-administration", jurisdiction="zone-a") + for label, payload, control, accepted in ( + ("exact", mapped, False, True), + ("extra scope", {**mapped, "scope": "registry:directory:write profile"}, False, False), + ("wrong zone", {**mapped, "jurisdiction": "zone-b"}, False, False), + ("wrong client", {**mapped, "azp": "foreign-directory-client"}, False, False), + ("unmapped control", claims, True, True), + ("mapped control", mapped, True, False), + ): + with self.subTest(case=label): + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", fn + '\n' + + 'TOKEN=$1 KC_ISSUER=https://keycloak.example.test SCOPE=registry:directory:write AUDIENCE=urn:example:api\n' + 'breg_keycloak_token_matches TOKEN directory-client keycloak-service-account "$2" "$3"', + "bash", self._encode_payload_for_parser_test(payload), + "" if control else "synthetic-directory-editor", "" if control else "zone-a"], + capture_output=True, text=True, timeout=5, + ) + self.assertEqual(result.returncode == 0, accepted, result.stderr) + def test_assert_wrong_agent_grant_refused_distinguishes_setup_and_credential_errors(self): fn = self._extract_functions("assert_wrong_agent_grant_refused") exact = "Casework refused the grant; check its approval, client, expiry and revocation" diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh index 7a16c5f522..b5bb73992d 100644 --- a/products/platform/journeys/test_lib.sh +++ b/products/platform/journeys/test_lib.sh @@ -398,8 +398,8 @@ driver_binaries() { # The cell of PRODUCT as CELL_ describes it: pass, fail:STEP:CODE, # needs:STEP:THING, poll:STEP (a journey_poll that runs out of time), -# unreached:STEP, blocker:STEP:CODE:ASSIST or harness:STEP. The default is the -# product's row in the synthetic table. +# unreached:STEP, unexercised:STEP, blocker:STEP:CODE:ASSIST or harness:STEP. +# The default is the product's row in the synthetic table. driver_cell() { local product=$1 plan_name plan kind stop code assist step plan_name="CELL_$product" @@ -421,6 +421,10 @@ driver_cell() { journey_unreached "$step" "runs beside its parent" break ;; + unexercised) + journey_unexercised "$step" + continue + ;; fail) if ! journey_step "$step" -- "$alpha" fail; then journey_fail "$step" "$code" @@ -802,6 +806,9 @@ driver_replay() { esac break fi + if [[ "$step" == refusals && -n "${REPLAY_PRODUCTION_REFUSALS:-}" ]]; then + journey_count production-refusals "$REPLAY_PRODUCTION_REFUSALS" + fi journey_pass "$step" done <<<"$steps" if [[ "$kind" == pass && ${REPLAY_COUNTERS:-0} != 0 ]]; then @@ -1812,6 +1819,8 @@ case_http() { drive 0 SCENARIO=http EXPECT_REFUSAL=1 -- --product alpha check "the observed 401 remains in the HTTP transcript" has "HTTP/1.1 401" "$out/alpha/call.http" check "the checked refusal passes the journey step" has $'alpha\tcall\tpass\t-' "$out/cells.tsv" + check_equal "a passing expected HTTP refusal adds no reader friction" 0 \ + "$(json '.cells[] | select(.product == "alpha") | .total.refusalsMet' "$out/summary.json")" begin_case http-source-bearer printf '{"access_token":"%s"}\n' "$token" >"$state/http-body.1" @@ -1875,6 +1884,16 @@ case_modes() { drive 1 CELL_gamma=unreached:start -- "${run_args[@]}" --expected "$table" check_equal "unreached at another step is a mismatch" mismatch "$(json '.cells[] | select(.product == "gamma") | .verdict' "$out/summary.json")" + begin_case unexercised-step + drive 0 CELL_alpha=unexercised:call -- "${run_args[@]}" --product alpha --expected "$table" --strict + check "the skipped step is recorded" has $'alpha\tcall\tunexercised\t-' "$out/cells.tsv" + check "later steps still run" has $'alpha\tstop\tpass\t-' "$out/cells.tsv" + check "the log identifies the unexercised step" has "alpha call: unexercised" "$last_err" + + begin_case final-step-must-run + drive 3 CELL_alpha=unexercised:stop -- "${run_args[@]}" --product alpha + check "the required final step cannot be skipped" has "the final step of alpha cannot be marked unexercised" "$last_err" + begin_case ratchet-stale drive 0 CELL_beta=pass -- "${run_args[@]}" --expected "$table" check "a listed failure that passes is a warning" has "warning: a listed failure no longer fails" "$last_err" @@ -2023,6 +2042,19 @@ case_real_tables() { check_equal "every product has a cell" "$(value replayed)" "$(json '.cells | length' "$out/summary.json")" check_equal "every cell equals its row" 0 "$(json '[.cells[] | select(.verdict != "ok")] | length' "$out/summary.json")" + begin_case production-refusal-count + local count + for count in 0 2; do + drive 0 TEST_JOURNEY=promote SCENARIO=replay REPLAY_PRODUCTION_REFUSALS="$count" JOURNEY_TABLES_DIR= -- \ + --product render --product breg --expected "$lib_dir/expected-failures.yaml" --strict + check_equal "the blocked cell explicitly records an unmeasured comparison" true \ + "$(json '.cells[] | select(.product == "breg") | has("productionRefusals") and .productionRefusals == null' "$out/summary.json")" + check_equal "the completed comparison records its measured count" "$count" \ + "$(json '.cells[] | select(.product == "render") | .productionRefusals' "$out/summary.json")" + check_equal "the production refusals are also included in the aggregate" "$count" \ + "$(json '.cells[] | select(.product == "render") | .total.refusalsMet' "$out/summary.json")" + done + begin_case real-table-missing-first-hour-measurements drive 0 TEST_JOURNEY=rstack-dev SCENARIO=replay JOURNEY_TABLES_DIR= -- --expected "$lib_dir/expected-failures.yaml" --strict check_equal "every functional cell equals its row" 0 "$(json '[.cells[] | select(.verdict != "ok")] | length' "$out/summary.json")" diff --git a/products/platform/schemas/task-connection.schema.json b/products/platform/schemas/task-connection.schema.json index 8d7dcf5b10..256fd72a8c 100644 --- a/products/platform/schemas/task-connection.schema.json +++ b/products/platform/schemas/task-connection.schema.json @@ -12,12 +12,17 @@ "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", "type": "string" }, - "FileSecretProviderConfig": { + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "StrictFileSecretProviderConfig": { "additionalProperties": false, - "description": "The file secret provider.", + "description": "The file secret provider without the Compose mount policy.", "properties": { "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe user running the process with mode 0400 or 0600, or owned by root\nwith no access beyond group read (0440 or 0640) when that user is not\nroot. A process that declared development loads a file with looser read\nor mode bits and logs a warning. A public document, such as a static\nJWKS or a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -27,13 +32,13 @@ ], "type": "object" }, - "SecretProvidersConfig": { + "StrictSecretProvidersConfig": { "additionalProperties": false, "anyOf": [ { "properties": { "file": { - "$ref": "#/$defs/FileSecretProviderConfig" + "$ref": "#/$defs/StrictFileSecretProviderConfig" } }, "required": [ @@ -51,24 +56,19 @@ ] } ], - "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", + "description": "The secret providers without the Compose mount policy, so the strict file\nrule always applies. An operator-local file read outside any runtime, such\nas a saved CLI connection or a task connection, uses it because nothing\nreports an explicit production setting for that file. A runtime whose keys\nkeep the strict rule publishes it as the shape of its `secretProviders`.", "properties": { "environment": { "$ref": "#/$defs/EnvironmentSecretProviderConfig", "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." }, "file": { - "$ref": "#/$defs/FileSecretProviderConfig", + "$ref": "#/$defs/StrictFileSecretProviderConfig", "description": "Enables `secret:file/name` references, read from files under `root`." } }, "type": "object" }, - "SecretReference": { - "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", - "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", - "type": "string" - }, "TaskClient": { "additionalProperties": false, "description": "One registered client.", @@ -181,7 +181,7 @@ "type": "string" }, "secretProviders": { - "$ref": "#/$defs/SecretProvidersConfig", + "$ref": "#/$defs/StrictSecretProvidersConfig", "description": "The providers that resolve each client's `assertionKeyRef`." }, "tokenEndpoint": { diff --git a/products/platform/scripts/check-config-conformance.py b/products/platform/scripts/check-config-conformance.py index e1ae75866d..7acb0d2cf4 100755 --- a/products/platform/scripts/check-config-conformance.py +++ b/products/platform/scripts/check-config-conformance.py @@ -705,13 +705,13 @@ class Row: "AccessTokenType", "DeclaredActorKind", "EnvironmentSecretProviderConfig", - "FileSecretProviderConfig", "IssuerActorKind", "ListenerBind", "MetricsListenerConfig", "ScopeClaimName", - "SecretProvidersConfig", "SecretReference", + "StrictFileSecretProviderConfig", + "StrictSecretProvidersConfig", ), reference_refusal=TestRef( "crates/registry-evidence-oid4vci/src/config.rs", diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index 19624d66a8..2cfd646502 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -113,7 +113,7 @@ "target", "schema", "reader", "check", "example", "conformance", "securityMembers", "restrictingMembers", ) -OPTIONAL_FORMAT_FIELDS = ("emittedBy", "exceptionClass", "topLevel", "buildArtifact", "notes") +OPTIONAL_FORMAT_FIELDS = ("emittedBy", "exceptionClass", "topLevel", "buildArtifact", "passiveReport", "notes") ENUMS = { "syntax": ("yaml", "json", "jsonl", "text"), "audience": ("authored", "operator", "generated"), @@ -1177,6 +1177,7 @@ def __init__(self, root: Path, report: Report) -> None: self.canonical: dict = {} self.convention: Convention | None = None self.formats: list[dict] = [] + self.passive_reports: set[str] = set() self.by_id: dict[str, dict] = {} self.quantities: list[tuple[str, str, str, str, str]] = [] @@ -1570,11 +1571,36 @@ def check_registry(self, registry: dict) -> None: self.check_target(fid, entry, kinds) self.check_schema_entry(fid, entry) self.check_reader(fid, entry) + writer = None if "emittedBy" in entry: - self.check_symbol(fid, "emittedBy", entry["emittedBy"]) + writer = self.check_symbol(fid, "emittedBy", entry["emittedBy"]) document = self.check_example(fid, entry) entry["_example"] = document schema = self.format_schema(entry) + if "passiveReport" in entry: + if ( + entry["passiveReport"] is True + and entry["audience"] == "generated" + and entry["syntax"] == "json" + and "buildArtifact" not in entry + and writer is not None + and isinstance(schema, dict) + and isinstance(entry["reader"], dict) + and isinstance(entry["check"], str) + and re.fullmatch( + r"rstack dev check --owner-report \{file\} --owner-report-format [a-z][a-z0-9-]*", + entry["check"], + ) + and isinstance(document, dict) + and entry["securityMembers"] == entry["restrictingMembers"] == [] + ): + self.passive_reports.add(fid) + else: + self.error( + f"{fid}: passiveReport requires true on a generated JSON writer report with a schema, " + "a reader and offline rstack owner-report check, a saved example, " + "and no build, security, or restricting members" + ) self.check_conformance(fid, entry, document, schema) self.check_members(fid, entry, schema) for kind, ids in kinds.items(): @@ -1914,14 +1940,15 @@ def find(rule: str, visit: Visit, message: str, fix: str, suffix: tuple[str, ... # do not bound configured work. Reports may state the writer's # native range, but still need both bounds explicitly in schema. output = entry is not None and entry.get("reader") == "none" - implicit = not output and str(node.get("format", "")).startswith("uint") and node.get("minimum") == 0 \ + passive = fid in self.passive_reports + implicit = not (output or passive) and str(node.get("format", "")).startswith("uint") and node.get("minimum") == 0 \ and node.get("maximum", UNSIGNED_CEILING.get(node.get("format"))) == UNSIGNED_CEILING.get(node.get("format")) - has_minimum = ("minimum" in node and not implicit) or "exclusiveMinimum" in node - has_maximum = "maximum" in node or "exclusiveMaximum" in node + has_minimum = ("minimum" in node and not implicit) or (not passive and "exclusiveMinimum" in node) + has_maximum = "maximum" in node or (not passive and "exclusiveMaximum" in node) if not (has_minimum and has_maximum): missing = [bound for bound, present in (("minimum", has_minimum), ("maximum", has_maximum)) if not present] detail = " (minimum 0 is the unsigned type's implicit bound)" if implicit else "" - fix = "State both bounds from the writer's serialized integer type" if output else \ + fix = "State both bounds from the writer's serialized integer type" if output or passive else \ "Read it with BoundedU32/BoundedU64 and state both bounds" find("CFG-QTY-4", visit, f"an integer without a stated {' and '.join(missing)}{detail}", fix) closing = None if visit.conditional else self.closing_problem(document, visit) diff --git a/products/platform/scripts/prepare-service-preview-locks.mjs b/products/platform/scripts/prepare-service-preview-locks.mjs index 482a22c651..a857930729 100644 --- a/products/platform/scripts/prepare-service-preview-locks.mjs +++ b/products/platform/scripts/prepare-service-preview-locks.mjs @@ -59,7 +59,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) assert.ok(archive && directory && extra.length === 0 && [archive, directory].every(isAbsolute), 'Usage: node prepare-service-preview-locks.mjs /absolute/client.tgz /absolute/service-previews') const client = await previewClientArchive(archive) - for (const name of ['medical-renewal', 'business-registration']) { + for (const name of ['medical-renewal', 'business-registration', 'permit-review']) { await stagePreviewClient(join(directory, name), client, { pin: true }) } } diff --git a/products/platform/scripts/run-config-conformance.py b/products/platform/scripts/run-config-conformance.py index 7a78f743fe..3dd3867e73 100644 --- a/products/platform/scripts/run-config-conformance.py +++ b/products/platform/scripts/run-config-conformance.py @@ -195,6 +195,8 @@ VARIABLE = "REGISTRY_CONFORMANCE_VALUE" UNSET_VARIABLE = "REGISTRY_CONFORMANCE_UNSET" BASELINE = "baseline" +INTEGER_BOUNDARY_SWEEP = "integer-boundary-sweep" +PASSIVE_REPORT_CASES = frozenset((BASELINE, INTEGER_BOUNDARY_SWEEP)) TIMEOUT_SECONDS = 120 CODE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+$") @@ -376,6 +378,7 @@ class Format: harness: dict[str, Any] schema: str | None = None schema_id: str | None = None + passive_report: bool = False def with_harness(self, harness: dict[str, Any]) -> "Format": return dataclasses.replace(self, harness=dict(harness)) @@ -1319,7 +1322,7 @@ def resolve_expected( # Reports -def parse_report(stdout: str) -> tuple[list[Any] | None, list[str]]: +def parse_report(stdout: str, *, passive: bool = False) -> tuple[list[Any] | None, list[str]]: text = stdout.strip() if not text: return None, [NO_REPORT] @@ -1329,6 +1332,8 @@ def parse_report(stdout: str) -> tuple[list[Any] | None, list[str]]: return None, [NOT_ONE_DOCUMENT] if not isinstance(value, dict): return None, [NOT_AN_OBJECT] + if passive and value.get("assessment") != "owner-report-structure": + return None, ["the JSON report has no owner-report-structure assessment"] diagnostics = value.get("diagnostics") if not isinstance(diagnostics, list): return None, [NO_DIAGNOSTICS] @@ -1576,6 +1581,8 @@ def sanitize(text: str, work: str) -> str: def not_applicable(case: Case, fmt: Format) -> str | None: """Why a case does not apply to a format, or None when it does.""" + if fmt.passive_report and case.id not in PASSIVE_REPORT_CASES: + return "a passive JSON report runs the baseline and integer boundary sweep" audiences = case.applies_to.get("audiences") if audiences and fmt.audience not in audiences: return f"the case applies to {' and '.join(audiences)} files" @@ -1596,7 +1603,7 @@ def partition_formats(formats: list[Format]) -> tuple[list[Format], dict[str, st skipped[fmt.id] = "no check command" elif not fmt.example: skipped[fmt.id] = "no example" - elif fmt.syntax != "yaml": + elif fmt.syntax != "yaml" and not (fmt.syntax == "json" and fmt.passive_report): skipped[fmt.id] = f"syntax {fmt.syntax}; the corpus mutates YAML text" else: reached.append(fmt) @@ -1803,6 +1810,7 @@ def load_registry(path: Path) -> list[Format]: harness={}, schema=str(root / schema["path"]) if isinstance(schema.get("path"), str) else None, schema_id=schema["id"] if isinstance(schema.get("id"), str) else None, + passive_report=entry.get("passiveReport") is True, ) ) return formats @@ -2067,7 +2075,7 @@ def check_variant( problems += marker_problems(stdout, stderr) posture_warnings = 0 if case.expect.get("report", True): - diagnostics, report = parse_report(stdout.decode("utf-8", "replace")) + diagnostics, report = parse_report(stdout.decode("utf-8", "replace"), passive=fmt.passive_report) problems += report if diagnostics is not None: compared = diagnostics @@ -2267,7 +2275,16 @@ def plan(root: Path, formats: list[Format], cases: list[Case], harness: dict[str swept: dict[str, dict[str, Case]] = {case.id: {} for case in cases} for fmt in reached: text = prepare_example((root / str(fmt.example)).read_text(encoding="utf-8"), fmt, {}) + if fmt.passive_report: + try: + json.loads(text) + except ValueError: + raise HarnessError(f"{fmt.id}: the passive report example is not JSON") from None for case in cases: + if fmt.passive_report and case.id in PASSIVE_REPORT_CASES: + case = dataclasses.replace( + case, args=[*case.args, "--deny-warnings"], human=case.id == INTEGER_BOUNDARY_SWEEP, + ) why = not_applicable(case, fmt) variants = [] if why is None and case.run is None: @@ -2276,6 +2293,8 @@ def plan(root: Path, formats: list[Format], cases: list[Case], harness: dict[str except NotApplicable as error: why = str(error) if why is not None: + if fmt.passive_report and case.id in PASSIVE_REPORT_CASES: + raise HarnessError(f"{fmt.id}: passive report must exercise {case.id}: {why}") inapplicable[(fmt.id, case.id)] = why elif case.operation == SWEEP: for variant in variants: @@ -2311,6 +2330,9 @@ def validate_ids( """ format_ids = {fmt.id for fmt in formats} case_ids = {case.id for case in cases} + passive = {fmt.id for fmt in formats if fmt.passive_report} + if passive and not PASSIVE_REPORT_CASES <= case_ids: + raise HarnessError("the corpus needs the baseline and integer boundary sweep for passive reports") for format_id in harness: if only_formats is not None and format_id not in only_formats: continue @@ -2321,6 +2343,8 @@ def validate_ids( continue if format_id not in format_ids: raise HarnessError(f"expected-failures.yaml names format {format_id}, which the registry does not") + if format_id in passive: + raise HarnessError(f"passive report {format_id} cannot have an expected-failure waiver") if not names_case(case_id, cases): raise HarnessError(f"expected-failures.yaml names case {case_id}, which the corpus does not") for format_id in expected.unreached: @@ -2328,6 +2352,8 @@ def validate_ids( continue if format_id not in format_ids: raise HarnessError(f"expected-failures.yaml names format {format_id}, which the registry does not") + if format_id in passive: + raise HarnessError(f"passive report {format_id} cannot have an unreached waiver") for case_id in expected.inapplicable: if case_id not in case_ids: raise HarnessError(f"expected-failures.yaml names case {case_id}, which the corpus does not") @@ -2426,8 +2452,9 @@ def report( if args.write_expected_failures: failures, refused = {}, [] + passive = {fmt.id for fmt in work.reached if fmt.passive_report} for cell, problems in results.items(): - if any(unmaskable(problem) for problem in problems): + if problems and (cell[0] in passive or any(unmaskable(problem) for problem in problems)): refused.append(cell) elif problems: failures[cell] = Listed(reason(problems), digest(problems)) diff --git a/products/platform/scripts/test-rstack-dev.py b/products/platform/scripts/test-rstack-dev.py index 916d42b128..7136d71226 100644 --- a/products/platform/scripts/test-rstack-dev.py +++ b/products/platform/scripts/test-rstack-dev.py @@ -1313,7 +1313,8 @@ def spatial_project(root, name): "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": "https://spatial-smoke.example.invalid", - "products": [{"product": "breg", "project": "registry", "audience": "breg"}], + "products": {"breg": {"projects": {"breg": {"path": "registry"}}}}, + "audiences": {"breg": "breg"}, "people": people, "journey": { "id": "spatial-smoke", @@ -1465,9 +1466,8 @@ def encrypted_project(root, name): "apiVersion": "id.registrystack.org/formats/rstack/dev/v1alpha1", "kind": "RStackDev", "issuer": "https://directory-smoke.example.invalid", - "products": [ - {"product": "breg", "project": "registry", "audience": "directory"} - ], + "products": {"breg": {"projects": {"breg": {"path": "registry"}}}}, + "audiences": {"breg": "directory"}, "people": { alias: { "subject": principal, @@ -1765,13 +1765,13 @@ def verify_offline_plan(root, bin_dir, project): ) shutil.copyfile(NATIVE_REVIEW / "service.yaml", binding / "service.yaml") authored = (NATIVE_REVIEW / "dev.yaml").read_text() - audience = 'audience: "urn:journey:breg"' + audience = 'breg: "urn:journey:breg"' assert authored.count(audience) == 1 - (binding / "dev.yaml").write_text(authored.replace(audience, "audience: registry")) + (binding / "dev.yaml").write_text(authored.replace(audience, "breg: registry")) refused = dev(bin_dir, check_env, binding, "check", ".", expected=1) [diagnostic] = refused["diagnostics"] assert refused["status"] == "domain-refusal" - assert diagnostic["path"] == "/products/0/audience" + assert diagnostic["path"] == "/audiences/breg" assert diagnostic["message"].startswith("Casework refuses"), diagnostic assert ( "contextProviders.registry.humanSourceAuthentication.audience: " diff --git a/products/platform/scripts/test-service-previews.mjs b/products/platform/scripts/test-service-previews.mjs index d940014ffe..9d4e2ce9ae 100644 --- a/products/platform/scripts/test-service-previews.mjs +++ b/products/platform/scripts/test-service-previews.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict' import { execFile } from 'node:child_process' -import { createHash } from 'node:crypto' +import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto' import { constants } from 'node:fs' import { cp, mkdtemp, mkdir, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -200,6 +200,208 @@ async function business(page, url, expectedName = 'Harbour Bicycle Cooperative') return { matchingRecords: records.length, revision: Number(record.revisionId) } } +// Same-origin gateway call as that actor's page would make it. +async function actorCall(origin, path, init = {}) { + const response = await fetch(new URL(path, origin), { + ...init, + headers: { Accept: 'application/json', 'Registry-Client': 'page', Origin: origin.origin, ...init.headers }, + signal: AbortSignal.timeout(8_000), + redirect: 'error', + }) + return { status: response.status, body: await response.json().catch(() => null) } +} + +// The applicant and the officer on two browser contexts, each on its own +// actor origin over the same built page. The applicant starts a Coordinator +// run that names only its application; the Coordinator reads it, Casework +// refuses the applicant's own decision, a forged completion cannot wake the +// run, another applicant cannot follow it, and the officer's approval lets +// the run record the assessment and the decision in BReg. A second run whose +// start the browser tampers with reviews and decides only the record the +// Coordinator read. +async function permitReview(browser, url, report) { + const actors = report.previewActors + assert.deepEqual(Object.keys(actors ?? {}), ['applicant', 'neighbour', 'officer']) + const [applicantUrl, neighbourUrl, officerUrl] = ['applicant', 'neighbour', 'officer'].map(name => loopback(actors[name])) + assert.equal(applicantUrl.href, url.href) + assert.equal(new Set([applicantUrl.origin, neighbourUrl.origin, officerUrl.origin]).size, 3) + assert.ok(report.substitutions.includes('per-actor gateway origin (development)')) + for (const path of ['/', '/app.js', '/service.css']) { + const bodies = await Promise.all([applicantUrl, neighbourUrl, officerUrl].map(async origin => { + const response = await fetch(new URL(path, origin), { signal: AbortSignal.timeout(8_000), redirect: 'error' }) + assert.equal(response.status, 200, path) + return Buffer.from(await response.arrayBuffer()) + })) + assert.ok(bodies.every(body => body.equals(bodies[0])), `The actor origins served different bytes for ${path}.`) + } + // The neighbour's application, seeded by the startup journey. + const listed = await actorCall(officerUrl, '/registry/permits/v1/records/permit-applications') + assert.equal(listed.status, 200) + const neighbourApplication = listed.body.items.find(record => record.domainData.activity === 'Daytime survey') + assert.equal(neighbourApplication?.domainData.status, 'submitted') + + const errors = [] + const requests = [] + const open = async () => { + const context = await browser.newContext({ viewport: { width: 390, height: 900 } }) + const page = await context.newPage() + page.setDefaultTimeout(8_000) + page.on('pageerror', () => errors.push('uncaught page error')) + page.on('request', request => { + const path = new URL(request.url()).pathname + if (path.startsWith('/registry/') || path.startsWith('/_rstack/actor')) requests.push(request) + }) + return { context, page } + } + const applicant = await open() + const officer = await open() + const submit = async (activity, site) => { + const page = applicant.page + await page.goto(applicantUrl.href) + await page.locator('#actor').getByText('applicant', { exact: true }).waitFor() + await page.getByLabel('Activity').fill(activity) + await page.getByLabel('Site').fill(site) + await page.getByRole('button', { name: 'Submit application' }).click() + await page.getByRole('heading', { name: 'Application under review' }).waitFor() + const applicationId = (await page.locator('#application-id').textContent())?.trim() + const runId = (await page.locator('#run-id').textContent())?.trim() + assert.match(applicationId ?? '', uuid) + assert.match(runId ?? '', uuid) + await page.locator('#run-step').getByText('await-review', { exact: true }).waitFor({ timeout: 60_000 }) + return { applicationId, runId } + } + // The officer's task for one application, with the content under review. + const task = async applicationId => { + await officer.page.getByRole('button', { name: 'Show tasks' }).click() + const item = officer.page.locator(`#tasks li[data-application-id="${applicationId}"]`) + await item.waitFor() + return item + } + const approve = async item => { + await item.getByRole('button', { name: 'Claim', exact: true }).click() + await item.getByRole('button', { name: 'Claimed' }).waitFor() + assert.equal(await item.getAttribute('data-claimed'), '200') + await item.getByRole('button', { name: 'Approve', exact: true }).click() + await item.getByRole('button', { name: 'Approved' }).waitFor() + assert.equal(await item.getAttribute('data-decided'), '204') + } + const registered = async applicationId => { + const read = await actorCall(officerUrl, '/registry/permits/v1/records/permit-applications/' + applicationId) + assert.equal(read.status, 200) + return read.body.data.domainData + } + try { + const page = applicant.page + const first = await submit('Night resurfacing', 'North road') + + // A well-formed completion for the configured recipient binding, signed + // with a key Casework does not hold, cannot wake the waiting run: only + // the signature check refuses it. + const coordinator = loopback(report.products.coordinator) + const eventId = randomUUID() + const timestamp = String(Math.floor(Date.now() / 1000)) + const event = JSON.stringify({ + type: 'review.completed', eventId, requestId: randomUUID(), resultId: randomUUID(), + completedAt: new Date().toISOString(), + }) + const forgedSignature = createHmac('sha256', randomBytes(32)).update(`${eventId}.${timestamp}.${event}`).digest('base64') + const forged = await fetch(new URL('/v1/review-completions', coordinator), { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'registry-recipient-binding': 'coordinator-v1', + 'webhook-id': eventId, + 'webhook-timestamp': timestamp, + 'webhook-signature': 'v1,' + forgedSignature, + }, + body: event, + signal: AbortSignal.timeout(8_000), + redirect: 'error', + }) + assert.equal(forged.status, 401, 'The Coordinator accepted a completion Casework did not sign.') + assert.equal((await forged.json()).code, 'authentication.refused') + + // The applicant follows its own run, and another applicant cannot: the + // Coordinator itself answers that the run is not visible. + assert.equal((await actorCall(applicantUrl, '/registry/permit-flow/v1/runs/' + first.runId)).status, 200) + const foreign = await actorCall(neighbourUrl, '/registry/permit-flow/v1/runs/' + first.runId) + assert.equal(foreign.status, 404, 'Another applicant could read the run.') + assert.equal(foreign.body?.code, 'run.not-visible') + + // The run input names only the application, so content is refused. + const workflow = await actorCall(applicantUrl, '/registry/permit-flow/v1/workflows/permit-flow') + const withContent = await actorCall(applicantUrl, '/registry/permit-flow/v1/runs', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID() }, + body: JSON.stringify({ + workflow: 'permit-flow', workflowRevision: workflow.body.workflowRevision, + input: { applicationId: first.applicationId, activity: 'Harmless survey' }, + }), + }) + assert.equal(withContent.status, 400, `A start carrying content answered ${withContent.status}.`) + assert.equal(withContent.body?.code, 'input.invalid') + + await officer.page.goto(officerUrl.href) + await officer.page.locator('#actor').getByText('officer', { exact: true }).waitFor() + const firstTask = await task(first.applicationId) + await firstTask.getByText('Night resurfacing', { exact: true }).waitFor() + await firstTask.getByText('North road', { exact: true }).waitFor() + const taskId = await firstTask.getAttribute('data-task-id') + assert.match(taskId ?? '', uuid) + + // The applicant's own decision reaches Casework, which refuses it. + await page.getByLabel('Task', { exact: true }).fill(taskId) + await page.getByRole('button', { name: 'Approve', exact: true }).click() + await page.getByText('Casework refused the decision (403).').waitFor() + assert.equal(await page.locator('#run-step').textContent(), 'await-review') + assert.equal((await actorCall(applicantUrl, '/registry/permit-flow/v1/runs/' + first.runId)).body.step, 'await-review') + + await approve(firstTask) + await page.locator('#run-outcome').getByText('approved', { exact: true }).waitFor({ timeout: 90_000 }) + assert.equal(await page.locator('#run-state').textContent(), 'finished') + assert.equal(await page.locator('#run-assessment').textContent(), 'conditions') + assert.equal((await registered(first.applicationId)).status, 'approved') + + // The browser rewrites its start to name the neighbour's application. + await page.route('**/registry/permit-flow/v1/runs', async route => { + const body = route.request().postDataJSON() + body.input.applicationId = neighbourApplication.recordId + await route.continue({ postData: JSON.stringify(body) }) + }) + const tampered = await submit('Night works', 'Harbour road') + await page.unroute('**/registry/permit-flow/v1/runs') + const tamperedTask = await task(neighbourApplication.recordId) + await tamperedTask.getByText('Daytime survey', { exact: true }).waitFor() + await tamperedTask.getByText('Market square', { exact: true }).waitFor() + assert.equal(await officer.page.locator(`#tasks li[data-application-id="${tampered.applicationId}"]`).count(), 0) + await approve(tamperedTask) + await page.locator('#run-outcome').getByText('approved', { exact: true }).waitFor({ timeout: 90_000 }) + assert.equal(await page.locator('#run-assessment').textContent(), 'standard') + const decided = await registered(neighbourApplication.recordId) + assert.deepEqual([decided.activity, decided.site, decided.status], ['Daytime survey', 'Market square', 'approved']) + const untouched = await registered(tampered.applicationId) + assert.deepEqual([untouched.activity, untouched.status], ['Night works', 'submitted']) + + assert.deepEqual(errors, []) + assert.ok(requests.some(request => new URL(request.url()).pathname.startsWith('/registry/casework/'))) + assert.ok(requests.some(request => new URL(request.url()).pathname.startsWith('/registry/permit-flow/'))) + for (const request of requests) { + const headers = await request.allHeaders() + assert.equal(Boolean(headers.authorization), false, 'The browser sent an Authorization header.') + assert.equal(headers['registry-client'], 'page') + } + return { + actors: 3, identicalPages: true, applicantDecisionStatus: 403, forgedCompletionStatus: 401, + foreignRunStatus: 404, contentStartRefused: true, outcome: 'approved', assessment: 'conditions', registerStatus: 'approved', + tamperedStart: { reviewed: 'neighbour application', assessment: 'standard', ownApplication: 'submitted' }, + browserBearer: false, + } + } finally { + await applicant.context.close() + await officer.context.close() + } +} + async function exercise(browser, url, journey) { const page = await browser.newPage({ viewport: { width: 390, height: 900 } }) page.setDefaultTimeout(8_000) @@ -253,8 +455,9 @@ async function main() { delete env.RSTACK_DEV_DATABASE_URL delete env.RSTACK_DEV_DATABASE_CA if (managed) { - delete env.RSTACK_BREG_BIN - delete env.RSTACK_BREGCTL_BIN + for (const name of ['BREG', 'BREGCTL', 'CASEWORK', 'CASEWORKCTL', 'COORDINATOR', 'COORDINATORCTL']) { + delete env[`RSTACK_${name}_BIN`] + } } const devArgs = (...args) => [...globalFlags, 'dev', ...args, '--format', 'json'] const dev = async (...args) => JSON.parse(await command(rstack, devArgs(...args), env)) @@ -268,7 +471,7 @@ async function main() { assert.equal(await treeDigest(project), before, 'npm ci modified the delivered example.') return project } - async function runProject(project, functionName, journey, onReady) { + async function runProject(project, functionName, journey, onReady, drive = exercise) { const before = await treeDigest(project) // Keep recovery state if startup times out and the driver never sees a run ID. keepScratch = true @@ -302,7 +505,7 @@ async function main() { }) assert.equal(wrongOrigin.status, 403, 'The preview gateway allowed a different browser origin.') await wrongOrigin.body?.cancel() - result = await exercise(browser, url, journey) + result = await drive(browser, url, journey, report) } finally { const stopped = await dev('stop', report.run_id, '--clean') assert.equal(stopped.cleaned, true) @@ -312,7 +515,8 @@ async function main() { assert.equal(containers.trim(), '', 'The managed PostgreSQL container survived clean stop.') keepScratch = false } - for (const address of [url, privateOrigin]) { + const actorOrigins = Object.values(report.previewActors ?? {}).map(loopback) + for (const address of [url, privateOrigin, ...actorOrigins]) { await assert.rejects(fetch(address, { signal: AbortSignal.timeout(2_000) }), { name: 'TypeError' }) } assert.equal(await treeDigest(project), before, 'Preview modified the authored project.') @@ -326,10 +530,24 @@ async function main() { const medical = await runProject(medicalProject, 'renew', renewal) const registered = await runProject(businessProject, 'register-business', business) assert.notEqual(medical.volume, registered.volume) + // Every run proves permit-review, unless a managed candidate whose release + // ships no Coordinator says so explicitly; a missing install then fails. + const skipPermit = process.env.RSTACK_PREVIEW_SKIP_PERMIT_REVIEW === 'no-coordinator-in-release' + assert.ok(!skipPermit || managed, 'Only a managed candidate may skip permit-review.') + let permit + if (!skipPermit) { + const permitProject = await installProject('permit-review') + permit = await runProject(permitProject, 'assess-permit', null, undefined, + (browser, url, _journey, report) => permitReview(browser, url, report)) + assert.equal(new Set([medical.volume, registered.volume, permit.volume]).size, 3) + } const results = [ { name: 'medical-renewal', ...medical.result, directAnonymousStatus: 401, wrongOriginStatus: 403 }, { name: 'business-registration', ...registered.result, directAnonymousStatus: 401, wrongOriginStatus: 403 }, + permit + ? { name: 'permit-review', ...permit.result, directAnonymousStatus: 401, wrongOriginStatus: 403 } + : { name: 'permit-review', skipped: 'This release ships no Coordinator.' }, ] if (!managed) { diff --git a/products/platform/scripts/test_check_config_conventions.py b/products/platform/scripts/test_check_config_conventions.py index 9ad7790787..d4d0b95a46 100644 --- a/products/platform/scripts/test_check_config_conventions.py +++ b/products/platform/scripts/test_check_config_conventions.py @@ -1198,6 +1198,45 @@ def test_cfg_qty_4_read_back_format_still_requires_semantic_bounds(self) -> None } self.assertFinding(self.repo.run(), "CFG-QTY-4", P, at(PROJECT_SCHEMA, "/$defs/Queue/properties/retryCount")) + def passive_report(self) -> dict: + entry = self.repo.fmt(R) + entry.update( + passiveReport=True, + reader={"crate": "registry-casework-core", "file": CONFIG_RS, "function": "load", "type": "untyped"}, + check="rstack dev check --owner-report {file} --owner-report-format casework-report", + ) + self.repo.report["properties"]["filesChecked"] = { + "type": "integer", "format": "uint64", "minimum": 0, "maximum": 2**64 - 1, + } + return entry + + def test_cfg_qty_4_accepts_explicit_native_passive_report_bounds(self) -> None: + self.passive_report() + report = self.repo.run() + self.assertEqual(report.errors, []) + self.assertNoFinding(report, "CFG-QTY-4") + + def test_cfg_qty_4_passive_report_flag_cannot_exempt_authored_config(self) -> None: + self.passive_report()["audience"] = "authored" + report = self.repo.run() + self.assertTrue(any("passiveReport requires" in error for error in report.errors)) + self.assertFinding(report, "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + + def test_cfg_qty_4_passive_report_requires_a_maintained_corpus_check(self) -> None: + self.passive_report()["check"] = "true {file}" + report = self.repo.run() + self.assertTrue(any("passiveReport requires" in error for error in report.errors)) + self.assertFinding(report, "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + + def test_cfg_qty_4_passive_report_still_requires_both_bounds(self) -> None: + self.passive_report() + fields = self.repo.report["properties"]["filesChecked"] + for bound in ("minimum", "maximum"): + with self.subTest(bound=bound): + value = fields.pop(bound) + self.assertFinding(self.repo.run(), "CFG-QTY-4", R, at(REPORT_SCHEMA, "/properties/filesChecked")) + fields[bound] = value + def test_cfg_qty_4_accepts_a_bounded_type_whose_stated_minimum_is_zero(self) -> None: self.queue()["leewayMilliseconds"] = {"type": "integer", "format": "uint64", "minimum": 0, "maximum": 300000} self.assertNoFinding(self.repo.run(), "CFG-QTY-4") diff --git a/products/platform/scripts/test_run_config_conformance.py b/products/platform/scripts/test_run_config_conformance.py index 10237499aa..51c376a8c8 100644 --- a/products/platform/scripts/test_run_config_conformance.py +++ b/products/platform/scripts/test_run_config_conformance.py @@ -2208,6 +2208,45 @@ def setUp(self) -> None: self.cases = runner.load_cases(self.corpus / "cases") self.registry = runner.load_registry(ROOT / runner.REGISTRY) + def test_passive_casework_report_has_a_positive_and_both_integer_controls(self) -> None: + fmt = next(fmt for fmt in self.registry if fmt.id == "casework/report") + plan = runner.plan(ROOT, [fmt], self.cases, runner.load_harness(self.corpus / "formats.yaml")) + self.assertEqual([fmt.id], [item.id for item in plan.reached]) + self.assertNotIn(fmt.id, plan.skipped) + cells = {case.id: case for _, case in plan.cells} + self.assertEqual(set(cells), {"baseline", "integer-boundary-sweep"}) + source = (ROOT / fmt.example).read_text(encoding="utf-8") + bounds = cells["integer-boundary-sweep"] + mutations = runner.mutate(source, bounds.mutation, fmt) + self.assertIn("--deny-warnings", bounds.args) + observed = {(mutation.sites[0].values["pointer"], json.loads(mutation.text)["claims"]) + for mutation in mutations if mutation.sites[0].values["pointer"] == "/claims"} + self.assertEqual(observed, {("/claims", -1), ("/claims", 4294967296)}) + + def test_passive_report_cannot_have_a_corpus_waiver(self) -> None: + fmt = next(fmt for fmt in self.registry if fmt.id == "casework/report") + for expected in ( + runner.ExpectedFailures({(fmt.id, "baseline"): runner.Listed("fixture", "test")}, {}, {}), + runner.ExpectedFailures({}, {fmt.id: "fixture"}, {}), + ): + with self.assertRaisesRegex(runner.HarnessError, "passive report.*cannot"): + runner.validate_ids(expected, self.registry, self.cases, {}) + + def test_passive_report_check_that_always_accepts_fails_the_executable_corpus(self) -> None: + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / "rstack" + binary.write_text( + f"#!{sys.executable}\nprint('{{\"assessment\":\"owner-report-structure\",\"diagnostics\":[]}}')\n", + encoding="utf-8", + ) + binary.chmod(0o755) + stdout = io.StringIO() + with redirect_stdout(stdout): + exit_code = runner.main(["--bin-dir", directory, "--only-format", "casework/report", "--matrix"]) + self.assertEqual(exit_code, 1, stdout.getvalue()) + self.assertIn("casework/report\tbaseline\tpass", stdout.getvalue()) + self.assertIn("casework/report\tinteger-boundary-sweep\tfail", stdout.getvalue()) + def test_cfg_check_3_every_case_cites_known_rules(self) -> None: convention = (ROOT / "products/platform/CONFIG-CONVENTIONS.md").read_text(encoding="utf-8") known = set(re.findall(r"^\*\*(CFG-[A-Z]+-[0-9]+) \(", convention, re.MULTILINE)) diff --git a/products/render/README.md b/products/render/README.md index 855511d07e..a97d8b917e 100644 --- a/products/render/README.md +++ b/products/render/README.md @@ -63,6 +63,16 @@ The scaffold compiles offline out of the box: the binary embeds a baseline Latin font set. Scripts beyond Latin (Arabic, Hebrew, …) need a bundle font (see `registry-render init`'s note) and `registry-render check` names the gap. +## Qualify signed delivery + +Check development B-B and B-T delivery from the repository root with +`uv run --script products/render/scripts/test_signed_delivery.py`. +Pass `--render ` and `--scratch `. +Use the same arguments with `products/render/scripts/test_transit_delivery.py` +to check production-posture B-T through OpenBao Transit and an HTTPS timestamp +authority. The Transit check needs a local Linux Docker engine and the +OpenBao image pinned in the script. + ## Where to read next - [Deploy Registry Render](https://docs.registrystack.org/operate/registry-render/): install, diff --git a/products/render/examples/starter/dev.yaml b/products/render/examples/starter/dev.yaml index feecb19254..d23a8b851b 100644 --- a/products/render/examples/starter/dev.yaml +++ b/products/render/examples/starter/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: render, project: ., audience: "urn:example:render"} + render: + path: . +audiences: + render: "urn:example:render" people: reader: subject: starter-reader diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index 2a6e343038..2d93323b55 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -177,8 +177,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -708,6 +715,12 @@ } ] }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/render/scripts/test_signed_delivery.py b/products/render/scripts/test_signed_delivery.py new file mode 100644 index 0000000000..b571ee3b54 --- /dev/null +++ b/products/render/scripts/test_signed_delivery.py @@ -0,0 +1,422 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = ["pyhanko==0.38.1"] +# /// +# SPDX-License-Identifier: Apache-2.0 +"""Exercise the published Render seal endpoint and verify the delivered PDF.""" + +import argparse +import base64 +import hashlib +import http.client +import json +import os +import socket +import subprocess +import sys +import tempfile +import threading +import time +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +from asn1crypto import keys, tsp +from asn1crypto import x509 as asn1_x509 +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, rsa, utils +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID, ObjectIdentifier +from pyhanko.pdf_utils.reader import PdfFileReader +from pyhanko.sign.timestamps import DummyTimeStamper + +HERE = Path(__file__).resolve().parent +NOTICE = HERE.parents[2] / "crates/registry-render/tests/fixtures/sealed-notice" +ISSUER = "https://issuer.example.test" +AUDIENCE = "urn:render:qualification" +CLIENT = "records-service" +DOCUMENT_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.36") +REQUEST = json.dumps({ + "issuedAt": "2026-01-01T00:00:00Z", + "data": {"reference": "SYNTHETIC-01", "body": "Fictional qualification notice."}, +}) + + +def b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def sign_token(key, scope): + now = int(time.time()) + header = {"alg": "ES256", "kid": "fixture", "typ": "at+jwt"} + claims = { + "iss": ISSUER, "sub": "qualification-caller", "aud": AUDIENCE, + "client_id": CLIENT, "iat": now, "exp": now + 300, "scope": scope, + } + data = ".".join(b64url(json.dumps(value).encode()) for value in (header, claims)) + r, s = utils.decode_dss_signature(key.sign(data.encode(), ec.ECDSA(hashes.SHA256()))) + return data + "." + b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big")) + + +def issue_certificate(public_key, name, issuer, issuer_key, *, purpose=None, names=None): + now = datetime.now(timezone.utc) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) + is_root = issuer is None + builder = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(subject if is_root else issuer.subject) + .public_key(public_key) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(days=90)) + .add_extension(x509.BasicConstraints(ca=is_root, path_length=None), critical=True) + .add_extension(x509.KeyUsage( + digital_signature=not is_root, content_commitment=not is_root, + key_encipherment=False, data_encipherment=False, key_agreement=False, + key_cert_sign=is_root, crl_sign=is_root, encipher_only=False, decipher_only=False, + ), critical=True) + ) + if purpose is not None: + builder = builder.add_extension( + x509.ExtendedKeyUsage([purpose]), critical=purpose == ExtendedKeyUsageOID.TIME_STAMPING + ) + if names is not None: + builder = builder.add_extension(x509.SubjectAlternativeName(names), critical=False) + return builder.sign(issuer_key, hashes.SHA256()) + + +def write_fixture(binary, directory, *, transit_socket=None): + def run(*args): + subprocess.run([binary, *args], check=True, stdout=subprocess.DEVNULL, timeout=30) + + run("package", "--bundle", NOTICE, "--output", directory / "package") + secrets = directory / "secrets" + secrets.mkdir(mode=0o700) + csr_path = directory / "seal.csr" + key_settings = ["--key", secrets / "seal.jwk"] + if transit_socket is not None: + key_settings = [ + "--transit-unix-socket-path", transit_socket, "--transit-mount", "transit", + "--transit-key-name", "render-seal", "--transit-key-version", "1", + ] + run("keygen", *key_settings, "--csr", csr_path, + "--common-name", "Qualification test seal", "--country", "FR") + signer_key = x509.load_pem_x509_csr(csr_path.read_bytes()).public_key() + root_key = ec.generate_private_key(ec.SECP256R1()) + root = issue_certificate(root_key.public_key(), "Qualification root", None, root_key) + other_key = ec.generate_private_key(ec.SECP256R1()) + other = issue_certificate(other_key.public_key(), "Unrelated root", None, other_key) + leaf = issue_certificate( + signer_key, "Qualification test seal", root, root_key, purpose=DOCUMENT_SIGNING + ) + for name, certificates in ( + ("root.pem", [root]), ("other-root.pem", [other]), ("chain.pem", [leaf, root]) + ): + (directory / name).write_bytes(b"".join( + certificate.public_bytes(serialization.Encoding.PEM) for certificate in certificates + )) + + issuer_key = ec.generate_private_key(ec.SECP256R1()) + point = issuer_key.public_key().public_numbers() + jwks = {"keys": [{ + "kty": "EC", "crv": "P-256", "alg": "ES256", "kid": "fixture", + "x": b64url(point.x.to_bytes(32, "big")), "y": b64url(point.y.to_bytes(32, "big")), + }]} + (secrets / "jwks.json").write_text(json.dumps(jwks)) + return issuer_key, "sha256:" + leaf.fingerprint(hashes.SHA256()).hex() + + +@contextmanager +def timestamp_authority(directory, *, tls=None): + root_key = ec.generate_private_key(ec.SECP256R1()) + root = issue_certificate(root_key.public_key(), "Qualification TSA root", None, root_key) + (directory / "tsa-root.pem").write_bytes(root.public_bytes(serialization.Encoding.PEM)) + tsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + leaf = issue_certificate( + tsa_key.public_key(), "Qualification TSA", root, root_key, + purpose=ExtendedKeyUsageOID.TIME_STAMPING, + ) + fixture = DummyTimeStamper( + asn1_x509.Certificate.load(leaf.public_bytes(serialization.Encoding.DER)), + keys.PrivateKeyInfo.load(tsa_key.private_bytes( + serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + )), + ) + timestamp_digests = [] + + class TimestampHandler(BaseHTTPRequestHandler): + def do_POST(self): + self.connection.settimeout(3) + assert self.path == "/timestamp" + assert self.headers["Content-Type"] == "application/timestamp-query" + data = self.rfile.read(int(self.headers["Content-Length"])) + reply = fixture.request_tsa_response(tsp.TimeStampReq.load(data)) + timestamp_digests.append( + "sha256:" + hashlib.sha256(reply["time_stamp_token"].dump()).hexdigest() + ) + response = reply.dump() + self.send_response_only(200) + self.send_header("Content-Type", "application/timestamp-reply") + self.send_header("Content-Length", str(len(response))) + self.end_headers() + self.wfile.write(response) + + with HTTPServer(("127.0.0.1", 0), TimestampHandler) as server: + scheme = "http" + if tls is not None: + server.socket = tls.wrap_socket(server.socket, server_side=True) + scheme = "https" + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"{scheme}://127.0.0.1:{server.server_port}/timestamp", timestamp_digests + finally: + server.shutdown() + thread.join() + + +def request(port, path, *, token=None): + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=25) + try: + if token is None: + connection.request("GET", path) + else: + connection.request("POST", path, REQUEST, { + "Authorization": "Bearer " + token, + "Accept": "application/pdf", + "Content-Type": "application/json", + }) + response = connection.getresponse() + return response.status, response.headers, response.read() + finally: + connection.close() + + +def delivery( + binary, directory, issuer_key, *, tsa_url=None, transit_socket=None, + tsa_ca=False, expect_timestamp_failure=False, +): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + audit = directory / "audit.jsonl" + runtime = directory / "runtime.yaml" + if tsa_url is None: + timestamp_settings = "withoutTimestamp: seal-stops-validating-when-certificate-expires" + else: + timestamp_settings = f"timestampAuthority:\n url: {tsa_url}" + if tsa_ca: + timestamp_settings += "\n caBundleRef: secret:file/tsa-tls-root.pem" + posture = "development" + assurance = "local" + signer = "type: local-jwk\n privateKeyRef: secret:file/seal.jwk" + expected_warnings = ["render.posture.local-assurance"] + if transit_socket is not None: + posture = assurance = "production" + signer = ( + f"type: transit\n unixSocketPath: {json.dumps(str(transit_socket))}\n" + " mount: transit\n keyName: render-seal\n keyVersion: 1\n" + " attemptTimeoutMilliseconds: 2000" + ) + expected_warnings = [] + runtime.write_text(f"""\ +apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1 +kind: RenderRuntimeConfig +listener: + bind: 127.0.0.1:{port} +package: + root: {json.dumps(str(directory / 'package'))} +secretProviders: + file: + root: {json.dumps(str(directory / 'secrets'))} +authentication: + oidc: + issuers: + fixture: + issuer: {ISSUER} + audience: {AUDIENCE} + allowedClients: [{CLIENT}] + jwksSource: + type: static + documentRef: secret:file/jwks.json +audit: + path: {json.dumps(str(audit))} +assuranceProfile: {assurance} +signing: + seals: + ministry: + signer: + {signer} + certificateChainFile: {json.dumps(str(directory / 'chain.pem'))} + {timestamp_settings} + allowedClients: [{CLIENT}] +""") + checked = subprocess.run( + [binary, "check", "--bundle", directory / "package", "--runtime-config", runtime, + "--environment", "--posture", posture, "--format", "json"], + capture_output=True, timeout=30, + ) + report = json.loads(checked.stdout) + assert checked.returncode == 0 and report["ok"], report + assert [item["code"] for item in report["diagnostics"]] == expected_warnings, report + log_path = directory / "serve.jsonl" + with log_path.open("w") as log, subprocess.Popen( + [binary, "serve", "--runtime-config", runtime, "--posture", posture], + stdout=subprocess.DEVNULL, stderr=log, + ) as server: + try: + for _ in range(100): + if server.poll() is not None: + raise RuntimeError(f"Render exited before readiness ({server.returncode})") + try: + status, _, body = request(port, "/ready") + except ConnectionRefusedError: + time.sleep(0.1) + continue + if status == 200 and json.loads(body)["signing"]["ministry"]["status"] == "ready": + break + time.sleep(0.1) + else: + raise RuntimeError("Render seal did not become ready") + + path = "/v1/seal/notice" + status, headers, body = request(port, path, token=sign_token(issuer_key, "render:seal")) + if expect_timestamp_failure: + assert status == 502 and headers.get_content_type() == "application/problem+json" + assert json.loads(body)["code"] == "render.timestamp-failed" + else: + assert status == 200, f"seal returned HTTP {status}" + assert headers.get_content_type() == "application/pdf" + assert headers["X-Registry-Seal-Id"] == "ministry" + assert headers["X-Registry-Seal-Level"] == ("B-B" if tsa_url is None else "B-T") + assert ("X-Registry-Timestamped-At" in headers) == (tsa_url is not None) + if posture == "development": + assert headers["Registry-Posture"] == "development" + assert headers["X-Registry-Seal-Test-Only"] == "true" + else: + assert "Registry-Posture" not in headers + assert "X-Registry-Seal-Test-Only" not in headers + refused, _, problem = request(port, path, token=sign_token(issuer_key, "render:render")) + assert refused == 403, f"wrong scope returned HTTP {refused}" + refusal = json.loads(problem) + assert refusal["code"] == "render.forbidden" + if posture == "development": + assert refusal["failedCheck"] == "scope" + else: + assert "failedCheck" not in refusal + finally: + if server.poll() is None: + server.terminate() + try: + server.wait(timeout=10) + except subprocess.TimeoutExpired: + server.kill() + server.wait() + raise + assert server.returncode == 0, f"Render shutdown exited {server.returncode}" + warnings = [ + event["fields"].get("error_code") or event["fields"].get("problem") + for event in map(json.loads, log_path.read_text().splitlines()) + if event["level"] in ("WARN", "ERROR") + ] + if expect_timestamp_failure: + expected_warnings.append("timestamp-failed") + assert warnings == expected_warnings, warnings + entries = [json.loads(line) for line in audit.read_text().splitlines()] + if expect_timestamp_failure: + assert not any(entry["record"].get("outcome") == "sealed" for entry in entries) + assert any(entry["record"].get("problem") == "timestamp-failed" for entry in entries) + return headers, body, None + sealed, = (entry for entry in entries if entry["record"].get("outcome") == "sealed") + matching = [entry["phase"] for entry in entries + if entry["correlation"] == sealed["correlation"]] + assert matching == ["request", "response"], matching + for name, header in ( + ("documentDigest", "X-Registry-Document-Digest"), + ("signedFileDigest", "X-Registry-Signed-File-Digest"), + ("certificateDigest", "X-Registry-Certificate-Digest"), + ): + assert sealed["record"][name] == headers[header], name + return headers, body, sealed["record"] + + +def verify_delivery(directory, headers, pdf, expected_certificate, *, tsa_root=None): + signed_digest = "sha256:" + hashlib.sha256(pdf).hexdigest() + assert headers["X-Registry-Signed-File-Digest"] == signed_digest + assert headers["X-Registry-Certificate-Digest"] == expected_certificate + signed = directory / "document.pdf" + signed.write_bytes(pdf) + with signed.open("rb") as stream: + signature, = PdfFileReader(stream).embedded_signatures + certificate_digest = "sha256:" + hashlib.sha256(signature.signer_cert.dump()).hexdigest() + assert certificate_digest == expected_certificate + + def verify(path, *trust_roots): + roots = [argument for root in trust_roots for argument in ("--trust-root", root)] + result = subprocess.run( + [sys.executable, HERE / "validate-seal.py", "--pdf", path, + *roots, "--document-digest", + headers["X-Registry-Document-Digest"]], + capture_output=True, timeout=30, + ) + return result.returncode, json.loads(result.stdout) + + root = directory / "root.pem" + roots = [root] + if tsa_root is not None: + roots.append(tsa_root) + code, report = verify(signed, root) + assert code == 1 and not report["ok"], report + assert any( + check["name"] == "signature-timestamp-valid" and not check["ok"] + for check in report["checks"] + ), report + code, report = verify(signed, *roots) + assert (code, report["ok"], report["level"]) == ( + 0, True, headers["X-Registry-Seal-Level"] + ), report + code, report = verify(signed, directory / "other-root.pem") + assert code == 1 and not report["ok"], report + assert any(check["name"] == "trusted" and not check["ok"] for check in report["checks"]) + + # Change a byte in the original revision without breaking PDF syntax. + tampered = directory / "tampered.pdf" + assert pdf.startswith(b"%PDF-") and pdf[7:8].isdigit() + replacement = b"6" if pdf[7:8] != b"6" else b"7" + tampered.write_bytes(pdf[:7] + replacement + pdf[8:]) + code, report = verify(tampered, *roots) + assert code == 1 and not report["ok"], report + assert any(check["name"] == "intact" and not check["ok"] for check in report["checks"]), report + assert "sha256:" + hashlib.sha256(tampered.read_bytes()).hexdigest() != signed_digest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--render", type=Path, required=True, help="published Render executable") + parser.add_argument("--scratch", type=Path, required=True, help="parent for a private fixture") + args = parser.parse_args() + binary = args.render.resolve(strict=True) + os.umask(0o077) + with tempfile.TemporaryDirectory(prefix="render-delivery-", dir=args.scratch) as temporary: + directory = Path(temporary).resolve() + issuer_key, certificate = write_fixture(binary, directory) + headers, pdf, audit = delivery(binary, directory, issuer_key) + verify_delivery(directory, headers, pdf, certificate) + assert "timestampTokenDigest" not in audit + (directory / "timestamped").mkdir() + with timestamp_authority(directory) as (tsa_url, timestamp_digests): + # Each runtime needs its own audit file and a single fixture key set. + timestamped = directory / "timestamped" + issuer_key, certificate = write_fixture(binary, timestamped) + headers, pdf, audit = delivery(binary, timestamped, issuer_key, tsa_url=tsa_url) + verify_delivery(timestamped, headers, pdf, certificate, tsa_root=directory / "tsa-root.pem") + assert timestamp_digests == [audit["timestampTokenDigest"]] + print("B-B and B-T signed delivery passed: exact PDF, first revision, signer, audit, and refusals") + + +if __name__ == "__main__": + main() diff --git a/products/render/scripts/test_transit_delivery.py b/products/render/scripts/test_transit_delivery.py new file mode 100644 index 0000000000..68646662cc --- /dev/null +++ b/products/render/scripts/test_transit_delivery.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = ["pyhanko==0.38.1"] +# /// +# SPDX-License-Identifier: Apache-2.0 +"""Qualify production-posture Render with disposable OpenBao and an HTTPS TSA.""" + +import argparse +import http.client +import ipaddress +import json +import os +import socket +import ssl +import subprocess +import tempfile +import time +from contextlib import contextmanager +from pathlib import Path + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import ExtendedKeyUsageOID + +from test_signed_delivery import ( + delivery, + issue_certificate, + timestamp_authority, + verify_delivery, + write_fixture, +) + +OPENBAO = "ghcr.io/openbao/openbao@sha256:09f1eaaee351c329d75a5a89654d6e1ad4792998650c3cbf0c3513a76d9d9b6e" +POLICY = """ +path "transit/keys/render-seal" { + capabilities = ["read"] +} + +path "transit/sign/render-seal/sha2-256" { + capabilities = ["update"] + required_parameters = ["input", "key_version", "marshaling_algorithm", "prehashed"] + allowed_parameters = { + "input" = [] + "key_version" = ["1"] + "marshaling_algorithm" = ["jws"] + "prehashed" = [true] + } +} +""" + + +@contextmanager +def bao_process(config, command): + directory = config.parent + identity = f"{os.getuid()}:{os.getgid()}" + container_id = subprocess.check_output( + ["docker", "run", "--pull", "never", "--rm", "--detach", + "--network", "host", "--user", identity, + "--mount", f"type=bind,source={directory},target={directory}", + "--entrypoint", "bao", OPENBAO, command, "-config", config], + text=True, timeout=30, + ).strip() + try: + yield + finally: + subprocess.run(["docker", "stop", "--time", "3", container_id], + check=True, stdout=subprocess.DEVNULL, timeout=15) + + +def bao_request(connection, method, path, *, token=None, data=None): + headers = {"X-Vault-Request": "true", "Content-Type": "application/json"} + if token is not None: + headers["X-Vault-Token"] = token + try: + connection.request(method, "/v1/" + path, json.dumps(data) if data is not None else None, + headers) + response = connection.getresponse() + payload = response.read() + return response.status, json.loads(payload) if payload else None + finally: + connection.close() + + +def wait_for(probe, expected): + for _ in range(50): + try: + status, result = probe() + except (ConnectionRefusedError, FileNotFoundError): + time.sleep(0.1) + continue + if status == expected: + return result + time.sleep(0.1) + raise RuntimeError(f"OpenBao did not return HTTP {expected} for the readiness probe") + + +class UnixHttpConnection(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost", timeout=3) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX) + self.sock.settimeout(self.timeout) + self.sock.connect(str(self.path)) + + +@contextmanager +def transit_proxy(directory): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + server = directory / "bao.hcl" + server.write_text(f""" +disable_mlock = true +api_addr = "http://127.0.0.1:{port}" +storage "inmem" {{}} +listener "tcp" {{ + address = "127.0.0.1:{port}" + tls_disable = true +}} +""") + root_token = None + + def request(method, path, expected, data=None): + status, response = bao_request( + http.client.HTTPConnection("127.0.0.1", port, timeout=3), + method, path, token=root_token, data=data, + ) + assert status == expected, f"OpenBao {method} {path}: HTTP {status}, expected {expected}" + return response + + with bao_process(server, "server"): + def health(): + return bao_request(http.client.HTTPConnection("127.0.0.1", port, timeout=3), + "GET", "sys/health") + + wait_for(health, 501) + init = request("PUT", "sys/init", 200, {"secret_shares": 1, "secret_threshold": 1}) + root_token = init["root_token"] + request("PUT", "sys/unseal", 200, {"key": init["keys_base64"][0]}) + request("POST", "sys/mounts/transit", 204, {"type": "transit"}) + request("POST", "transit/keys/render-seal", 200, { + "type": "ecdsa-p256", "derived": False, "exportable": False, + "allow_plaintext_backup": False, + }) + request("PUT", "sys/policies/acl/render-seal", 204, {"policy": POLICY}) + request("POST", "sys/auth/approle", 204, {"type": "approle"}) + request("POST", "auth/approle/role/render-seal", 204, { + "token_policies": ["render-seal"], "token_ttl": "10m", "token_max_ttl": "10m", + "secret_id_ttl": "10m", + }) + role = request("GET", "auth/approle/role/render-seal/role-id", 200) + secret = request("POST", "auth/approle/role/render-seal/secret-id", 200) + (directory / "role-id").write_text(role["data"]["role_id"]) + (directory / "secret-id").write_text(secret["data"]["secret_id"]) + unix_socket = directory / "bao.sock" + agent = directory / "agent.hcl" + agent.write_text(f""" +vault {{ + address = "http://127.0.0.1:{port}" + retry {{ num_retries = -1 }} +}} +auto_auth {{ + method "approle" {{ + config = {{ + role_id_file_path = {json.dumps(str(directory / 'role-id'))} + secret_id_file_path = {json.dumps(str(directory / 'secret-id'))} + }} + }} +}} +api_proxy {{ use_auto_auth_token = "force" }} +listener "unix" {{ + address = {json.dumps(str(unix_socket))} + tls_disable = true + socket_mode = "0660" + socket_user = "{os.getuid()}" + socket_group = "{os.getgid()}" + require_request_header = true +}} +""") + with bao_process(agent, "agent"): + metadata = wait_for(lambda: bao_request( + UnixHttpConnection(unix_socket), "GET", "transit/keys/render-seal" + ), 200)["data"] + assert metadata["type"] == "ecdsa-p256" and metadata["latest_version"] == 1 + for setting in ("derived", "exportable", "allow_plaintext_backup"): + assert metadata[setting] is False, setting + owner = unix_socket.stat() + mode = owner.st_mode & 0o777 + assert mode == 0o660, f"OpenBao Agent socket has mode {mode:#o}" + assert (owner.st_uid, owner.st_gid) == (os.getuid(), os.getgid()) + forced, _ = bao_request(UnixHttpConnection(unix_socket), "GET", "sys/mounts", + token=root_token) + assert forced == 403, f"proxy forwarded the caller token, HTTP {forced}" + yield unix_socket + + +def tsa_tls(directory): + root_key = ec.generate_private_key(ec.SECP256R1()) + root = issue_certificate(root_key.public_key(), "Qualification TLS root", None, root_key) + key = ec.generate_private_key(ec.SECP256R1()) + leaf = issue_certificate( + key.public_key(), "Qualification RFC 3161 server", root, root_key, + purpose=ExtendedKeyUsageOID.SERVER_AUTH, + names=[x509.IPAddress(ipaddress.IPv4Address("127.0.0.1"))], + ) + chain = directory / "tls-chain.pem" + chain.write_bytes(leaf.public_bytes(serialization.Encoding.PEM)) + private = directory / "tls-key.pem" + private.write_bytes(key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + )) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(chain, private) + return context, root.public_bytes(serialization.Encoding.PEM) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--render", type=Path, required=True, help="published Render executable") + parser.add_argument("--scratch", type=Path, required=True, help="parent for a private fixture") + args = parser.parse_args() + binary = args.render.resolve(strict=True) + os.umask(0o077) + with tempfile.TemporaryDirectory(prefix="transit-", dir=args.scratch) as temporary: + directory = Path(temporary).resolve() + tls, tls_root = tsa_tls(directory) + with transit_proxy(directory) as proxy, timestamp_authority(directory, tls=tls) as tsa: + url, digests = tsa + untrusted = directory / "untrusted" + untrusted.mkdir() + issuer, _ = write_fixture(binary, untrusted, transit_socket=proxy) + delivery(binary, untrusted, issuer, tsa_url=url, transit_socket=proxy, + expect_timestamp_failure=True) + assert digests == [], "a timestamp query crossed the untrusted TLS connection" + + trusted = directory / "trusted" + trusted.mkdir() + issuer, certificate = write_fixture(binary, trusted, transit_socket=proxy) + (trusted / "secrets/tsa-tls-root.pem").write_bytes(tls_root) + headers, pdf, audit = delivery( + binary, trusted, issuer, tsa_url=url, transit_socket=proxy, tsa_ca=True + ) + verify_delivery(trusted, headers, pdf, certificate, tsa_root=directory / "tsa-root.pem") + assert digests == [audit["timestampTokenDigest"]] + assert { + path.name for path in (trusted / "secrets").iterdir() + } == {"jwks.json", "tsa-tls-root.pem"} + print("Production-posture Render passed with OpenBao Transit and an independently trusted HTTPS TSA") + + +if __name__ == "__main__": + main() diff --git a/products/scheduling/AGENTS.md b/products/scheduling/AGENTS.md index 3d3e965425..dff3278c03 100644 --- a/products/scheduling/AGENTS.md +++ b/products/scheduling/AGENTS.md @@ -33,13 +33,12 @@ product. Document Store, Evidence, or Messaging crate, and none of those products reach a scheduling crate. Run `scripts/check_dependency_direction.py` after dependency changes. -- Each directory under `examples/` is exactly what `schedulingctl init` writes - for the template with the same name (the `resource-reservations` example also - keeps a README the template does not write), and the checkpoint fails if any - of the three pairs drifts apart. When `schedulingctl init` starts emitting or - changing a file, copy that output into every applicable committed example - (`standalone-exact-time`, `standalone-arrival-window`, and - `resource-reservations`) in the same commit. +- The three starter directories under `examples/` are the checked snapshots + for `schedulingctl init` on 2026-10-01. The `resource-reservations` example + also keeps a README the template does not write. The CLI test checks the + exact snapshot bytes and the checkpoint verifies both fresh and committed + projects. When `init` changes a file, keep each applicable snapshot in + sync and date its fixture cases relative to the fixture clock. - Keep authored examples and the checkpoint demo small. Do not add a later-wave surface to close a documentation obligation; record the exclusion instead. diff --git a/products/scheduling/README.md b/products/scheduling/README.md index 7081d86d31..f68d9557aa 100644 --- a/products/scheduling/README.md +++ b/products/scheduling/README.md @@ -73,8 +73,10 @@ serves the runtime on loopback. See `products/scheduling/demo/README.md`. - `contracts/`: the security invariant matrix, its test traceability, and recorded decisions. - `examples/`: `standalone-exact-time`, `standalone-arrival-window`, and `resource-reservations` - are what `schedulingctl init --template ` writes, and `formats/` holds a sample - `schedulingctl` report. The `resource-reservations` example also keeps a README. + are snapshots of `schedulingctl init --template ` as of 2026-10-01. Their five fixtures + replay against their declared clocks. Run `init` for live supply dated from the day you create + a project. `formats/` holds a sample `schedulingctl` report, and `resource-reservations` also + keeps a README. - `generated/`: the OpenAPI description and the JSON Schemas derived from the Rust types. Do not edit them by hand. - `demo/`: the acceptance demo. @@ -99,9 +101,9 @@ cargo build --locked -p registry-schedulingctl products/scheduling/scripts/check-checkpoint.sh ``` -`examples/standalone-exact-time/` is exactly what -`schedulingctl init --template standalone-exact-time` writes, and the checkpoint fails if the two -drift apart. +The checkpoint checks and replays all three committed examples and freshly initialized projects. +The CLI unit test verifies that initialization on the reference date reproduces the example files +byte for byte. For PostgreSQL execution, the destructive test suites require a separate disposable database and the `postgres-test` feature: diff --git a/products/scheduling/examples/resource-reservations/dev.yaml b/products/scheduling/examples/resource-reservations/dev.yaml index 533a1adc41..f501107a83 100644 --- a/products/scheduling/examples/resource-reservations/dev.yaml +++ b/products/scheduling/examples/resource-reservations/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: scheduling, project: ., audience: "urn:example:scheduling"} + scheduling: + path: . +audiences: + scheduling: "urn:example:scheduling" people: reader: subject: starter-reader diff --git a/products/scheduling/examples/standalone-arrival-window/dev.yaml b/products/scheduling/examples/standalone-arrival-window/dev.yaml index 533a1adc41..f501107a83 100644 --- a/products/scheduling/examples/standalone-arrival-window/dev.yaml +++ b/products/scheduling/examples/standalone-arrival-window/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: scheduling, project: ., audience: "urn:example:scheduling"} + scheduling: + path: . +audiences: + scheduling: "urn:example:scheduling" people: reader: subject: starter-reader diff --git a/products/scheduling/examples/standalone-exact-time/dev.yaml b/products/scheduling/examples/standalone-exact-time/dev.yaml index 533a1adc41..f501107a83 100644 --- a/products/scheduling/examples/standalone-exact-time/dev.yaml +++ b/products/scheduling/examples/standalone-exact-time/dev.yaml @@ -3,7 +3,10 @@ apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 kind: RStackDev issuer: https://identity.starter.example.test products: - - {product: scheduling, project: ., audience: "urn:example:scheduling"} + scheduling: + path: . +audiences: + scheduling: "urn:example:scheduling" people: reader: subject: starter-reader diff --git a/products/scheduling/generated/runtime/runtime.schema.json b/products/scheduling/generated/runtime/runtime.schema.json index 308e1f008d..1a2795d840 100644 --- a/products/scheduling/generated/runtime/runtime.schema.json +++ b/products/scheduling/generated/runtime/runtime.schema.json @@ -332,8 +332,15 @@ "additionalProperties": false, "description": "The file secret provider.", "properties": { + "mountPolicy": { + "$ref": "#/$defs/SecretMountPolicy", + "description": "`compose-native` also accepts a root-owned regular file with one hard\nlink and mode exactly 0444, the shape of a Docker Compose secret mount.\nEvery user in the container can read such a file. Startup and `check`\nreport this explicit production setting. Without it, only the file\nshapes `root` describes are accepted.", + "x-registry-explicit-production": [ + "platform.posture.compose-native-secret-mount" + ] + }, "root": { - "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning.", + "description": "Absolute directory holding one file per secret. A name may be a\nrelative link that stays below this directory, through at most 8 links.\nThe file it reaches must be a regular file with one hard link, owned by\nthe runtime user with mode 0400 or 0600, or owned by root with no\naccess beyond group read (0440 or 0640) when the runtime is not root.\nA process that declared development loads a file with looser read or\nmode bits and logs a warning. A public document, such as a static JWKS\nor a CA bundle, may also be readable by group and others.", "pattern": "^/", "type": "string" } @@ -920,6 +927,12 @@ "$ref": "#/$defs/ExternalId", "description": "The name of the claim that carries scopes." }, + "SecretMountPolicy": { + "enum": [ + "compose-native" + ], + "type": "string" + }, "SecretProvidersConfig": { "additionalProperties": false, "anyOf": [ diff --git a/products/scheduling/scripts/check-checkpoint.sh b/products/scheduling/scripts/check-checkpoint.sh index 80373a5067..dc4da027f8 100755 --- a/products/scheduling/scripts/check-checkpoint.sh +++ b/products/scheduling/scripts/check-checkpoint.sh @@ -41,8 +41,51 @@ cleanup() { } trap cleanup EXIT HUP INT TERM -for template in standalone-exact-time standalone-arrival-window; do +for template in standalone-exact-time standalone-arrival-window resource-reservations; do + init_before=$(date -u +%Y-%m-%d) "$schedulingctl_bin" init "$work/$template" --template "$template" >/dev/null + init_after=$(date -u +%Y-%m-%d) + # Accept either UTC day if init crosses midnight. Replay uses fixture + # clocks and the later snapshot comparison deliberately ignores dates. + python3 - "$work/$template" "$init_before" "$init_after" <<'PY' +import sys +from datetime import date, timedelta +from pathlib import Path + +import yaml + +project = Path(sys.argv[1]) +first_day, last_day = sorted(date.fromisoformat(day) for day in sys.argv[2:]) +records = yaml.safe_load((project / "records.yaml").read_text(encoding="utf-8")) + +def require(condition, detail): + if not condition: + sys.exit(f"{project.name}: {detail} for UTC init dates {first_day} to {last_day}") + +if project.name == "standalone-arrival-window": + starts = {window["start"].date() for window in records["windows"]} + require(len(starts) == 1, "arrival windows must share one date") + start = starts.pop() + earliest = first_day + timedelta(days=7) + latest = last_day + timedelta(days=13) + require(start.weekday() == 5 and earliest <= start <= latest, + "arrival windows are outside the starter date range") +else: + openings = yaml.safe_load((project / "scheduling.yaml").read_text(encoding="utf-8"))["openings"] + if project.name == "standalone-exact-time": + opening = openings["bangkok-counter-hours"] + future_day = openings["new-york-hall-hours"]["effectiveFrom"] + label = "New York fold opening" + else: + opening = openings["hall-hours"] + maintenance = next(item for item in records["exceptions"] if item["id"] == "maintenance-day") + future_day = maintenance["date"] + label = "New York maintenance closure" + first_covered = max(first_day, date.fromisoformat(opening["effectiveFrom"])) + last_covered = min(last_day, date.fromisoformat(opening["effectiveUntil"])) + require(first_covered <= last_covered, "regular opening does not cover initialization") + require(date.fromisoformat(future_day) > first_covered, f"{label} is stale") +PY "$schedulingctl_bin" check "$work/$template" >/dev/null "$schedulingctl_bin" test "$work/$template" >/dev/null "$schedulingctl_bin" explain "$work/$template" >/dev/null @@ -153,14 +196,31 @@ if [ "$written" != "$sums_digest" ]; then exit 1 fi -# The committed examples are the starter templates' output, so neither can -# drift from what an adopter initializes, including its live records document. +# The committed examples match what an adopter initializes, with the live +# and fixture dates shifted from the snapshot to the day of init. The CLI +# unit test compares the exact bytes with init pinned to the snapshot date. # The resource-reservations example also carries a README, which the template # does not write, so the comparison excludes that one file. for template in standalone-exact-time standalone-arrival-window resource-reservations; do example="$repo_root/products/scheduling/examples/$template" - "$schedulingctl_bin" init "$work/example-$template" --template "$template" >/dev/null - diff -r -x README.md "$work/example-$template" "$example" >/dev/null + python3 - "$work/$template" "$example" <<'PY' +import re +import sys +from pathlib import Path + +date = re.compile(rb"(?", path.read_bytes()) + for path in root.rglob("*") if path.is_file() and path.name != "README.md" + } + +fresh, snapshot = (files(Path(root)) for root in sys.argv[1:]) +for path in sorted(fresh.keys() | snapshot.keys()): + if fresh.get(path) != snapshot.get(path): + sys.exit(f"{sys.argv[2]}/{path}: starter differs from snapshot after masking dates") +PY "$schedulingctl_bin" check "$example" >/dev/null "$schedulingctl_bin" test "$example" >/dev/null done diff --git a/release/NIGHTLY.md b/release/NIGHTLY.md index 505faa045e..4bb4a8550d 100644 --- a/release/NIGHTLY.md +++ b/release/NIGHTLY.md @@ -59,9 +59,9 @@ to v2.4 and v2.5 respectively, from the base version that version; `nightly.json`, the asset name, and its checksum authenticate the exact nightly source. No profile carries the Registry Document Store, which stays held out while -`DOCUMENTS_FIRST_RELEASE` is `None`. The session service is also held out -while `SESSION_FIRST_RELEASE` is `None`. No release script builds -`registry-session` yet. An incompatible inventory requires a +`DOCUMENTS_FIRST_RELEASE` is `None`. No profile carries `registry-session` +either: `SESSION_FIRST_RELEASE` adds it to numbered releases only, and the +frozen nightly inventories keep their existing set. An incompatible inventory requires a new schema and profile. The reader still accepts frozen `registry-stack.nightly.v1` manifests, including historical v0.39.0 nightlies that carried Relay, so an existing channel head can be reconciled and advanced diff --git a/release/OPERATIONS.md b/release/OPERATIONS.md index ba18a049c1..d942284971 100644 --- a/release/OPERATIONS.md +++ b/release/OPERATIONS.md @@ -216,8 +216,10 @@ exclude its image, binaries, installers, and client namespace. `RENDER_FIRST_RELEASE`, and `EVIDENCE_OID4VCI_IMAGE_FIRST_RELEASE` in `release/scripts/release_roster.py` own those boundaries. The Document Store is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`. -The session service is held out while `SESSION_FIRST_RELEASE` is `None`. -No release script builds, stages or publishes `registry-session` yet. +`SESSION_FIRST_RELEASE` adds the `registry-session` binary for Linux amd64, +Linux arm64 and macOS arm64 from `v0.51.0`. It is a standalone asset of the +`session` release unit, not an `rstack` component, and has no image or +installer. The existing OID4VCI binary stays in earlier inventories. v0.38.0 also adds the Linux amd64 `discoveryctl` asset beside the existing Discovery runtime asset, completing the released authoring and runtime pair. Earlier releases require operators to diff --git a/release/VERIFY.md b/release/VERIFY.md index 305ef1785a..1be92c8099 100644 --- a/release/VERIFY.md +++ b/release/VERIFY.md @@ -284,8 +284,10 @@ Registry Adapter binaries join in `v0.46.0`, as set by `ADAPTER_IMAGE_FIRST_RELEASE` is unset. The Registry Document Store is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`, and no release roster names it. -The session service is held out while `SESSION_FIRST_RELEASE` is `None`. -No release script builds, stages or publishes `registry-session` yet. +`SESSION_FIRST_RELEASE` controls the `registry-session` binary for numbered +Linux amd64, Linux arm64 and macOS arm64 payloads from `v0.51.0`. Session has +no image or installer in this roster, `rstack` does not install it, and the +frozen nightly profiles keep their existing inventory. `BREG_SERVICES_FIRST_RELEASE`, `MESSAGING_FIRST_RELEASE`, `RENDER_FIRST_RELEASE`, `EVIDENCE_OID4VCI_IMAGE_FIRST_RELEASE`, and the three Coordinator release constants in `release/scripts/release_roster.py` diff --git a/release/scripts/build-additional-platform-binaries.sh b/release/scripts/build-additional-platform-binaries.sh index b369c3007e..bdc507225f 100644 --- a/release/scripts/build-additional-platform-binaries.sh +++ b/release/scripts/build-additional-platform-binaries.sh @@ -18,7 +18,11 @@ if [[ "$#" == 6 ]]; then exclude_discovery=1 fi repo_root="$(git rev-parse --show-toplevel)" -builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}")" +roster_flags=() +if [[ "${tag}" == "v${version}-nightly."* ]]; then + roster_flags+=(--nightly) +fi +builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}" "${roster_flags[@]}")" cargo_bin="${CARGO:-cargo}" if [[ -z "${builds}" ]]; then exit 0 diff --git a/release/scripts/build-nightly-linux-arm64.sh b/release/scripts/build-nightly-linux-arm64.sh index d8d24c50f9..d9638ecb2f 100644 --- a/release/scripts/build-nightly-linux-arm64.sh +++ b/release/scripts/build-nightly-linux-arm64.sh @@ -65,7 +65,7 @@ from pathlib import Path sys.path.insert(0, str(Path('release/scripts').resolve())) from release_candidate import _release_payload_inventory version, tag, target = sys.argv[1:] -for asset, kind in _release_payload_inventory(version).items(): +for asset, kind in _release_payload_inventory(version, nightly=True).items(): if kind != 'binary' or not asset.endswith('-linux-arm64'): continue binary = asset.split(f'-v{version}-', 1)[0] diff --git a/release/scripts/build-release-binaries.sh b/release/scripts/build-release-binaries.sh index 38c0a931ed..778eed9208 100755 --- a/release/scripts/build-release-binaries.sh +++ b/release/scripts/build-release-binaries.sh @@ -165,6 +165,10 @@ include_coordinator_image=0 if [[ "$(python3 "${script_dir}/release_roster.py" coordinator-in-release "${version}")" == true ]]; then include_coordinator_image=1 fi +include_session=0 +if [[ -z "${nightly_tag}" && "$(python3 "${script_dir}/release_roster.py" session-in-release "${version}")" == true ]]; then + include_session=1 +fi # Adapter binaries have an independent boundary from image publication. include_adapter=0 adapter_in_release="$(python3 "${script_dir}/release_roster.py" \ @@ -358,6 +362,13 @@ build_payload() { fi fi + if [[ "${include_session}" -eq 1 ]]; then + cargo build --release --locked -p registry-session --bin registry-session + cp target/release/registry-session "dist/bin/registry-session-${RELEASE_TAG}-linux-amd64" + check_version "dist/bin/registry-session-${RELEASE_TAG}-linux-amd64" \ + "registry-session ${RELEASE_TAG#v}" + fi + # One invocation per binary keeps each product's feature boundary. if [[ "${include_adapter}" -eq 1 ]]; then cargo build --release --locked \ @@ -729,6 +740,9 @@ if [[ "${group}" == all || "${group}" == core ]]; then image_bin_binaries+=(coordinator coordinatorctl) fi fi + if [[ "${include_session}" -eq 1 ]]; then + bin_assets+=("registry-session-${tag}-linux-amd64") + fi if [[ "${include_adapter}" -eq 1 ]]; then bin_assets+=( "adapter-${tag}-linux-amd64" diff --git a/release/scripts/build-release-native-platform.sh b/release/scripts/build-release-native-platform.sh index 6d029cb95f..fac430bf27 100755 --- a/release/scripts/build-release-native-platform.sh +++ b/release/scripts/build-release-native-platform.sh @@ -343,7 +343,11 @@ build_scheduling() { check_version "schedulingctl ${display_version}" } -additional_platform_builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}")" +roster_flags=() +if [[ -n "${nightly_tag}" ]]; then + roster_flags+=(--nightly) +fi +additional_platform_builds="$(python3 "${repo_root}/release/scripts/release_roster.py" additional-platform-builds "${version}" "${roster_flags[@]}")" if [[ "${exclude_discovery}" -eq 1 ]]; then filtered_platform_builds="" while read -r package binary; do diff --git a/release/scripts/merge-release-binary-shards.py b/release/scripts/merge-release-binary-shards.py index f0bd56741d..5607bf7686 100755 --- a/release/scripts/merge-release-binary-shards.py +++ b/release/scripts/merge-release-binary-shards.py @@ -141,6 +141,8 @@ def rosters( f"coordinatorctl-{tag}-linux-amd64", ] ) + if nightly_tag is None and release_roster.session_in_release(parsed): + common.append(f"registry-session-{tag}-linux-amd64") if release_roster.adapter_in_release(parsed): common.extend( [ diff --git a/release/scripts/merge-release-native-platform-shards.py b/release/scripts/merge-release-native-platform-shards.py index 7d240445ec..9927c627c5 100755 --- a/release/scripts/merge-release-native-platform-shards.py +++ b/release/scripts/merge-release-native-platform-shards.py @@ -82,7 +82,7 @@ def rosters( core.insert(0, f"relayctl-{tag}-{ASSET}") if parsed >= MINT_RETIREMENT_VERSION: core.remove(f"mint-{tag}-{ASSET}") - additional = release_roster.additional_platform_builds(parsed) + additional = release_roster.additional_platform_builds(parsed, nightly=nightly_tag is not None) additional_core = [ f"{binary}-{tag}-{ASSET}" for _, binary in additional diff --git a/release/scripts/nightly_release.py b/release/scripts/nightly_release.py index 5544fa6f49..98a9ee6c56 100644 --- a/release/scripts/nightly_release.py +++ b/release/scripts/nightly_release.py @@ -641,7 +641,7 @@ def assemble( expected_roster = current_roster(base, record["tag"]) if record.get("schema_version") != SCHEMA_V2 or record.get("roster") != expected_roster: raise NightlyError("build plan source roster mismatch") - release_assets = release_candidate._release_payload_inventory(base) + release_assets = release_candidate._release_payload_inventory(base, nightly=True) for name, kind in release_assets.items(): if kind == "notice": notice = ROOT / name diff --git a/release/scripts/registry-release b/release/scripts/registry-release index 0dcfd38f41..4565d23fcd 100755 --- a/release/scripts/registry-release +++ b/release/scripts/registry-release @@ -295,6 +295,8 @@ def artifact_inventory_errors(version: str, artifacts: dict[Any, Any]) -> list[s expected_inventory.add("registry-render") if release_roster.coordinator_binaries_in_release(parsed_version): expected_inventory.update({"coordinator", "coordinatorctl"}) + if release_roster.session_in_release(parsed_version): + expected_inventory.add("registry-session") if release_roster.adapter_in_release(parsed_version): expected_inventory.update({"adapter", "adapterctl"}) if release_roster.rstack_in_release(parsed_version): diff --git a/release/scripts/release_candidate.py b/release/scripts/release_candidate.py index 71b4639d2d..47af0ecffc 100644 --- a/release/scripts/release_candidate.py +++ b/release/scripts/release_candidate.py @@ -374,7 +374,7 @@ def _version_uses_release_docs(version: tuple[int, int, int]) -> bool: return version >= DOCS_RELEASE_RESUMPTION_VERSION -def _release_payload_inventory(version: str) -> dict[str, str]: +def _release_payload_inventory(version: str, *, nightly: bool = False) -> dict[str, str]: tag = f"v{version}" version_tuple = tuple(int(part) for part in version.split(".")) inventory = { @@ -538,7 +538,7 @@ def _release_payload_inventory(version: str) -> dict[str, str]: inventory[f"registry-language-server-{tag}-macos-arm64"] = "binary" if version_tuple >= THIRD_PARTY_NOTICES_MINIMUM_VERSION: inventory["THIRD_PARTY_NOTICES"] = "notice" - for _, binary in release_roster.additional_platform_builds(version_tuple): + for _, binary in release_roster.additional_platform_builds(version_tuple, nightly=nightly): for platform in ("linux-amd64", "linux-arm64", "macos-arm64"): inventory[f"{binary}-{tag}-{platform}"] = "binary" for installer in release_roster.additional_installers(version_tuple): diff --git a/release/scripts/release_roster.py b/release/scripts/release_roster.py index 609b851abf..12dcd8c463 100644 --- a/release/scripts/release_roster.py +++ b/release/scripts/release_roster.py @@ -68,10 +68,10 @@ script builds, stages, or publishes them yet, so the product stays held until it is releasable. -``SESSION_FIRST_RELEASE`` is the single place that decides which release -first ships the ``registry-session`` binary and any image or security evidence -of its own. No release script builds, stages, or publishes it yet, so the -service stays held until it is releasable. +``SESSION_FIRST_RELEASE`` decides which numbered release first includes the +``registry-session`` binary in the native platform builds, from v0.51.0. It is +a standalone release asset that ``rstack`` does not install. Its image and +the frozen nightly inventories are independent of this gate. ``PYTHON_311_ABI_FIRST_RELEASE`` is the single place that decides which release first builds the Python client wheels against the Python 3.11 stable @@ -114,7 +114,7 @@ DOCUMENTS_FIRST_RELEASE: tuple[int, int, int] | None = None -SESSION_FIRST_RELEASE: tuple[int, int, int] | None = None +SESSION_FIRST_RELEASE: tuple[int, int, int] | None = (0, 51, 0) COORDINATOR_BINARY_FIRST_RELEASE: tuple[int, int, int] = (0, 44, 0) @@ -137,6 +137,7 @@ ("registry-manifest-cli", "registry-manifest"), ("registry-coordinator", "coordinator"), ("registry-coordinator", "coordinatorctl"), + ("registry-session", "registry-session"), ("registry-adapter", "adapter"), ("registry-adapterctl", "adapterctl"), ) @@ -153,7 +154,7 @@ } -def additional_platform_builds(version: tuple[int, int, int]): +def additional_platform_builds(version: tuple[int, int, int], *, nightly: bool = False): """Return the additional native binaries without changing historical releases.""" if tuple(version) < ALL_PLATFORMS_FIRST_RELEASE: return () @@ -164,6 +165,7 @@ def additional_platform_builds(version: tuple[int, int, int]): "registry-discoveryctl": discoveryctl_in_release(version), "registry-render": render_in_release(version), "registry-coordinator": coordinator_binaries_in_release(version), + "registry-session": not nightly and session_in_release(version), "registry-adapter": adapter_in_release(version), "registry-adapterctl": adapter_in_release(version), } @@ -372,6 +374,10 @@ def main(argv: list[str] | None = None) -> int: commands = parser.add_subparsers(dest="command", required=True) platforms = commands.add_parser("additional-platform-builds") platforms.add_argument("version", type=version_argument) + platforms.add_argument("--nightly", action="store_true") + session = commands.add_parser("session-in-release") + session.add_argument("version", type=version_argument) + session.set_defaults(in_release=session_in_release) coordinator_binaries = commands.add_parser("coordinator-binaries-in-release") coordinator_binaries.add_argument("version", type=version_argument) coordinator_binaries.set_defaults(in_release=coordinator_binaries_in_release) @@ -481,7 +487,7 @@ def main(argv: list[str] | None = None) -> int: relay.set_defaults(in_release=relay_in_release) args = parser.parse_args(argv) if args.command == "additional-platform-builds": - for crate, binary in additional_platform_builds(args.version): + for crate, binary in additional_platform_builds(args.version, nightly=args.nightly): print(crate, binary) return 0 print("true" if args.in_release(args.version) else "false") diff --git a/release/scripts/rstack_components.py b/release/scripts/rstack_components.py index f7032e34ff..e9b838a22b 100644 --- a/release/scripts/rstack_components.py +++ b/release/scripts/rstack_components.py @@ -82,7 +82,7 @@ # These release binaries are consumed directly and are deliberately not # installed as product components by rstack. -DISTRIBUTION_ONLY_BINARIES = {"registry-language-server"} +DISTRIBUTION_ONLY_BINARIES = {"registry-language-server", "registry-session"} def _binary_name(asset_name: str, tag: str) -> tuple[str, str]: diff --git a/release/scripts/test_merge_release_binary_shards.py b/release/scripts/test_merge_release_binary_shards.py index 3b4afb7b3c..010b140f90 100644 --- a/release/scripts/test_merge_release_binary_shards.py +++ b/release/scripts/test_merge_release_binary_shards.py @@ -75,6 +75,18 @@ def digest(data: bytes) -> str: class MergeReleaseBinaryShardsTest(unittest.TestCase): + def test_session_is_a_numbered_core_binary_and_has_no_image(self) -> None: + version = "0.51.0" + nightly_tag = f"v{version}-nightly.20261201.{SOURCE_SHA}" + with mock.patch.object(MODULE.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + past, _ = MODULE.rosters("0.50.0") + numbered, images = MODULE.rosters(version) + nightly, _ = MODULE.rosters(version, nightly_tag) + self.assertNotIn("registry-session-v0.50.0-linux-amd64", past["core"]) + self.assertIn("registry-session-v0.51.0-linux-amd64", numbered["core"]) + self.assertNotIn(f"registry-session-{nightly_tag}-linux-amd64", nightly["core"]) + self.assertNotIn("registry-session", dict(images)) + def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) diff --git a/release/scripts/test_nightly_release.py b/release/scripts/test_nightly_release.py index d2232057fa..f1c958abca 100644 --- a/release/scripts/test_nightly_release.py +++ b/release/scripts/test_nightly_release.py @@ -48,6 +48,20 @@ class NightlyTest(unittest.TestCase): + def test_numbered_session_does_not_change_frozen_nightly_inventory(self): + version = "0.51.0" + tag = f"v{version}-nightly.20261201.{SHA}" + before = nightly.current_roster(version, tag) + with patch.object(nightly.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + self.assertEqual(before, nightly.current_roster(version, tag)) + inventory = release_candidate._release_payload_inventory(version, nightly=True) + expected = sorted( + name.replace(f"v{version}", tag) + for name, kind in inventory.items() + if kind in {"binary", "notice"} + ) + self.assertEqual(before["payloads"], expected) + def test_current_platform_roster_preserves_historical_manifest_meaning(self): tag = f"v0.44.0-nightly.20261023.{SHA}" roster = nightly.current_roster("0.44.0", tag) diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 3bb133b3b7..6a686752ef 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -3964,6 +3964,8 @@ def released(version: str) -> dict[str, str]: inventory.update({"rstack": version, "rstack-installer": version}) if module.release_roster.language_server_in_release(version_tuple): inventory["registry-language-server"] = version + if module.release_roster.session_in_release(version_tuple): + inventory["registry-session"] = version if module.release_roster.scheduling_installer_in_release(version_tuple): inventory["scheduling-installer"] = version if version_tuple >= (0, 39, 0): @@ -4088,6 +4090,8 @@ def released(version: str) -> dict[str, str]: inventory.update({"rstack": version, "rstack-installer": version}) if roster.language_server_in_release(version_tuple): inventory["registry-language-server"] = version + if roster.session_in_release(version_tuple): + inventory["registry-session"] = version if roster.scheduling_installer_in_release(version_tuple): inventory["scheduling-installer"] = version inventory.update({f"{name}-installer": version for name in module.release_roster.additional_installers(version_tuple)}) @@ -4117,6 +4121,17 @@ def released(version: str) -> dict[str, str]: [], module.artifact_inventory_errors("0.42.0", incomplete) ) + before_session = released("0.50.0") + at_session = released("0.51.0") + session = "registry-session" + self.assertNotIn(session, before_session) + self.assertEqual("0.51.0", at_session[session]) + self.assertEqual([], module.artifact_inventory_errors("0.50.0", before_session)) + self.assertTrue(module.artifact_inventory_errors("0.50.0", before_session | {session: "0.50.0"})) + self.assertEqual([], module.artifact_inventory_errors("0.51.0", at_session)) + without_session = {name: value for name, value in at_session.items() if name != session} + self.assertTrue(module.artifact_inventory_errors("0.51.0", without_session)) + # Holding the image does not hold the independently released binaries. with mock.patch.object( module.release_roster, "COORDINATOR_FIRST_RELEASE", None @@ -4246,6 +4261,8 @@ def test_breg_services_release_surface_begins_at_their_first_release( current.update({"rstack": version, "rstack-installer": version}) if module.release_roster.language_server_in_release(version_tuple): current["registry-language-server"] = version + if module.release_roster.session_in_release(version_tuple): + current["registry-session"] = version if module.release_roster.scheduling_installer_in_release(version_tuple): current["scheduling-installer"] = version current.update({f"{name}-installer": version for name in module.release_roster.additional_installers(version_tuple)}) @@ -6203,6 +6220,8 @@ def write_manifest( artifacts["rstack-installer"] = version if load_release_roster().language_server_in_release(version_tuple): artifacts["registry-language-server"] = version + if load_release_roster().session_in_release(version_tuple): + artifacts["registry-session"] = version if load_release_roster().scheduling_installer_in_release(version_tuple): artifacts["scheduling-installer"] = version if version_tuple >= (0, 39, 0): diff --git a/release/scripts/test_registry_release_plans.py b/release/scripts/test_registry_release_plans.py index c2a73948d8..0e479f25e9 100644 --- a/release/scripts/test_registry_release_plans.py +++ b/release/scripts/test_registry_release_plans.py @@ -177,6 +177,8 @@ def manifest(version: str, release_id: str, source_ref: str, status: str) -> dic inventory += ("rstack", "rstack-installer") if REGISTRY_RELEASE.release_roster.language_server_in_release(version_tuple): inventory += ("registry-language-server",) + if REGISTRY_RELEASE.release_roster.session_in_release(version_tuple): + inventory += ("registry-session",) if REGISTRY_RELEASE.release_roster.scheduling_installer_in_release(version_tuple): inventory += ("scheduling-installer",) if version_tuple >= (0, 39, 0): diff --git a/release/scripts/test_release_candidate.py b/release/scripts/test_release_candidate.py index 54b1b109cf..d0f20c4b4a 100644 --- a/release/scripts/test_release_candidate.py +++ b/release/scripts/test_release_candidate.py @@ -1567,6 +1567,20 @@ def test_breg_services_join_only_the_rosters_from_their_first_release( self.assertNotIn(f"{service}-v0.38.0-install.sh", inventory) self.assertNotIn(f"{service}-v0.38.0-macos-arm64", inventory) + @roster_patch("release_roster.SESSION_FIRST_RELEASE", (0, 51, 0)) + def test_session_first_release_closes_native_platform_assets(self) -> None: + old = self.module._release_payload_inventory("0.50.0") + self.assertFalse(any(name.startswith("registry-session-") for name in old)) + current = self.module._release_payload_inventory("0.51.0") + self.assertEqual( + { + "registry-session-v0.51.0-linux-amd64": "binary", + "registry-session-v0.51.0-linux-arm64": "binary", + "registry-session-v0.51.0-macos-arm64.tar.gz": "binary", + }, + {name: kind for name, kind in current.items() if name.startswith("registry-session-")}, + ) + @roster_patch("release_roster.COORDINATOR_FIRST_RELEASE", (0, 42, 0)) def test_no_version_ships_the_breg_services_until_the_roster_names_one( self, diff --git a/release/scripts/test_release_native_platform.py b/release/scripts/test_release_native_platform.py index a8a640255d..5ee6bd57c1 100755 --- a/release/scripts/test_release_native_platform.py +++ b/release/scripts/test_release_native_platform.py @@ -281,10 +281,9 @@ def setUp(self) -> None: self.fake_codesign.chmod(0o755) def roster_shim( - self, stem: str, first_release: tuple[int, int, int] + self, stem: str, first_releases: dict[str, tuple[int, int, int]] ) -> Path: - """Return a directory whose python3 answers the roster as if it named - ``first_release``, and runs every other command unchanged.""" + """Run the real roster with fixture gates and pass through other commands.""" shim_dir = self.root / f"{stem}-roster-shim" shim_dir.mkdir() shim = shim_dir / "python3" @@ -298,12 +297,12 @@ def roster_shim( if ( len(args) >= 2 and args[0].endswith("/release_roster.py") - and args[1] == "breg-services-in-release" ): spec = importlib.util.spec_from_file_location("release_roster", args[0]) roster = importlib.util.module_from_spec(spec) spec.loader.exec_module(roster) - roster.BREG_SERVICES_FIRST_RELEASE = {first_release!r} + for constant, first_release in {first_releases!r}.items(): + setattr(roster, constant, first_release) sys.exit(roster.main(args[1:])) os.execv({sys.executable!r}, [{sys.executable!r}, *args]) """, @@ -326,6 +325,7 @@ def build( missing_fips_binary: str | None = None, nightly_tag: str | None = None, breg_services_first_release: tuple[int, int, int] | None = None, + session_first_release: tuple[int, int, int] | None = None, exclude_discovery: bool = False, ) -> tuple[subprocess.CompletedProcess[str], Path, list[list[str]]]: stem = name or group @@ -348,8 +348,14 @@ def build( environment["FAKE_CARGO_FAIL_CALL"] = str(fail_call) if binary_version is not None: environment["FAKE_BINARY_VERSION"] = binary_version - if breg_services_first_release is not None: - shim_dir = self.roster_shim(stem, breg_services_first_release) + first_releases = { + name: value for name, value in ( + ("BREG_SERVICES_FIRST_RELEASE", breg_services_first_release), + ("SESSION_FIRST_RELEASE", session_first_release), + ) if value is not None + } + if first_releases: + shim_dir = self.roster_shim(stem, first_releases) environment["PATH"] = f"{shim_dir}{os.pathsep}{environment['PATH']}" parsed = tuple(int(part) for part in version.split(".")) if fips_shared or parsed >= (0, 33, 0): @@ -371,6 +377,7 @@ def build( "registry-render", "coordinator", "coordinatorctl", + "registry-session", "adapter", "adapterctl", ] @@ -525,6 +532,32 @@ def test_nightly_language_server_keeps_its_cargo_version(self): ).is_file() ) + def test_session_numbered_archive_is_built_and_nightly_archive_is_omitted(self): + version = "0.51.0" + first_release = (0, 51, 0) + numbered_tag = f"v{version}" + nightly_tag = f"{numbered_tag}-nightly.20261201.{SOURCE_SHA}" + asset = f"registry-session-{numbered_tag}-macos-arm64.tar.gz" + with mock.patch.object(MODULE.release_roster, "SESSION_FIRST_RELEASE", first_release): + result, output, _ = self.build( + "core", name="session-numbered", version=version, session_first_release=first_release, + ) + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn(asset, MODULE.rosters(version)["core"]) + with tarfile.open(output / "platform" / asset, "r:gz") as package: + self.assertEqual( + [asset.removesuffix(".tar.gz"), "libaws_lc_fips_0_14_2_crypto.dylib", "THIRD_PARTY_NOTICES"], + package.getnames(), + ) + result, output, calls = self.build( + "core", name="session-nightly", version=version, nightly_tag=nightly_tag, + session_first_release=first_release, + ) + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse(any("registry-session" in call for call in calls)) + paths = [path.name for path in (output / "platform").iterdir()] + self.assertCountEqual(paths, MODULE.rosters(version, nightly_tag)["core"]) + def test_v0_44_core_bundles_and_launches_every_additional_native_binary(self): result, output, calls = self.build("core", version="0.44.0") self.assertEqual(0, result.returncode, result.stderr) diff --git a/release/scripts/test_release_roster.py b/release/scripts/test_release_roster.py index ae0e22c92f..f98e3871bd 100644 --- a/release/scripts/test_release_roster.py +++ b/release/scripts/test_release_roster.py @@ -115,17 +115,33 @@ def test_document_store_is_held_out_of_every_release(self) -> None: self.assertFalse(release_roster.documents_in_release((0, 43, 99))) self.assertTrue(release_roster.documents_in_release((0, 44, 0))) - def test_session_service_is_held_out_of_every_release(self) -> None: - self.assertIsNone(release_roster.SESSION_FIRST_RELEASE) - for version in ((0, 48, 0), (0, 49, 0), (1, 0, 0)): + def test_session_service_joins_the_numbered_v0_51_0_release(self) -> None: + binary = ("registry-session", "registry-session") + self.assertEqual((0, 51, 0), release_roster.SESSION_FIRST_RELEASE) + for version in ((0, 48, 0), (0, 49, 0), (0, 50, 0)): self.assertFalse(release_roster.session_in_release(version)) - self.assertNotIn( - ("registry-session", "registry-session"), - release_roster.additional_platform_builds(version), - ) - with mock.patch.object(release_roster, "SESSION_FIRST_RELEASE", (0, 49, 0)): - self.assertFalse(release_roster.session_in_release((0, 48, 99))) - self.assertTrue(release_roster.session_in_release((0, 49, 0))) + self.assertNotIn(binary, release_roster.additional_platform_builds(version)) + for version in ((0, 51, 0), (1, 0, 0)): + self.assertTrue(release_roster.session_in_release(version)) + self.assertIn(binary, release_roster.additional_platform_builds(version)) + self.assertNotIn(binary, release_roster.additional_platform_builds(version, nightly=True)) + + def test_session_first_release_adds_its_native_binary_to_the_roster(self) -> None: + binary = ("registry-session", "registry-session") + with mock.patch.object(release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + self.assertFalse(release_roster.session_in_release((0, 50, 0))) + self.assertNotIn(binary, release_roster.additional_platform_builds((0, 50, 0))) + self.assertTrue(release_roster.session_in_release((0, 51, 0))) + self.assertIn(binary, release_roster.additional_platform_builds((0, 51, 0))) + self.assertNotIn(binary, release_roster.additional_platform_builds((0, 51, 0), nightly=True)) + for arguments, expected in ( + (["session-in-release", "0.50.0"], "false\n"), + (["session-in-release", "0.51.0"], "true\n"), + ): + stdout = io.StringIO() + with redirect_stdout(stdout): + self.assertEqual(0, release_roster.main(arguments)) + self.assertEqual(expected, stdout.getvalue()) def test_coordinator_binary_release_does_not_release_its_image(self): self.assertFalse(release_roster.coordinator_binaries_in_release((0, 43, 99))) diff --git a/release/scripts/test_release_units.py b/release/scripts/test_release_units.py index d494d57819..a299c8e965 100644 --- a/release/scripts/test_release_units.py +++ b/release/scripts/test_release_units.py @@ -41,6 +41,7 @@ def test_registry_maps_every_approved_release_unit(self) -> None: "messaging", "render", "scheduling", + "session", }, set(registry.names), ) @@ -69,6 +70,18 @@ def test_language_server_owns_only_its_standalone_artifacts(self) -> None: ), ) + def test_session_owns_only_its_native_platform_artifacts(self) -> None: + registry = self.module.load_registry() + unit = registry.get("session") + self.assertEqual(("registry-session",), unit.members) + for name in ( + "registry-session-v0.51.0-linux-amd64", + "registry-session-v0.51.0-linux-arm64", + "registry-session-v0.51.0-macos-arm64.tar.gz", + ): + with self.subTest(name=name): + self.assertEqual("session", registry.artifact_owner(name)) + def test_discovery_identity_and_candidate_roster_are_unit_scoped(self) -> None: self.assertEqual("v1.2.3", self.module.asset_tag("1.2.3")) self.assertEqual( diff --git a/release/scripts/test_rstack_components.py b/release/scripts/test_rstack_components.py index 7b327d8eae..c8b39abf50 100644 --- a/release/scripts/test_rstack_components.py +++ b/release/scripts/test_rstack_components.py @@ -6,6 +6,7 @@ import json import re import unittest +from unittest import mock from pathlib import Path from release.scripts import release_candidate, rstack_components @@ -90,6 +91,17 @@ def test_language_server_remains_a_distribution_only_binary(self) -> None: rstack_components.DISTRIBUTION_ONLY_BINARIES, ) + def test_session_is_a_distribution_only_binary_when_it_joins_the_release(self) -> None: + with mock.patch.object(release_candidate.release_roster, "SESSION_FIRST_RELEASE", (0, 51, 0)): + current = payloads("0.51.0") + self.assertIn( + "registry-session-v0.51.0-linux-amd64", + {payload["name"] for payload in current}, + ) + document = rstack_components.build_component_manifest("0.51.0", current) + self.assertNotIn("session", document["components"]) + self.assertIn("registry-session", rstack_components.DISTRIBUTION_ONLY_BINARIES) + def test_rstack_validator_exempts_the_same_distribution_only_binaries(self) -> None: model = ( Path(__file__).resolve().parents[2] / "crates/registry-rstack/src/model.rs" diff --git a/release/units.yaml b/release/units.yaml index d39b6b88a0..3b2b1c3df8 100644 --- a/release/units.yaml +++ b/release/units.yaml @@ -153,6 +153,16 @@ "artifact_patterns": ["scheduling-v*-*", "scheduling-install.sh", "schedulingctl-v*-*"], "dependencies": [], "candidate": null + }, + "session": { + "display_name": "Registry Session", + "status": "held", + "tag_prefix": "session/", + "asset_prefix": "registry-session", + "members": ["registry-session"], + "artifact_patterns": ["registry-session-v*-*"], + "dependencies": [], + "candidate": null } } }