From 04b1e54370cda241b7e5890db64ff768f94136c8 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 3 Dec 2026 06:59:40 +0000 Subject: [PATCH] chore(release): replay reviewed v0.52 platform changes Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 106 ++- .github/scripts/test_ci_changes.py | 424 ++++++++++- .github/workflows/ci.yml | 170 +++++ .github/workflows/release-candidate.yml | 97 +++ .github/workflows/release-rehearsal.yml | 6 + .github/workflows/release-repeatability.yml | 2 + AGENTS.md | 16 +- Cargo.lock | 7 + clients/typescript/README.md | 9 + clients/typescript/generate-service.ts | 33 +- clients/typescript/generate.ts | 25 +- clients/typescript/generated/breg-facility.ts | 2 +- clients/typescript/generated/discovery.ts | 23 +- clients/typescript/generated/render.ts | 2 +- clients/typescript/holder-function.ts | 144 +++- clients/typescript/preview/build.mjs | 51 +- clients/typescript/preview/config.mjs | 16 +- clients/typescript/preview/gateway.mjs | 14 +- clients/typescript/preview/host.mjs | 19 +- clients/typescript/preview/run.mjs | 64 +- .../typescript/preview/tests/preview.test.mjs | 294 +++++++- .../preview/tests/route-parity-fixtures.mjs | 53 ++ .../typescript/preview/tests/route-parity.mjs | 275 +++++++ clients/typescript/tests/discovery.test.ts | 85 +++ .../typescript/tests/generate-preview.test.ts | 71 +- .../tests/holder-function-outcome.test.ts | 230 ++++++ clients/typescript/tests/live-plan.test.ts | 41 + clients/typescript/tests/live/harness.ts | 42 +- crates/registry-adapter-core/src/runtime.rs | 2 +- .../src/job_sources.rs | 1 + crates/registry-adapter-engine/src/load.rs | 2 +- .../registry-adapter-job/src/hook_ingress.rs | 4 +- .../src/runtime_destination.rs | 176 ++++- crates/registry-adapter-job/src/store.rs | 72 +- .../signed_coordinator_event_postgres.rs | 82 +- crates/registry-adapter/src/serve.rs | 58 +- .../registry-adapter/tests/facade_refusals.rs | 15 + .../registry-adapterctl/src/job_provision.rs | 46 +- crates/registry-adapterctl/src/provision.rs | 49 +- .../tests/job_provision_cli.rs | 5 +- .../tests/provision_cli.rs | 58 ++ crates/registry-breg/src/action_outcome.rs | 7 +- crates/registry-breg/src/artifacts.rs | 88 ++- crates/registry-breg/src/fixtures.rs | 20 + .../registry-breg/src/history_maintenance.rs | 1 + .../registry-breg/src/migration_reconcile.rs | 1 + crates/registry-breg/src/model.rs | 10 + crates/registry-breg/src/mutation/action.rs | 227 ++++-- crates/registry-breg/src/postgres/config.rs | 39 +- crates/registry-breg/src/postgres/context.rs | 70 ++ crates/registry-breg/src/postgres/mod.rs | 9 +- crates/registry-breg/src/postgres/mutation.rs | 21 +- .../registry-breg/src/proposal_artifacts.rs | 15 +- crates/registry-breg/src/runtime_config.rs | 28 +- .../tests/artifacts_response_schema_tests.rs | 284 ++++++- .../tests/authentication_refusals.rs | 14 + .../registry-breg/tests/compiled_ddl_pins.rs | 6 +- .../tests/disclosure_exposure.rs | 20 +- crates/registry-breg/tests/http_auth.rs | 2 +- .../tests/postgres_action_evidence.rs | 28 +- .../tests/postgres_immediate_actions.rs | 303 +++++++- .../registry-breg/tests/postgres_proposal.rs | 16 +- crates/registry-breg/tests/postgres_tls.rs | 78 +- crates/registry-bregctl/src/provision.rs | 63 +- .../registry-bregctl/tests/provision_cli.rs | 40 +- .../__test__/facade.test-d.ts | 2 + .../__test__/facade.test.js | 151 +++- .../registry-casework-client-node/client.d.ts | 1 + .../registry-casework-client-node/client.js | 15 +- .../registry-casework-client-node/src/lib.rs | 15 +- .../registry_casework_client/__init__.pyi | 1 + crates/registry-casework-client-py/src/lib.rs | 6 + .../tests/python/test_native_requests.py | 153 +++- crates/registry-casework-client/src/client.rs | 40 +- crates/registry-casework-client/src/error.rs | 161 +++- .../src/task_assertion_source.rs | 1 + crates/registry-casework-client/src/wire.rs | 358 +++++++-- .../tests/fixtures/ask-response-shapes.json | 574 ++++++++++++++ .../fixtures/direct-response-additions.json | 81 ++ .../tests/fixtures/problem-responses.json | 101 +++ .../tests/http_boundary.rs | 333 ++++++++- crates/registry-casework/src/config.rs | 2 +- .../registry-casework/src/config/issuers.rs | 2 +- crates/registry-casework/src/store.rs | 59 +- .../registry-casework/tests/refusal_golden.rs | 14 + crates/registry-caseworkctl/src/lib.rs | 2 +- crates/registry-caseworkctl/src/provision.rs | 90 +-- .../registry-caseworkctl/tests/provision.rs | 18 +- crates/registry-cli-docs/catalog.json | 56 +- crates/registry-cli-report/tests/envelope.rs | 10 +- crates/registry-coordinator/src/deployment.rs | 65 +- crates/registry-coordinator/src/provision.rs | 121 ++- crates/registry-coordinator/src/runtime.rs | 4 +- crates/registry-coordinator/src/store.rs | 8 +- .../tests/caller_contract.rs | 2 +- .../tests/deployment_postgres.rs | 2 +- .../tests/provision_cli.rs | 51 +- .../tests/refusal_golden.rs | 34 +- .../__test__/surface.test.js | 104 ++- .../client.d.ts | 6 + .../registry-discovery-client-node/client.js | 15 +- .../registry-discovery-client-node/src/lib.rs | 11 +- .../registry_discovery_client/__init__.pyi | 3 + .../registry-discovery-client-py/src/lib.rs | 30 +- .../tests/python/test_client.py | 129 ++-- .../tests/python/test_drift.py | 10 +- crates/registry-discovery-client/Cargo.toml | 1 + .../registry-discovery-client/src/client.rs | 366 +++++++-- crates/registry-discovery-client/src/error.rs | 81 +- .../src/selection.rs | 216 ++++-- crates/registry-discovery-client/src/wire.rs | 42 +- .../tests/compatibility_metadata.rs | 8 +- .../tests/fixtures/http-responses.json | 215 ++++++ crates/registry-discovery/src/model.rs | 2 +- crates/registry-discoveryctl/src/lib.rs | 2 +- crates/registry-documents/src/auth.rs | 39 + crates/registry-documents/src/store.rs | 59 +- .../tests/refusal_golden.rs | 14 + crates/registry-documentsctl/src/operate.rs | 2 +- crates/registry-documentsctl/src/provision.rs | 60 +- .../tests/provision_cli.rs | 146 +++- .../registry-evidence-client-node/README.md | 12 +- .../__test__/drift.test.js | 1 + .../__test__/errors.test.js | 148 +++- .../registry-evidence-client-node/client.d.ts | 10 +- .../registry-evidence-client-node/client.js | 17 +- .../src/convert.rs | 86 +-- crates/registry-evidence-client-py/README.md | 10 +- .../registry_evidence_client/__init__.pyi | 11 +- .../src/convert.rs | 64 +- crates/registry-evidence-client-py/src/lib.rs | 6 +- .../tests/python/test_drift.py | 1 + .../tests/python/test_errors.py | 126 +++- crates/registry-evidence-client/src/batch.rs | 16 +- crates/registry-evidence-client/src/client.rs | 294 +++++++- crates/registry-evidence-client/src/error.rs | 114 ++- .../registry-evidence-client/src/problem.rs | 96 +-- crates/registry-evidence-client/src/wire.rs | 159 +++- .../registry-evidence-oid4vci/src/config.rs | 4 +- .../registry-evidence-oid4vci/src/issuer.rs | 14 +- .../tests/check_command.rs | 2 +- crates/registry-evidence/src/bundle.rs | 4 +- crates/registry-evidence/src/contracts.rs | 71 +- .../src/evidence_source_tests.rs | 37 + .../src/refusal_recording_tests.rs | 16 + crates/registry-evidencectl/src/check.rs | 4 +- .../src/store_provision.rs | 49 +- crates/registry-evidencectl/tests/fixtures.rs | 2 +- .../tests/store_provision.rs | 68 ++ crates/registry-mcp/src/casework.rs | 1 + .../registry-mcp/tests/provider_contract.rs | 1 + crates/registry-messaging/src/config.rs | 2 +- crates/registry-messaging/src/http.rs | 14 + .../registry-messaging/src/smtp/settings.rs | 8 +- crates/registry-messaging/src/store.rs | 59 +- crates/registry-messagingctl/src/lib.rs | 2 +- crates/registry-messagingctl/src/provision.rs | 49 +- .../tests/provision_cli.rs | 23 +- crates/registry-platform-config/src/blocks.rs | 242 ++++-- .../src/blocks_tests.rs | 68 +- .../src/caller_issuers.rs | 10 +- crates/registry-platform-config/src/lib.rs | 17 +- .../registry-platform-config/src/posture.rs | 4 +- .../registry-platform-config/src/secrets.rs | 7 - .../registry-platform-oidc/src/diagnostics.rs | 33 +- .../registry-platform-oidc/src/issuer_set.rs | 4 +- .../src/issuer_set_tests.rs | 35 + crates/registry-platform-postgres/Cargo.toml | 4 + crates/registry-platform-postgres/README.md | 2 + crates/registry-platform-postgres/src/lib.rs | 249 +++++- .../registry-platform-postgres/src/roots.rs | 185 +++++ crates/registry-platform-provision/Cargo.toml | 4 +- crates/registry-platform-provision/README.md | 4 +- .../registry-platform-provision/src/admin.rs | 76 +- crates/registry-platform-provision/src/cli.rs | 2 +- crates/registry-platform-provision/src/lib.rs | 7 + .../src/refusal.rs | 223 ++++++ .../src/test_support.rs | 20 + crates/registry-render/src/cli.rs | 3 +- crates/registry-render/src/runtime.rs | 404 ++++++---- crates/registry-render/src/schema.rs | 31 +- crates/registry-render/src/server.rs | 28 +- crates/registry-render/tests/common/mod.rs | 45 +- crates/registry-render/tests/scaffold.rs | 13 +- crates/registry-render/tests/serve.rs | 304 ++++++-- crates/registry-render/tests/serve_seal.rs | 2 +- crates/registry-render/tests/test_seal.rs | 2 +- crates/registry-review-client/src/client.rs | 186 +++-- crates/registry-review-client/src/error.rs | 40 +- .../tests/http_boundary.rs | 706 ++++++++++++++++-- crates/registry-rstack-dev/src/database.rs | 45 +- crates/registry-rstack-dev/src/dev_facts.rs | 6 +- crates/registry-rstack-dev/src/lib.rs | 263 ++++++- crates/registry-rstack-dev/src/preview.rs | 105 ++- .../registry-rstack-dev/src/preview_export.rs | 657 ++++++++++++++++ crates/registry-rstack-dev/src/products.rs | 107 ++- crates/registry-rstack/src/cli.rs | 39 +- crates/registry-rstack/tests/dev.rs | 50 ++ crates/registry-scheduling/src/config.rs | 2 +- crates/registry-scheduling/src/store.rs | 59 +- .../tests/postgres_commitments.rs | 62 ++ crates/registry-schedulingctl/src/lib.rs | 2 +- .../registry-schedulingctl/src/provision.rs | 49 +- .../tests/provision_cli.rs | 48 +- crates/registry-session/README.md | 4 +- .../casework/client.d.ts | 1 + .../casework/client.js | 15 +- .../compatibility.json | 4 +- .../discovery/client.d.ts | 6 + .../discovery/client.js | 15 +- .../evidence/client.d.ts | 10 +- .../evidence/client.js | 17 +- .../registry-stack-client/compatibility.json | 4 +- .../examples/business-registration/.gitignore | 1 + .../examples/business-registration/Dockerfile | 2 + .../examples/business-registration/README.md | 242 ++++-- .../casework/compose.yaml | 64 ++ .../casework/runtime.yaml | 28 + .../casework/seed-task.mjs | 92 +++ .../business-registration/compose.local.yaml | 6 + .../business-registration/compose.yaml | 12 +- .../examples/business-registration/host.mjs | 193 ++++- .../business-registration/session.yaml | 4 +- .../business-registration/tests/browser.mjs | 224 ++++-- .../tests/build-host-client.mjs | 150 ++++ .../tests/build-host-client.test.mjs | 168 +++++ .../bundle/functions/register-business.mjs | 4 + .../tests/bundle/manifest.json | 1 + .../tests/bundle/project/web/dist/app.js | 1 + .../tests/bundle/project/web/dist/assets.json | 1 + .../bundle/project/web/dist/assets/note.txt | 1 + .../bundle/project/web/dist/caf\303\251.txt" | 1 + .../tests/bundle/project/web/dist/index.html | 3 + .../tests/bundle/project/web/dist/service.css | 1 + .../tests/cleanup-preview.sh | 36 + .../business-registration/tests/host.test.mjs | 255 ++++++- .../tests/prepare-inputs.mjs | 190 +++++ .../business-registration/tests/receipt.mjs | 40 + .../tests/receipt.test.mjs | 78 ++ .../business-registration/tests/routes.mjs | 34 + .../tests/routes.test.mjs | 89 +++ .../tests/run-reference.sh | 459 ++++++++++++ .../business-registration/tests/smoke.sh | 4 +- .../tests/test_casework_compose.py | 40 + .../tests/test_compose.py | 57 +- .../tests/test_host_node.py | 8 +- .../tests/test_preview_cleanup.py | 74 ++ .../business-registration/thunderid.sh | 16 +- docs/site/scripts/evidence-problems.test.mjs | 11 +- .../content/docs/configure/breg-actions.mdx | 6 +- .../content/docs/configure/breg-proposals.mdx | 7 +- .../content/docs/configure/coordinator.mdx | 3 +- .../src/content/docs/configure/discovery.mdx | 14 +- .../docs/configure/enable-sd-jwt-vc.mdx | 6 +- .../run-a-project-with-rstack-dev.mdx | 79 +- .../src/content/docs/configure/session.mdx | 8 +- .../site/src/content/docs/operate/adapter.mdx | 17 +- docs/site/src/content/docs/operate/breg.mdx | 9 +- .../src/content/docs/operate/casework.mdx | 16 +- .../src/content/docs/operate/coordinator.mdx | 19 +- .../src/content/docs/operate/documents.mdx | 16 +- .../src/content/docs/operate/messaging.mdx | 16 +- .../content/docs/operate/registry-render.mdx | 40 +- .../src/content/docs/operate/scheduling.mdx | 16 +- .../content/docs/reference/api-stability.mdx | 13 +- .../src/content/docs/reference/breg-api.mdx | 24 +- .../src/content/docs/reference/client-api.mdx | 10 +- .../src/content/docs/reference/contracts.mdx | 8 +- .../reference/documents-configuration.mdx | 12 +- .../src/content/docs/reference/errors.mdx | 63 +- .../docs/reference/render-configuration.mdx | 8 +- docs/site/src/content/docs/security/breg.mdx | 19 + .../src/content/docs/security/coordinator.mdx | 13 +- .../src/content/docs/security/messaging.mdx | 12 +- .../site/src/content/docs/security/render.mdx | 16 + .../content/docs/start/registry-render.mdx | 2 +- .../build-and-deploy-evidence-project.mdx | 8 +- .../tutorials/connect-a-sqlite-extract.mdx | 8 +- .../connect-an-institution-source.mdx | 4 +- .../control-who-can-request-evidence.mdx | 2 +- .../tutorials/first-evidence-assertion.mdx | 4 +- .../docs/tutorials/first-render-document.mdx | 11 +- .../publish-and-consume-discovery-index.mdx | 6 +- .../request-evidence-as-sd-jwt-vc.mdx | 2 +- docs/site/src/data/breg-api.yaml | 4 +- docs/site/src/data/posture-diagnostics.json | 39 +- products/adapter/CHANGELOG.md | 10 + products/breg/CHANGELOG.md | 14 + .../contracts/security-invariant-matrix.yaml | 1 + .../contracts/security-test-traceability.yaml | 2 + .../breg/examples/formats/ctl-report.json | 4 +- .../formats/explain/actions-explanation.json | 2 +- .../formats/explain/model-explanation.json | 2 +- .../tests/journeys.yaml | 4 +- .../generated/facility/generated/openapi.json | 2 +- .../breg/scripts/test_validate_product.py | 2 +- products/breg/scripts/validate_product.py | 2 +- products/casework/CHANGELOG.md | 5 + products/coordinator/CHANGELOG.md | 6 + products/coordinator/README.md | 2 +- products/discovery/CHANGELOG.md | 8 + products/documents/CHANGELOG.md | 5 + .../evidence-definitions-v1.schema.json | 2 +- ...ence-request-batch-response-v1.schema.json | 2 +- .../evidence/generated/jwks-v1.schema.json | 2 +- .../evidence/generated/problem-v1.schema.json | 2 +- .../identifiers/contracts/catalog-source.json | 105 ++- .../identifiers/generated/catalog.v1.json | 18 +- products/messaging/CHANGELOG.md | 5 + .../scripts/check-role-assignment.sh | 41 + .../scripts/test-check-role-assignment.sh | 81 ++ products/messaging/scripts/test-dev.sh | 20 +- .../scripts/test_dev_callback_metric.py | 73 ++ products/platform/AGENTS.md | 17 +- products/platform/CHANGELOG.md | 89 +++ products/platform/CONFIG-CONVENTIONS.md | 5 + products/platform/README.md | 3 +- products/platform/config-formats.yaml | 2 +- .../functions/register-business/index.ts | 8 +- .../functions/register-business/prepare.ts | 10 + .../functions/assess-permit/index.ts | 6 +- .../functions/digest-application/index.ts | 5 +- .../client-response-tolerance/evidence.json | 199 +++++ .../generated/dev/dev.v1alpha1.schema.json | 11 +- products/platform/journeys/README.md | 88 ++- .../journeys/first-hour-pass-rule.yaml | 4 +- .../platform/journeys/first-hour-reading.md | 78 ++ .../platform/journeys/first-hour-receipt.jq | 132 +++- products/platform/journeys/lib.sh | 170 ++++- products/platform/journeys/own-provider.sh | 154 ++-- products/platform/journeys/products.yaml | 56 ++ products/platform/journeys/rstack-dev.sh | 94 ++- .../platform/journeys/test_journey_tables.py | 447 +++++++++-- products/platform/journeys/test_lib.sh | 79 +- .../scripts/check-config-conventions.py | 43 ++ .../scripts/check-session-dependencies.py | 160 ++++ .../service-preview-supervisor-probes.mjs | 8 +- .../scripts/test-service-previews.mjs | 244 +++++- .../scripts/test_check_config_conventions.py | 42 ++ .../test_check_session_dependencies.py | 148 ++++ products/render/CHANGELOG.md | 13 +- products/render/README.md | 4 +- products/render/SECURITY-MATRIX.md | 16 + products/render/examples/runtime.yaml | 7 +- .../generated/registry-render.openapi.json | 2 +- products/render/integrations/openfn/README.md | 12 +- .../render/integrations/openfn/receipt-job.js | 9 +- products/render/schemas/runtime.schema.json | 5 +- products/scheduling/CHANGELOG.md | 5 + .../run_managed_task_authority_journey.py | 165 ++++ ...test_run_managed_task_authority_journey.py | 199 +++++ release/NIGHTLY.md | 18 +- release/OPERATIONS.md | 121 ++- release/VERIFY.md | 21 +- release/docker/Dockerfile.registry-session | 47 ++ release/scripts/build-release-binaries.sh | 19 +- release/scripts/build-release-image.sh | 2 +- .../candidate-host-casework.compose.yaml | 15 + release/scripts/candidate-host-smoke.sh | 10 + release/scripts/candidate-host.compose.yaml | 24 + release/scripts/candidate_host_inputs.py | 192 +++++ release/scripts/check-debian13-images.py | 6 + release/scripts/check-gates-inventory.py | 8 + release/scripts/cleanup-release-candidates.py | 1 + .../collect-rehearsal-advisory-evidence.py | 1 + .../scripts/merge-release-binary-shards.py | 12 +- release/scripts/nightly_release.py | 15 +- release/scripts/release_candidate.py | 4 + release/scripts/release_roster.py | 41 +- .../scripts/smoke-release-image-oci-labels.sh | 2 +- release/scripts/test_candidate_host_smoke.py | 308 ++++++++ release/scripts/test_check_debian13_images.py | 12 + release/scripts/test_check_gates_inventory.py | 15 + .../test_check_release_image_oci_labels.py | 8 +- .../test_cleanup_release_candidates.py | 18 +- .../test_merge_release_binary_shards.py | 27 + release/scripts/test_nightly_release.py | 20 + release/scripts/test_registry_release.py | 5 +- release/scripts/test_release_candidate.py | 39 +- .../test_release_repeatability_workflow.py | 5 + release/scripts/test_release_roster.py | 29 +- .../scripts/test_release_supporting_images.py | 7 +- .../test_release_workflow_structure.py | 12 +- release/scripts/test_verify_public_release.py | 9 + release/scripts/test_zig_glibc_compiler.py | 54 +- 385 files changed, 19167 insertions(+), 2777 deletions(-) create mode 100644 clients/typescript/preview/tests/route-parity-fixtures.mjs create mode 100644 clients/typescript/preview/tests/route-parity.mjs create mode 100644 clients/typescript/tests/holder-function-outcome.test.ts create mode 100644 clients/typescript/tests/live-plan.test.ts create mode 100644 crates/registry-casework-client/tests/fixtures/ask-response-shapes.json create mode 100644 crates/registry-casework-client/tests/fixtures/direct-response-additions.json create mode 100644 crates/registry-casework-client/tests/fixtures/problem-responses.json create mode 100644 crates/registry-discovery-client/tests/fixtures/http-responses.json create mode 100644 crates/registry-platform-postgres/src/roots.rs create mode 100644 crates/registry-platform-provision/src/refusal.rs create mode 100644 crates/registry-rstack-dev/src/preview_export.rs create mode 100644 deploy/examples/business-registration/.gitignore create mode 100644 deploy/examples/business-registration/casework/compose.yaml create mode 100644 deploy/examples/business-registration/casework/runtime.yaml create mode 100644 deploy/examples/business-registration/casework/seed-task.mjs create mode 100644 deploy/examples/business-registration/compose.local.yaml create mode 100644 deploy/examples/business-registration/tests/build-host-client.mjs create mode 100644 deploy/examples/business-registration/tests/build-host-client.test.mjs create mode 100644 deploy/examples/business-registration/tests/bundle/functions/register-business.mjs create mode 100644 deploy/examples/business-registration/tests/bundle/manifest.json create mode 100644 deploy/examples/business-registration/tests/bundle/project/web/dist/app.js create mode 100644 deploy/examples/business-registration/tests/bundle/project/web/dist/assets.json create mode 100644 deploy/examples/business-registration/tests/bundle/project/web/dist/assets/note.txt create mode 100644 "deploy/examples/business-registration/tests/bundle/project/web/dist/caf\303\251.txt" create mode 100644 deploy/examples/business-registration/tests/bundle/project/web/dist/index.html create mode 100644 deploy/examples/business-registration/tests/bundle/project/web/dist/service.css create mode 100644 deploy/examples/business-registration/tests/cleanup-preview.sh create mode 100644 deploy/examples/business-registration/tests/prepare-inputs.mjs create mode 100644 deploy/examples/business-registration/tests/receipt.mjs create mode 100644 deploy/examples/business-registration/tests/receipt.test.mjs create mode 100644 deploy/examples/business-registration/tests/routes.mjs create mode 100644 deploy/examples/business-registration/tests/routes.test.mjs create mode 100644 deploy/examples/business-registration/tests/run-reference.sh create mode 100644 deploy/examples/business-registration/tests/test_casework_compose.py create mode 100644 deploy/examples/business-registration/tests/test_preview_cleanup.py create mode 100755 products/messaging/scripts/check-role-assignment.sh create mode 100755 products/messaging/scripts/test-check-role-assignment.sh create mode 100644 products/messaging/scripts/test_dev_callback_metric.py create mode 100644 products/platform/examples/service-previews/business-registration/functions/register-business/prepare.ts create mode 100644 products/platform/fixtures/client-response-tolerance/evidence.json create mode 100644 products/platform/journeys/first-hour-reading.md create mode 100644 products/platform/scripts/check-session-dependencies.py create mode 100644 products/platform/scripts/test_check_session_dependencies.py create mode 100644 products/render/SECURITY-MATRIX.md create mode 100755 products/scheduling/scripts/run_managed_task_authority_journey.py create mode 100644 products/scheduling/scripts/test_run_managed_task_authority_journey.py create mode 100644 release/docker/Dockerfile.registry-session create mode 100644 release/scripts/candidate-host-casework.compose.yaml create mode 100644 release/scripts/candidate-host-smoke.sh create mode 100644 release/scripts/candidate-host.compose.yaml create mode 100644 release/scripts/candidate_host_inputs.py create mode 100644 release/scripts/test_candidate_host_smoke.py diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index af53de7870..56e946e835 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -226,7 +226,22 @@ def literal(node: ast.expr | None) -> Any: "registry-casework", "registry-caseworkctl", "registry-coordinator", + "registry-session", }) +# One job builds these CI-profile binaries for every job that runs them, +# instead of each job building its own. Each consumer job is selected by one +# of CI_BINARY_CONSUMERS, and the builder runs whenever any of them does, and +# in the full sweep, which proves the build on its own. +CI_BINARY_PACKAGES = ( + "registry-rstack", + "registry-session", + "registry-breg", + "registry-bregctl", + "registry-casework", + "registry-caseworkctl", +) +CI_BINARIES = ("rstack", "registry-session", "breg", "bregctl", "casework", "caseworkctl") +CI_BINARY_CONSUMERS: tuple[str, ...] = ("reference_host_smoke",) # The shared dependency gate owns the list of development runner hosts; it # is read as data, and test_ci_changes.py holds it equal to the gate's own. _dev_runner_gate = literal_assignments( @@ -275,6 +290,30 @@ def literal(node: ast.expr | None) -> Any: # The journey scripts, their tables, the realm and the per-product inputs. JOURNEY_INPUTS = ("products/platform/journeys/**",) +# The managed Scheduling task-authority journey: the ThunderID own-provider +# journey with an rstack dev Scheduling runtime bound to one live Casework task +# authority. Scheduling, the shared task-grant code that Scheduling links (the +# reverse-dependency closure reaches it), the rstack dev runner, Casework as +# the grant issuer and the ThunderID fixture select it, and so do the harness +# files the run reads. It runs in the ThunderID leg of the acceptance journeys. +SCHEDULING_MANAGED_JOURNEY_PACKAGES = frozenset( + { + "registry-casework", + "registry-caseworkctl", + "registry-rstack", + "registry-rstack-dev", + "registry-thunderid-tooling", + } +) +SCHEDULING_MANAGED_JOURNEY_INPUTS = ( + "products/platform/journeys/own-provider.sh", + "products/platform/journeys/lib.sh", + "products/platform/journeys/projects/composed_fixtures.py", + "products/platform/journeys/expected-failures-thunderid.yaml", + "products/scheduling/scripts/run_managed_task_authority_journey.py", + "crates/registry-thunderid-tooling/thunderid-version.json", +) + # The token fixture corpus, read by the corpus test in # registry-platform-testing and by the token characterisation test of every # runtime that verifies a token. The corpus is not a crate, so its path names @@ -411,11 +450,23 @@ def literal(node: ast.expr | None) -> Any: "clients/typescript/generate-project.ts", "clients/typescript/generate-service.ts", "clients/typescript/package*.json", + "clients/typescript/registry-generate.js", "clients/typescript/preview/**", "products/platform/examples/service-previews/**", "products/platform/scripts/test-service-previews.mjs", + "deploy/examples/business-registration/edge.yaml", + "deploy/examples/business-registration/session.yaml", + # The end-to-end export check serves the exported bundle with this host. + "deploy/examples/business-registration/host.mjs", + "deploy/examples/business-registration/package.json", + "deploy/examples/business-registration/package-lock.json", + "deploy/examples/business-registration/tests/build-host-client.mjs", ) +# registry-rstack-dev pins the digest of this shared bundle fixture, and the +# reference host's own test pins the same value. +SHARED_PREVIEW_BUNDLE = "deploy/examples/business-registration/tests/bundle/" + # The TypeScript clients generate from these OpenAPI documents, verify the # shared Standard Webhooks vectors, and check the documents against what the # clients assume. @@ -1543,6 +1594,8 @@ def classify( # Cross-product commitments select the two owning product gates # explicitly below; each gate compiles and exercises its router. pass + elif path.startswith(SHARED_PREVIEW_BUNDLE): + seeds.add("registry-rstack-dev") elif path.startswith(("crates/", "products/")): # A new or moved Rust package must not silently escape the test matrix. force_all = True @@ -1855,10 +1908,21 @@ def classify( or bool(affected & BREG_EVIDENCE_COMPOSITION_PACKAGES) ) - acceptance_journeys = integration and ( + scheduling_managed_journey = integration and ( complete - or any(matches(path, *JOURNEY_INPUTS) for path in paths) - or bool(affected & JOURNEY_PACKAGES) + or any(matches(path, *SCHEDULING_MANAGED_JOURNEY_INPUTS) for path in paths) + or bool(affected & (SCHEDULING_PACKAGES | SCHEDULING_MANAGED_JOURNEY_PACKAGES)) + ) + + # The managed journey runs in the ThunderID leg, so selecting it selects + # the acceptance journeys. + acceptance_journeys = scheduling_managed_journey or ( + integration + and ( + complete + or any(matches(path, *JOURNEY_INPUTS) for path in paths) + or bool(affected & JOURNEY_PACKAGES) + ) ) # Running dev_run for a host change does not make the harness itself @@ -1934,12 +1998,34 @@ def classify( outputs = { "full_sweep": full_sweep, - # The operator tests read the successor warnings bregctl prints. "deployment": complete - or any( - path.startswith("deploy/") or path == "crates/registry-bregctl/src/apply_lifecycle.rs" - for path in paths - ), + or any(matches( + path, + "deploy/**", + # The operator tests read the successor warnings bregctl prints. + "crates/registry-bregctl/src/apply_lifecycle.rs", + # The reference host wrapper loads the holder binding from source. + "clients/typescript/holder-function.ts", + "clients/typescript/core.ts", + "clients/typescript/version.ts", + "clients/typescript/generated-client-version.ts", + "clients/typescript/package.json", # Sets the module type for those imports. + ) for path in paths), + "reference_host_smoke": complete + or bool(affected & (RSTACK_DEV_HARNESS_PACKAGES | { + "registry-session", "registry-breg", "registry-bregctl", + "registry-casework", "registry-caseworkctl", + })) + or any(matches( + path, + "deploy/examples/business-registration/**", + "clients/typescript/*.ts", + "clients/typescript/tsconfig*.json", + "products/casework/examples/standalone-decision/**", + "products/platform/scripts/prepare-service-preview-locks.mjs", + ".github/workflows/ci.yml", + *SERVICE_PREVIEW_INPUTS, + ) for path in paths), "rust": bool(affected), "rust_matrix": {"include": matrix}, "rust_packages": sorted(rust_packages), @@ -1975,6 +2061,7 @@ def classify( "scheduling_postgres": ( integration or "registry-platform-activation" in affected ) and bool(affected & (SCHEDULING_PACKAGES | {"registry-platform-dispatch"})), + "scheduling_managed_journey": scheduling_managed_journey, "messaging_contracts": bool(affected & MESSAGING_PACKAGES), "messaging_postgres": bool(affected & MESSAGING_PACKAGES), "documents_contracts": bool(affected & DOCUMENTS_PACKAGES), @@ -2002,6 +2089,9 @@ def classify( "acceptance_journeys": acceptance_journeys, "identifiers": identifiers, } + outputs["ci_binaries"] = full_sweep or any( + outputs[consumer] for consumer in CI_BINARY_CONSUMERS + ) return outputs diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 147ac6f5c6..9c81987da6 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -23,6 +23,9 @@ import yaml from ci_changes import ( + CI_BINARIES, + CI_BINARY_CONSUMERS, + CI_BINARY_PACKAGES, RSTACK_DEV_HOST_PACKAGES, BREG_CONTRACTS_LANES, BREG_TUTORIAL_INPUTS, @@ -730,6 +733,7 @@ def test_critical_ci_work_remains_directly_eligible_after_classification( "typescript-clients", "release-linux-node-clients", "deployment", + "ci-binaries", } direct = { name @@ -743,9 +747,12 @@ def test_critical_ci_work_remains_directly_eligible_after_classification( # contracts-journeys lane: they replace the longest serial integration # jobs, so the pool trades extra directly-eligible slots for the # shorter critical path. - # The deployment and Evidence doctor jobs each use one runner. - self.assertLessEqual(slots, 21) - self.assertEqual(21, slots) + # The deployment and Evidence doctor jobs each use one runner. The + # shared binary builder starts in the first wave too, because the + # jobs that run its binaries, such as the two reference-host + # profiles, wait for it. + self.assertLessEqual(slots, 22) + self.assertEqual(22, slots) def test_deferred_ci_work_keeps_its_selector_and_explicit_status_guard( self, @@ -955,6 +962,8 @@ def test_ci_scheduling_graph_retains_every_job_and_aggregate_dependency( "typescript-live", "release-linux-node-clients", "deployment", + "reference-host-smoke", + "ci-binaries", "ci-result", } self.assertEqual(expected_jobs, set(self.workflow_jobs)) @@ -1042,6 +1051,8 @@ def test_ci_scheduling_graph_retains_every_job_and_aggregate_dependency( "typescript-live", "release-linux-node-clients", "deployment", + "reference-host-smoke", + "ci-binaries", ), } for name, expected in aggregate_needs.items(): @@ -1087,12 +1098,15 @@ def test_final_aggregate_flattens_rust_results_with_equivalent_outcomes( "typescript-clients", "release-linux-node-clients", "deployment", + "ci-binaries", } self.assertEqual( final_needs, - previous_final_needs.difference({"rust-result"}).union(rust_needs, {"typescript-live"}), + previous_final_needs.difference({"rust-result"}).union( + rust_needs, {"typescript-live", "reference-host-smoke"} + ), ) - self.assertEqual(50, len(final_needs)) + self.assertEqual(52, len(final_needs)) # Platform line coverage publishes from main and the nightly sweep; # it does not hold the merge queue. self.assertNotIn("platform-coverage", final_needs) @@ -1461,6 +1475,7 @@ def test_final_aggregate_refuses_a_selected_integration_job_that_skipped( "acceptance-journeys": "acceptance_journeys", "adapter-openbao": "adapter_openbao", "deployment": "deployment", + "reference-host-smoke": "reference_host_smoke", } def status(job: str, selected: str, result: str) -> int: @@ -1795,6 +1810,51 @@ def test_messaging_product_and_core_select_the_checkpoint_crates(self) -> None: self.assertFalse(unrelated["messaging_contracts"]) self.assertFalse(unrelated["messaging_postgres"]) + def test_rstack_dev_change_runs_the_native_messaging_role_check(self) -> None: + # The check is an ignored registry-rstack-dev test that needs the + # messagingctl the Messaging PostgreSQL job already builds. messagingctl + # links registry-rstack-dev, so a change on either side selects that job. + for path in ( + "crates/registry-rstack-dev/src/dev_facts.rs", + "products/messaging/scripts/check-role-assignment.sh", + ): + with self.subTest(path=path): + outputs = classify(self.workspace, (path,), pull_request=True) + self.assertTrue(outputs["messaging_postgres"]) + unrelated = classify( + self.workspace, ("crates/registry-scheduling/src/lib.rs",), pull_request=True + ) + self.assertFalse(unrelated["messaging_postgres"]) + + def test_messaging_role_check_runs_on_the_built_messagingctl(self) -> None: + script = "products/messaging/scripts/check-role-assignment.sh" + steps = self.workflow_jobs["messaging-postgres"]["steps"] + runs = [str(step.get("run", "")) for step in steps] + carriers = [index for index, run in enumerate(runs) if script in run] + self.assertEqual(1, len(carriers)) + step = steps[carriers[0]] + self.assertEqual(script, step["run"]) + self.assertNotIn("if", step) + self.assertNotIn("continue-on-error", step) + self.assertEqual( + "${{ github.workspace }}/target/debug/messagingctl", + step["env"]["MESSAGINGCTL_BIN"], + ) + builds = [ + index + for index, run in enumerate(runs) + if run.startswith("cargo build") and "-p registry-messagingctl" in run + ] + self.assertTrue(builds and builds[0] < carriers[0]) + self_test = "products/messaging/scripts/test-check-role-assignment.sh" + self.assertIn( + self_test, + [ + str(step.get("run", "")) + for step in self.workflow_jobs["messaging-contracts"]["steps"] + ], + ) + def test_document_store_product_and_core_select_its_own_gates(self) -> None: for path in ( "products/documents/README.md", @@ -3009,6 +3069,25 @@ def test_yaml_reader_boundary_inputs_select_platform_hygiene(self) -> None: with self.subTest(path=path): self.assertTrue(classify(self.workspace, (path,))["platform_hygiene"]) + def test_session_dependency_gate_runs_for_manifest_and_gate_changes(self) -> None: + for path in ( + "Cargo.toml", + "crates/registry-session/Cargo.toml", + "crates/registry-breg/Cargo.toml", + "products/platform/scripts/check-session-dependencies.py", + "products/platform/scripts/test_check_session_dependencies.py", + ): + with self.subTest(path=path): + self.assertTrue(classify(self.workspace, (path,))["platform_hygiene"]) + + steps = self.workflow_jobs["platform-hygiene"]["steps"] + commands = [step["run"] for step in steps if "run" in step] + fixture_test = "python3 -m unittest products/platform/scripts/test_check_session_dependencies.py" + gate = "python3 products/platform/scripts/check-session-dependencies.py" + self.assertIn(fixture_test, commands) + self.assertIn(gate, commands) + self.assertLess(commands.index(fixture_test), commands.index(gate)) + def test_documentation_alone_skips_platform_hygiene(self) -> None: for path in ( "products/platform/README.md", @@ -3179,6 +3258,30 @@ def test_bregctl_apply_warnings_run_the_deployment_tests(self) -> None: ) self.assertTrue(outputs["deployment"]) + def test_reference_host_binding_inputs_run_the_deployment_tests(self) -> None: + for path in ( + "clients/typescript/holder-function.ts", + "clients/typescript/core.ts", + "clients/typescript/version.ts", + "clients/typescript/generated-client-version.ts", + "clients/typescript/package.json", + ): + with self.subTest(path=path): + outputs = classify(self.workspace, (path,), pull_request=True) + self.assertTrue(outputs["deployment"]) + self.assertFalse(outputs["rust"]) + outputs = classify(self.workspace, ("clients/typescript/browser.ts",), pull_request=True) + self.assertFalse(outputs["deployment"]) + + def test_deployment_pins_node_before_running_the_reference_host_wrapper(self) -> None: + steps = self.workflow_jobs["deployment"]["steps"] + setup = next(step for step in steps if step.get("name") == "Setup Node") + self.assertTrue(setup["uses"].startswith("actions/setup-node@")) + self.assertEqual("24.11.0", setup["with"]["node-version"]) + contracts = next(step for step in steps if step.get("name") == "Test deployment contracts") + self.assertIn("unittest discover", contracts["run"]) + self.assertLess(steps.index(setup), steps.index(contracts)) + def test_evidence_code_and_product_contracts_select_its_shards_and_drift_gate(self) -> None: # A runtime change reaches the real Evidence router consumers, including # the Casework institutional exchange acceptance through its dev dependency. @@ -4173,12 +4276,118 @@ def test_development_host_changes_select_the_rstack_shard(self) -> None: ) self.assertLessEqual(packages, set(selected)) + def test_service_preview_route_parity_selects_both_gateway_sources(self) -> None: + for path in ( + "clients/typescript/preview/tests/route-parity.mjs", + "clients/typescript/preview/tests/route-parity-fixtures.mjs", + "crates/registry-session/src/gateway/verify.rs", + "deploy/examples/business-registration/edge.yaml", + "deploy/examples/business-registration/session.yaml", + "products/platform/examples/service-previews/permit-review/dev.yaml", + ): + with self.subTest(path=path): + outputs = classify(self.workspace, (path,)) + self.assertTrue(outputs["service_previews"]) + self.assertTrue(outputs["typescript_clients"]) + steps = self.workflow_jobs["typescript-clients"]["steps"] + parity = next(step for step in steps if step.get("name") == "Check service preview browser route parity") + self.assertIn("needs.changes.outputs.service_previews", parity["if"]) + self.assertIn("route-parity.mjs", parity["run"]) + build = next(step for step in steps if step.get("name") == "Build the preview launcher and product tools") + self.assertIn("-p registry-session", build["run"]) + self.assertLess(steps.index(build), steps.index(parity)) + + def test_reference_host_changes_require_both_browser_profiles(self) -> None: + for path in ( + "deploy/examples/business-registration/casework/compose.yaml", + "clients/typescript/browser.ts", + "clients/typescript/core.ts", + "clients/typescript/tsconfig.browser.json", + "crates/registry-session/src/signin.rs", + "crates/registry-casework/src/lib.rs", + "crates/registry-breg/src/lib.rs", + "products/platform/examples/service-previews/business-registration/dev.yaml", + ): + with self.subTest(path=path): + self.assertTrue(classify(self.workspace, (path,))["reference_host_smoke"]) + self.assertFalse(classify(self.workspace, ("README.md",))["reference_host_smoke"]) + job = self.workflow_jobs["reference-host-smoke"] + self.assertIn("needs.changes.outputs.reference_host_smoke", job["if"]) + self.assertEqual(job["strategy"]["matrix"]["profile"], ["breg", "casework"]) + self.assertIn("reference-host-smoke", self.workflow_jobs["ci-result"]["needs"]) + # Both profiles run the shared CI-profile binaries; neither compiles. + self.assertIn("reference_host_smoke", CI_BINARY_CONSUMERS) + self.assertEqual(["changes", "ci-binaries"], job["needs"]) + for step in job["steps"]: + self.assertNotIn("cargo", step.get("run", "")) + unpack = next( + step["run"] for step in job["steps"] + if step.get("name") == "Unpack the shared CI-profile binaries" + ) + self.assertIn( + 'tar -C "${RUNNER_TEMP}/ci-binaries" -xf "${RUNNER_TEMP}/ci-binaries.tar"', unpack + ) + script = Path("deploy/examples/business-registration/tests/run-reference.sh").read_text() + self.assertIn( + "Pass the absolute directory containing the CI-profile or release-profile binaries", + script, + ) + run = next( + step["run"] for step in job["steps"] + if step.get("name") == "Run the reference host and verify its browser receipt" + ) + logical_lines = run.replace("\\\n", "").splitlines() + commands = [words for line in logical_lines if (words := shlex.split(line, comments=True))] + # Pin the sequence so an earlier successful exit cannot bypass either check. + self.assertEqual(commands, [ + ["set", "-euo", "pipefail"], + ["recipe=$GITHUB_WORKSPACE/deploy/examples/business-registration"], + ["client=$GITHUB_WORKSPACE/clients/typescript"], + [ + "REFERENCE_YAML_MODULE=$client/node_modules/yaml/dist/index.js", + "node", "--test", "$recipe/tests/receipt.test.mjs", "$recipe/tests/routes.test.mjs", + ], + [ + "REFERENCE_ESBUILD_PACKAGE=$client/node_modules/esbuild", + "node", "--test", "$recipe/tests/build-host-client.test.mjs", + ], + [ + "bash", "$recipe/tests/run-reference.sh", "$REFERENCE_PROFILE", + "$RUNNER_TEMP/ci-binaries", + "$client/node_modules/playwright-core/index.mjs", "$client/node_modules/yaml/dist/index.js", + "$RUNNER_TEMP/reference-host-receipt.json", + ], + ]) + + def test_the_shared_preview_bundle_fixture_runs_the_export_pin(self) -> None: + # registry-rstack-dev pins the digest of this fixture, which the + # reference host pins too. + outputs = classify( + self.workspace, + ("deploy/examples/business-registration/tests/bundle/manifest.json",), + pull_request=True, + ) + self.assertIn("registry-rstack-dev", outputs["rust_packages"]) + self.assertTrue(outputs["deployment"]) + unrelated = classify( + self.workspace, + ("deploy/examples/business-registration/README.md",), + pull_request=True, + ) + self.assertNotIn("registry-rstack-dev", unrelated["rust_packages"]) + def test_service_preview_inputs_select_installed_browser_proof(self) -> None: for path in ( "crates/registry-rstack-service/src/lib.rs", + "clients/typescript/registry-generate.js", "clients/typescript/preview/host.mjs", "products/platform/examples/service-previews/medical-renewal/dev.yaml", "products/platform/scripts/test-service-previews.mjs", + # The end-to-end export check serves the bundle with the reference host. + "deploy/examples/business-registration/host.mjs", + "deploy/examples/business-registration/package.json", + "deploy/examples/business-registration/package-lock.json", + "deploy/examples/business-registration/tests/build-host-client.mjs", # permit-review starts Casework and the Coordinator. "crates/registry-casework/src/lib.rs", "crates/registry-caseworkctl/src/main.rs", @@ -4791,6 +5000,110 @@ def test_acceptance_journeys_routing(self) -> None: )["acceptance_journeys"] ) + def test_scheduling_managed_journey_routing(self) -> None: + # Scheduling, the shared task-grant code it links, the rstack dev + # runner, Casework and the ThunderID fixture select the managed journey + # in the merge queue, and selecting it selects the acceptance journeys + # whose ThunderID leg runs it. It never selects scheduling-postgres. + for package in ( + "registry-scheduling", + "registry-schedulingctl", + "registry-platform-oidc", + "registry-platform-authcommon", + "registry-rstack", + "registry-rstack-dev", + "registry-casework", + "registry-thunderid-tooling", + ): + path = f"{self.workspace.roots[package]}/Cargo.toml" + with self.subTest(path=path): + outputs = classify(self.workspace, (path,)) + self.assertTrue(outputs["scheduling_managed_journey"]) + self.assertTrue(outputs["acceptance_journeys"]) + + edgeless = Workspace(without_dependency_edges(self.metadata)) + for path in ( + "products/platform/journeys/own-provider.sh", + "products/platform/journeys/projects/composed_fixtures.py", + "products/platform/journeys/expected-failures-thunderid.yaml", + "products/scheduling/scripts/run_managed_task_authority_journey.py", + "crates/registry-thunderid-tooling/thunderid-version.json", + ): + with self.subTest(path=path): + outputs = classify(edgeless, (path,)) + self.assertTrue(outputs["scheduling_managed_journey"]) + self.assertTrue(outputs["acceptance_journeys"]) + # The ThunderID pin selects only the journey, which no longer starts + # scheduling-postgres. + pinned = classify(edgeless, ("crates/registry-thunderid-tooling/thunderid-version.json",)) + self.assertTrue(pinned["scheduling_managed_journey"]) + self.assertFalse(pinned["scheduling_postgres"]) + + # Unrelated products and the Keycloak-only inputs do not select it. + for path in ( + "crates/registry-messaging/Cargo.toml", + "products/platform/journeys/keycloak/realm.json", + ): + with self.subTest(path=path): + self.assertFalse(classify(edgeless, (path,))["scheduling_managed_journey"]) + # Review defers it with the rest of the integration tier. + self.assertFalse( + classify( + self.workspace, + ("crates/registry-scheduling/Cargo.toml",), + pull_request=True, + )["scheduling_managed_journey"] + ) + self.assertTrue( + classify( + self.workspace, + ("crates/registry-scheduling/Cargo.toml",), + pull_request=True, + ci_full=True, + )["scheduling_managed_journey"] + ) + + def test_thunderid_leg_runs_the_managed_journey_when_selected(self) -> None: + job = self.workflow_jobs["acceptance-journeys"] + steps = job["steps"] + names = [step.get("name") for step in steps] + selected = ( + "matrix.leg == 'own-provider-thunderid' && " + "needs.changes.outputs.scheduling_managed_journey == 'true'" + ) + install = names.index("Install uv for the managed Scheduling journey") + run = names.index("Run the managed Scheduling task-authority journey") + # It reuses the leg's image pull, binary build and fixture build, and + # follows the leg's own ThunderID journey. + for earlier in ( + "Pull the ThunderID issuer image", + "Build the journey binaries", + "Build the ThunderID journey fixture", + "Run the ThunderID own-provider journey", + ): + self.assertLess(names.index(earlier), install) + self.assertLess(install, run) + for index in (install, run): + with self.subTest(step=names[index]): + self.assertEqual(selected, steps[index]["if"]) + self.assertNotIn("continue-on-error", steps[index]) + build = shlex.split(folded_command(steps[names.index("Build the journey binaries")])) + for package in ( + "registry-breg", "registry-bregctl", "registry-casework", "registry-caseworkctl", + "registry-scheduling", "registry-schedulingctl", "registry-rstack", + ): + self.assertIn(package, build) + words = shlex.split(folded_command(steps[run])) + self.assertIn("products/scheduling/scripts/run_managed_task_authority_journey.py", words) + self.assertEqual("${GITHUB_WORKSPACE}/target/debug", words[words.index("--bin-dir") + 1]) + + # scheduling-postgres keeps its 30-minute limit and runs no journey. + postgres = self.workflow_jobs["scheduling-postgres"] + self.assertEqual(30, postgres["timeout-minutes"]) + self.assertFalse(any( + "run_managed_task_authority_journey" in step.get("run", "") for step in postgres["steps"] + )) + def test_acceptance_journeys_job_runs_each_leg_in_ratchet_mode(self) -> None: job = self.workflow_jobs["acceptance-journeys"] self.assertEqual("Acceptance journeys (${{ matrix.title }})", job["name"]) @@ -6231,5 +6544,106 @@ def test_the_host_list_matches_the_gate_module(self) -> None: ) self.assertEqual(gate["DEV_RUNNER_HOSTS"], RSTACK_DEV_HOST_PACKAGES) + +class SharedBinariesTest(unittest.TestCase): + """One job builds the CI-profile binaries that other jobs run.""" + + @classmethod + def setUpClass(cls) -> None: + root = Path(__file__).resolve().parents[2] + cls.jobs = yaml.safe_load((root / ".github/workflows/ci.yml").read_text())["jobs"] + metadata = subprocess.run( + ("cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"), + check=True, capture_output=True, text=True, cwd=root, + ) + cls.metadata = json.loads(metadata.stdout) + cls.workspace = Workspace(cls.metadata) + + def test_the_builder_is_selected_exactly_when_a_consumer_is(self) -> None: + for label, outputs in ( + ("full sweep", classify(self.workspace, (), full_sweep=True)), + ("review", classify(self.workspace, ("crates/registry-breg/src/lib.rs",), pull_request=True)), + ("queue", classify(self.workspace, ("crates/registry-session/src/lib.rs",))), + ("unrelated", classify(self.workspace, ("README.md",))), + ): + with self.subTest(case=label): + self.assertEqual( + outputs["full_sweep"] + or any(outputs[consumer] for consumer in CI_BINARY_CONSUMERS), + outputs["ci_binaries"], + ) + + def test_each_binary_comes_from_a_listed_package(self) -> None: + binaries = { + target["name"]: package["name"] + for package in self.metadata["packages"] + for target in package["targets"] + if "bin" in target["kind"] + } + self.assertEqual( + set(CI_BINARY_PACKAGES), {binaries[binary] for binary in CI_BINARIES} + ) + + def test_the_builder_builds_and_publishes_the_listed_binaries(self) -> None: + job = self.jobs["ci-binaries"] + self.assertEqual("Shared CI-profile binaries", job["name"]) + self.assertEqual("changes", job["needs"]) + self.assertEqual("needs.changes.outputs.ci_binaries == 'true'", job["if"]) + steps = {step["name"]: step for step in job["steps"]} + build = steps["Build the shared CI-profile binaries"]["run"] + packages = re.findall(r"-p (registry-[a-z-]+)", build) + self.assertEqual(list(CI_BINARY_PACKAGES), packages) + self.assertIn( + "cargo build --locked --profile ci --bins --features registry-breg/runtime", build + ) + self.assertIn(f"for binary in {' '.join(CI_BINARIES)}; do", build) + self.assertIn('tar -C "${RUNNER_TEMP}/ci-binaries" -cf "${RUNNER_TEMP}/ci-binaries.tar" .', build) + upload = steps["Upload the shared CI-profile binaries"] + self.assertEqual( + "actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9", upload["uses"] + ) + self.assertEqual( + { + "name": "ci-binaries", + "path": "${{ runner.temp }}/ci-binaries.tar", + "if-no-files-found": "error", + "retention-days": 1, + }, + upload["with"], + ) + + def test_every_consumer_job_runs_after_the_builder(self) -> None: + def downloads(job: dict) -> list[dict]: + return [ + step for step in job.get("steps", []) + if str(step.get("uses", "")).startswith("actions/download-artifact@") + and step.get("with", {}).get("name") == "ci-binaries" + ] + + selected = { + job_id: set(re.findall(r"needs\.changes\.outputs\.([a-z_]+)\b", str(job.get("if", "")))) + & set(CI_BINARY_CONSUMERS) + for job_id, job in self.jobs.items() + } + selected = {job_id: outputs for job_id, outputs in selected.items() if outputs} + # Every listed consumer selects a job, and the jobs that download the + # binaries are exactly the jobs a listed consumer selects. + for consumer in CI_BINARY_CONSUMERS: + with self.subTest(consumer=consumer): + self.assertTrue(any(consumer in outputs for outputs in selected.values())) + downloading = {job_id for job_id, job in self.jobs.items() if downloads(job)} + self.assertEqual(set(selected), downloading) + for job_id in selected: + with self.subTest(job=job_id): + job = self.jobs[job_id] + needs = job["needs"] if isinstance(job["needs"], list) else [job["needs"]] + self.assertIn("ci-binaries", needs) + self.assertEqual(1, len(downloads(job))) + + def test_ci_result_requires_a_selected_builder(self) -> None: + final = self.jobs["ci-result"] + self.assertIn("ci-binaries", final["needs"]) + self.assertIn('"ci-binaries": "ci_binaries",', final["steps"][0]["run"]) + if __name__ == "__main__": unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 014fcf35fc..ec0ea39c7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,6 +47,7 @@ env: bregctl_wasm_in_rust casework_postgres scheduling_postgres + scheduling_managed_journey evidence_doctor evidence_contracts evidence_assurance @@ -77,6 +78,8 @@ env: breg_evidence_composition acceptance_journeys identifiers + ci_binaries + reference_host_smoke CARGO_TERM_COLOR: always CARGO_INCREMENTAL: "0" CARGO_PROFILE_DEV_DEBUG: "0" @@ -111,6 +114,7 @@ jobs: platform_coverage: ${{ steps.filter.outputs.platform_coverage }} platform_hygiene: ${{ steps.filter.outputs.platform_hygiene }} deployment: ${{ steps.filter.outputs.deployment }} + reference_host_smoke: ${{ steps.filter.outputs.reference_host_smoke }} config_conformance: ${{ steps.filter.outputs.config_conformance }} discovery_contracts: ${{ steps.filter.outputs.discovery_contracts }} breg_contracts: ${{ steps.filter.outputs.breg_contracts }} @@ -119,6 +123,7 @@ jobs: breg_contracts_lanes: ${{ steps.filter.outputs.breg_contracts_lanes }} casework_postgres: ${{ steps.filter.outputs.casework_postgres }} scheduling_postgres: ${{ steps.filter.outputs.scheduling_postgres }} + scheduling_managed_journey: ${{ steps.filter.outputs.scheduling_managed_journey }} evidence_doctor: ${{ steps.filter.outputs.evidence_doctor }} evidence_contracts: ${{ steps.filter.outputs.evidence_contracts }} evidence_assurance: ${{ steps.filter.outputs.evidence_assurance }} @@ -149,6 +154,7 @@ jobs: breg_evidence_composition: ${{ steps.filter.outputs.breg_evidence_composition }} acceptance_journeys: ${{ steps.filter.outputs.acceptance_journeys }} identifiers: ${{ steps.filter.outputs.identifiers }} + ci_binaries: ${{ steps.filter.outputs.ci_binaries }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -317,6 +323,11 @@ jobs: with: submodules: false + - name: Setup Node + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version: 24.11.0 + - name: Test deployment contracts shell: bash run: | @@ -677,6 +688,12 @@ jobs: - name: Keep rstack a plain bootstrap launcher run: python3 products/platform/scripts/check-rstack-dependencies.py + - name: Test the Session dependency boundary check + run: python3 -m unittest products/platform/scripts/test_check_session_dependencies.py + + - name: Enforce the Session dependency boundary + run: python3 products/platform/scripts/check-session-dependencies.py + platform-fuzz: name: Platform fuzz smoke (${{ matrix.group }}) needs: @@ -1528,6 +1545,9 @@ jobs: - name: Self-test the Messaging vendor-neutrality gate run: products/messaging/scripts/test-check-vendor-neutrality.sh + - name: Self-test the Messaging role-assignment check + run: products/messaging/scripts/test-check-role-assignment.sh + - name: Enforce Messaging vendor neutrality run: products/messaging/scripts/check-vendor-neutrality.sh @@ -1574,6 +1594,10 @@ jobs: env: MESSAGINGCTL_BIN: ${{ github.workspace }}/target/debug/messagingctl run: uv run --no-project --with PyYAML==6.0.2 products/messaging/scripts/check-checkpoint.sh + - name: Verify the native Messaging role assignment that rstack dev check reads + env: + MESSAGINGCTL_BIN: ${{ github.workspace }}/target/debug/messagingctl + run: products/messaging/scripts/check-role-assignment.sh - name: Verify migrations, readiness, and the served runtime env: MESSAGING_TEST_DATABASE_URL: postgresql://messaging:messaging_test@localhost:${{ job.services.postgres.ports['5432'] }}/messaging @@ -2757,6 +2781,9 @@ jobs: - name: Test release image build command run: python3 -m unittest release/scripts/test_build_release_image.py + - name: Test candidate reference host inputs and workflow + run: uv run --no-project --with PyYAML==6.0.2 python3 -m unittest release/scripts/test_candidate_host_smoke.py + - name: Test release candidate manifest and promotion verifier run: python3 -m unittest release/scripts/test_release_candidate.py @@ -3830,6 +3857,25 @@ jobs: --expected products/platform/journeys/expected-failures-thunderid.yaml --strict --out "${RUNNER_TEMP}/journeys/own-provider-thunderid" + # The managed Scheduling task-authority journey reuses this leg's image + # pull and binary builds: a strict ThunderID run whose rstack dev + # Scheduling runtime is bound to one live Casework task authority. The + # product script fails unless the run proves all four outcomes and + # leaves no container behind. + - name: Install uv for the managed Scheduling journey + if: matrix.leg == 'own-provider-thunderid' && needs.changes.outputs.scheduling_managed_journey == 'true' + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + version: "0.11.16" + + - name: Run the managed Scheduling task-authority journey + if: matrix.leg == 'own-provider-thunderid' && needs.changes.outputs.scheduling_managed_journey == 'true' + run: >- + uv run --no-project --with PyYAML==6.0.2 + products/scheduling/scripts/run_managed_task_authority_journey.py + --bin-dir "${GITHUB_WORKSPACE}/target/debug" + --out "${RUNNER_TEMP}/journeys/scheduling-managed" + - name: Run the rstack dev journey if: matrix.leg == 'rstack-dev' run: >- @@ -4351,6 +4397,11 @@ jobs: 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 + -p registry-session + + - name: Check service preview browser route parity + if: needs.changes.outputs.service_previews == 'true' + run: node --test clients/typescript/preview/tests/route-parity.mjs - name: Install Chromium for previews if: needs.changes.outputs.service_previews == 'true' @@ -4433,6 +4484,121 @@ jobs: working-directory: clients/typescript run: npm run test:live -- --require-deno + ci-binaries: + name: Shared CI-profile binaries + needs: changes + if: needs.changes.outputs.ci_binaries == 'true' + runs-on: ubuntu-24.04 + # Builds once the binaries several jobs run, and publishes them as one + # artifact, so each consumer downloads instead of compiling. The CI + # profile keeps the build short; release-profile binaries are proven by + # the nightly release workflow. + timeout-minutes: 40 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + submodules: false + + - name: Cache Cargo registry + uses: Swatinem/rust-cache@eedcf2fb1c22f010a0eb66b92f378c110977f266 # v2 + with: + shared-key: workspace-registry + cache-targets: false + save-if: ${{ github.ref == 'refs/heads/main' }} + + - name: Build the shared CI-profile binaries + run: | + set -euo pipefail + cargo build --locked --profile ci --bins --features registry-breg/runtime \ + -p registry-rstack -p registry-session -p registry-breg -p registry-bregctl \ + -p registry-casework -p registry-caseworkctl + mkdir -p "${RUNNER_TEMP}/ci-binaries" + for binary in rstack registry-session breg bregctl casework caseworkctl; do + install -m 0755 "target/ci/${binary}" "${RUNNER_TEMP}/ci-binaries/${binary}" + done + # A tar keeps the executable bits an artifact upload would drop. + tar -C "${RUNNER_TEMP}/ci-binaries" -cf "${RUNNER_TEMP}/ci-binaries.tar" . + + - name: Upload the shared CI-profile binaries + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: ci-binaries + path: ${{ runner.temp }}/ci-binaries.tar + if-no-files-found: error + retention-days: 1 + + reference-host-smoke: + name: Reference host smoke (${{ matrix.profile }}) + needs: [changes, ci-binaries] + if: needs.changes.outputs.reference_host_smoke == 'true' + runs-on: ubuntu-24.04 + # Both profiles run the binaries the ci-binaries job built once, so + # neither compiles. Release-profile binaries are proven by the release + # workflows. + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + profile: [breg, casework] + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + submodules: false + + - name: Setup Node + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version: 24.11.0 + cache: npm + cache-dependency-path: clients/typescript/package-lock.json + + - name: Download the shared CI-profile binaries + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: ci-binaries + path: ${{ runner.temp }} + + - name: Unpack the shared CI-profile binaries + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/ci-binaries" + tar -C "${RUNNER_TEMP}/ci-binaries" -xf "${RUNNER_TEMP}/ci-binaries.tar" + + - name: Build the preview client and install Chromium + run: | + set -euo pipefail + client="$GITHUB_WORKSPACE/clients/typescript" + npm --prefix "$client" ci --ignore-scripts --no-audit --no-fund + npm --prefix "$client" run build + node "$client/node_modules/playwright-core/cli.js" install --with-deps chromium + + - name: Run the reference host and verify its browser receipt + timeout-minutes: 15 + env: + REFERENCE_PROFILE: ${{ matrix.profile }} + run: | + set -euo pipefail + recipe="$GITHUB_WORKSPACE/deploy/examples/business-registration" + client="$GITHUB_WORKSPACE/clients/typescript" + REFERENCE_YAML_MODULE="$client/node_modules/yaml/dist/index.js" \ + node --test "$recipe/tests/receipt.test.mjs" "$recipe/tests/routes.test.mjs" + REFERENCE_ESBUILD_PACKAGE="$client/node_modules/esbuild" \ + node --test "$recipe/tests/build-host-client.test.mjs" + bash "$recipe/tests/run-reference.sh" "$REFERENCE_PROFILE" "$RUNNER_TEMP/ci-binaries" \ + "$client/node_modules/playwright-core/index.mjs" "$client/node_modules/yaml/dist/index.js" \ + "$RUNNER_TEMP/reference-host-receipt.json" + + - name: Upload the checked browser receipt + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: reference-host-${{ matrix.profile }}-receipt + path: ${{ runner.temp }}/reference-host-receipt.json + if-no-files-found: error + ci-result: name: CI result if: always() @@ -4487,6 +4653,8 @@ jobs: - typescript-live - release-linux-node-clients - deployment + - reference-host-smoke + - ci-binaries runs-on: ubuntu-slim timeout-minutes: 5 env: @@ -4538,6 +4706,8 @@ jobs: "acceptance-journeys": "acceptance_journeys", "adapter-openbao": "adapter_openbao", "deployment": "deployment", + "reference-host-smoke": "reference_host_smoke", + "ci-binaries": "ci_binaries", } selection = jobs["changes"].get("outputs", {}) for name, output in selected_by.items(): diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index f065943eab..ab00d06e69 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -590,6 +590,12 @@ jobs: --strict --output "${RUNNER_TEMP}/release-render-letter.pdf" test -s "${RUNNER_TEMP}/release-render-letter.pdf" fi + session_image_in_release="$(python3 release/scripts/release_roster.py \ + session-image-in-release "${{ needs.validate.outputs.version }}")" + if [[ "${session_image_in_release}" == true ]]; then + test "$(dist/image-bin/registry-session --version)" = \ + "registry-session ${{ needs.validate.outputs.version }}" + fi oid4vci_image_in_release="$(python3 release/scripts/release_roster.py \ evidence-oid4vci-image-in-release "${{ needs.validate.outputs.version }}")" if [[ "${oid4vci_image_in_release}" == true ]]; then @@ -2710,3 +2716,94 @@ jobs: subject-path: | candidate/release-candidate-manifest.json candidate/${{ needs.validate.outputs.prefix }}-${{ needs.validate.outputs.asset_tag }}-candidate.tar.gz + + reference-host: + name: Prove the sealed candidate on the Compose reference host (${{ matrix.profile }}) + needs: [validate, attest] + if: >- + needs.validate.outputs.unit == 'stack' && + contains(format(' {0} ', needs.validate.outputs.image_names), ' registry-session ') + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + profile: [breg, casework] + permissions: + actions: read + attestations: read + contents: read + packages: read + steps: + - name: Checkout exact protected candidate source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.validate.outputs.source_sha }} + fetch-depth: 1 + persist-credentials: false + submodules: false + + - name: Download the attested candidate from this attempt + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: registry-stack-release-candidate-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/reference-candidate + + - name: Verify the sealed candidate and stage exact host inputs + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_BUNDLE: ${{ needs.validate.outputs.bundle_name }} + CANDIDATE_RELEASE_ID: ${{ needs.validate.outputs.release_id }} + CANDIDATE_SOURCE: ${{ needs.validate.outputs.source_sha }} + CANDIDATE_VERSION: ${{ needs.validate.outputs.version }} + REFERENCE_PROFILE: ${{ matrix.profile }} + shell: bash + run: | + set -euo pipefail + artifact="${RUNNER_TEMP}/reference-candidate" + python3 release/scripts/candidate_host_inputs.py verify --current-run \ + --profile "${REFERENCE_PROFILE}" \ + --manifest "${artifact}/release-candidate-manifest.json" \ + --bundle "${artifact}/${CANDIDATE_BUNDLE}" \ + --source-sha "${CANDIDATE_SOURCE}" --version "${CANDIDATE_VERSION}" \ + --release-id "${CANDIDATE_RELEASE_ID}" \ + --run-id "${GITHUB_RUN_ID}" --run-attempt "${GITHUB_RUN_ATTEMPT}" \ + --output "${RUNNER_TEMP}/reference-host-inputs" + + - name: Pull only verified private candidate digests + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + refs="$(jq -er '.images[]' "${RUNNER_TEMP}/reference-host-inputs/inputs.json")" + export DOCKER_CONFIG + DOCKER_CONFIG="$(mktemp -d "${RUNNER_TEMP}/reference-ghcr.XXXXXX")" + trap 'docker logout ghcr.io' EXIT + printf '%s' "${GH_TOKEN}" | docker login ghcr.io \ + --username "${GITHUB_ACTOR}" --password-stdin + while IFS= read -r ref; do + docker pull --platform linux/amd64 "${ref}" + done <<<"${refs}" + + - name: Set up Node for the candidate reference host + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24.11.0 + package-manager-cache: false + + - name: Run the release-profile Compose and browser proof + shell: bash + run: | + set -euo pipefail + stage="${RUNNER_TEMP}/reference-host-inputs" + bash "${stage}/source/release/scripts/candidate-host-smoke.sh" \ + "${stage}" "${RUNNER_TEMP}/candidate-host-receipt.json" --with-deps + + - name: Retain the checked reference host receipt + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: candidate-host-receipt-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.profile }} + path: ${{ runner.temp }}/candidate-host-receipt.json + if-no-files-found: error + retention-days: 2 diff --git a/.github/workflows/release-rehearsal.yml b/.github/workflows/release-rehearsal.yml index 8f7212a2b0..73491cdbcf 100644 --- a/.github/workflows/release-rehearsal.yml +++ b/.github/workflows/release-rehearsal.yml @@ -411,6 +411,12 @@ jobs: test "$(dist/image-bin/messagingctl --version)" = \ "messagingctl ${REHEARSAL_VERSION}" fi + session_image_in_release="$(python3 release/scripts/release_roster.py \ + session-image-in-release "${REHEARSAL_VERSION}")" + if [[ "${session_image_in_release}" == true ]]; then + test "$(dist/image-bin/registry-session --version)" = \ + "registry-session ${REHEARSAL_VERSION}" + fi coordinator_in_release="$(python3 release/scripts/release_roster.py \ coordinator-in-release "${REHEARSAL_VERSION}")" if [[ "${coordinator_in_release}" == true ]]; then diff --git a/.github/workflows/release-repeatability.yml b/.github/workflows/release-repeatability.yml index 5e812e119c..6aa1b81584 100644 --- a/.github/workflows/release-repeatability.yml +++ b/.github/workflows/release-repeatability.yml @@ -208,6 +208,8 @@ jobs: binary_names.update({"relay": "relay", "relayctl": "relayctl"}) if release_roster.scheduling_binary_in_release(parsed_version): binary_names["scheduling"] = "scheduling" + if release_roster.session_image_in_release(parsed_version): + binary_names["registry-session"] = "registry-session" for artifact, asset in sorted(binary_names.items()): if artifact in artifacts: print(f"{asset}-{tag}-linux-amd64") diff --git a/AGENTS.md b/AGENTS.md index fff41273da..245b84fbb5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,7 +113,7 @@ not products of their own. | `crates/registry-evidence-authoring` | The authoring form: the single implementation of the model an adopter writes and the checks it must satisfy, shared by adopter tooling | | `crates/registry-manifest-*` | Manifest core types and CLI | | `crates/registry-platform-*` | Shared primitives used by the maintained runtimes and tooling | -| `crates/registry-session` | Platform-owned browser session service and `registry-session` binary: server-held person tokens and the gateway's per-call check, held out of releases | +| `crates/registry-session` | Platform-owned browser session service and `registry-session` binary: server-held person tokens and the gateway's per-call check | | `crates/registry-platform-sqlite` | Shared bounded read-only SQLite security boundary used by Evidence | | `crates/registry-platform-x509` | Pure X.509 path validation outside TLS, against configured anchors only | | `crates/registry-platform-text` | Pure, versioned Unicode text normalisation pipelines; products own their named profiles | @@ -360,11 +360,15 @@ journal records no values. **Platform** also owns `registry-session`, a supporting service beside an 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. 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. +workspace crates and other `registry-*` packages it depends on +`registry-platform-*` only, and no crate but `registry-cli-docs`, which reads +its command tree, depends on it. +`products/platform/scripts/check-session-dependencies.py` enforces both +directions. It runs as one replica, with a check listener private to the +gateway. Numbered releases ship its binary from v0.51.0, as +`SESSION_FIRST_RELEASE` in `release/scripts/release_roster.py` sets. +`SESSION_IMAGE_FIRST_RELEASE` adds its container image from v0.52.0. +`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 dd5307a803..7893207052 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6843,6 +6843,7 @@ dependencies = [ "registry-evidence-verifier", "registry-platform-canonical-json", "registry-platform-crypto", + "registry-platform-httpsec", "registry-platform-httputil", "reqwest 0.12.28", "serde", @@ -8053,7 +8054,11 @@ dependencies = [ name = "registry-platform-postgres" version = "0.52.0" dependencies = [ + "base64 0.23.1", + "percent-encoding", + "rcgen", "registry-platform-config", + "rustls", "serde", "tokio-postgres", ] @@ -8066,9 +8071,11 @@ version = "0.52.0" name = "registry-platform-provision" version = "0.52.0" dependencies = [ + "base64 0.23.1", "clap", "getrandom 0.4.3", "postgres-protocol", + "rcgen", "registry-cli-report", "registry-platform-activation", "registry-platform-config", diff --git a/clients/typescript/README.md b/clients/typescript/README.md index 43e7cb98dc..b175a09f3f 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -380,6 +380,15 @@ 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. +Pass `{ onOutcome }` as the third argument to hear one outcome per answer: +its class (`succeeded`, `unauthenticated`, `request-refused`, +`preparation-failed`, `preparation-refused`, `preparation-deadline`, +`cancelled`, `product-refused` or `unresolved`), the attempt key once the +handler has checked it, and the HTTP status. An outcome carries no submitted +or prepared value and no credential, so a host can log it whole. The hook may +be async. A hook that throws or rejects is logged as `The holder outcome hook +failed.` and leaves the answer unchanged. + 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 diff --git a/clients/typescript/generate-service.ts b/clients/typescript/generate-service.ts index cf17029ce2..e68469fffa 100644 --- a/clients/typescript/generate-service.ts +++ b/clients/typescript/generate-service.ts @@ -373,21 +373,35 @@ export function generatePreviewFunctionBinding(productId: string, member: string return [ 'type ProductConnection = { readonly baseUrl: string }', 'type PreparedRun = { readonly products: Readonly> }', - 'type FunctionHandler = (request: Request, client: RegistryServerClient[' + key + ']) => Response | Promise', + 'export type PreviewCallerKind = "page" | "coordinator"', + 'type FunctionHandler = (request: Request, client: RegistryServerClient[' + key + '], caller: PreviewCallerKind) => Response | Promise', + '', + 'class CoordinatorRegistryAuthorityDenied extends Error {}', + '', + '// Refuse at the entry to the transport, including calls that bypass token lookup.', + 'class PreviewDeniedTransport extends Transport {', + ' override register(): Transport { return this }', + ' override async call(): Promise {', + ' throw new CoordinatorRegistryAuthorityDenied("Coordinator calls carry no registry authority.")', + ' }', + '}', '', 'export const defineFunction = (handle: FunctionHandler) => ({ products }: PreparedRun) => {', ' const id = ' + JSON.stringify(productId), ' const connection = Object.hasOwn(products, id) ? products[id] : undefined', ' if (!connection) throw new Error("Missing prepared BReg connection for " + id + ".")', ' const { baseUrl } = connection', - ' return (request: Request) => {', - ' const credential = /^Bearer ([A-Za-z0-9._-]+)$/iu.exec(request.headers.get("authorization") ?? "")?.[1]', - ' if (!credential) {', + ' const denied = registerMembers(new PreviewDeniedTransport({ baseUrl }), { baseUrl })[' + key + ']', + ' return async (request: Request, caller: PreviewCallerKind = "page") => {', + ' const credential = caller === "page"', + ' ? /^Bearer ([A-Za-z0-9._-]+)$/iu.exec(request.headers.get("authorization") ?? "")?.[1]', + ' : undefined', + ' if (caller !== "coordinator" && !credential) {', ' return Response.json({ message: "Sign in to continue." }, {', ' status: 401, headers: { "Cache-Control": "no-store" },', ' })', ' }', - ' const client = createRegistryServerClient({ baseUrl, token: () => credential })[' + key + ']', + ' const client = credential ? createRegistryServerClient({ baseUrl, token: () => credential })[' + key + '] : denied', ' // 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)', @@ -395,7 +409,14 @@ export function generatePreviewFunctionBinding(productId: string, member: string ' const copy = new Request(request.url, {', ' method: request.method, headers, body: request.body, duplex: "half", signal: request.signal,', ' } as RequestInit)', - ' return handle(copy, client)', + ' try {', + ' return await handle(copy, client, caller)', + ' } catch (error) {', + ' if (caller !== "coordinator" || !(error instanceof CoordinatorRegistryAuthorityDenied)) throw error', + ' return Response.json({ code: "preview.coordinator-registry-authority-denied" }, {', + ' status: 403, headers: { "Cache-Control": "no-store" },', + ' })', + ' }', ' }', '}', '', diff --git a/clients/typescript/generate.ts b/clients/typescript/generate.ts index 5139f788b7..9f04567b79 100644 --- a/clients/typescript/generate.ts +++ b/clients/typescript/generate.ts @@ -264,7 +264,7 @@ export function generate(source: string, settings: Settings = {}): string { // problem types in that namespace, using the same compatibility rules as the Rust client. const discoveryProblems = title === 'Registry Discovery' && Array.isArray(schemas.Problem?.oneOf) ? schemas.Problem.oneOf.map(({ properties }: Node) => - [properties.type.const, { title: properties.title.const, status: properties.status.const, code: properties.code.const }]) + [properties.type.const, { status: properties.status.const, code: properties.code.const }]) : undefined for (const [name] of members(schemas)) { const pointer = '/components/schemas/' + escape(name) @@ -1090,18 +1090,29 @@ export function generate(source: string, settings: Settings = {}): string { '])', 'const routes: Record = Object.create(null)', ...(discoveryProblems ? [ - 'const knownProblems: Record = Object.fromEntries(' + quote(discoveryProblems) + ')', + 'const knownProblems: Record = Object.fromEntries(' + quote(discoveryProblems) + ')', + 'const knownCodes = new Set(Object.values(knownProblems).map(problem => problem.code))', 'function discoveryProblem(value: unknown, headers: Headers): boolean {', ' if (!value || typeof value !== "object") return false', - ' const { type, title, status, code, traceId } = value as Record', - ' if (typeof type !== "string" || typeof title !== "string" || typeof status !== "number" || status < 400 || status >= 600) return false', + ' // A problem is classified by type, status and code; title and detail are prose a server may reword.', + ' const problem = value as Record', + ' const { type, status, code, title, traceId } = problem', + ' if (typeof title !== "string" || typeof type !== "string" || typeof status !== "number" || status < 400 || status >= 600) return false', ' const known = Object.hasOwn(knownProblems, type) ? knownProblems[type] : undefined', ' if ((known || traceId !== undefined || headers.has("traceparent")) && !matchesTrace(headers, traceId)) return false', - ' if (known) return known.title === title && known.status === status && (code === undefined || known.code === code)', + ' // A later release may add a code under a known type; another known type\'s code stays a contradiction.', + ' const validCode = typeof code === "string" && code.length <= 128', + ' && /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\\.[a-z0-9]+(?:-[a-z0-9]+)*)*$/u.test(code)', ' const prefix = "https://id.registrystack.org/problems/registry-discovery/"', ' const suffix = type.slice(prefix.length)', - ' return type.startsWith(prefix) && suffix.length <= 128 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(suffix)', - ' && title.length > 0 && [...title].length <= 128 && !/\\p{Cc}/u.test(title)', + ' const valid = known', + ' ? known.status === status && (code === undefined || known.code === code || (validCode && !knownCodes.has(code)))', + ' : (code === undefined || validCode) && type.startsWith(prefix) && suffix.length <= 128 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(suffix)', + ' if (valid) {', + ' delete problem.title', + ' delete problem.detail', + ' }', + ' return valid', '}', ] : []), 'type Definition = Omit & { problems?: Record;' + diff --git a/clients/typescript/generated/breg-facility.ts b/clients/typescript/generated/breg-facility.ts index 5d96bf155e..03de78ac6f 100644 --- a/clients/typescript/generated/breg-facility.ts +++ b/clients/typescript/generated/breg-facility.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 a29f66c2bbff96fab6003672e8e13f9a958c6ed04ebd6c55a6c5bb762b472187 +// Source SHA-256 04e9cb0a48a7f056eea904829bf26257ecd384e04b0b619c87fd0bd758629ef8 // Unconstrained JSON /paths/~1v1~1records~1directory-entries~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/properties/value // Unconstrained JSON /paths/~1v1~1records~1operators~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/properties/value import { assertClientVersion, type Transport, type Answer, type CallOptions, type JsonValue, type Operation, type Page, type RequestValues, type ResponseVariant, type WireBytes, type WireText } from "../core.ts" diff --git a/clients/typescript/generated/discovery.ts b/clients/typescript/generated/discovery.ts index 9b7e996e77..c60ba9aae3 100644 --- a/clients/typescript/generated/discovery.ts +++ b/clients/typescript/generated/discovery.ts @@ -33,18 +33,29 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1services/get/responses/200/content/application~1json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ServiceSearchResponse\"}")], ]) const routes: Record = Object.create(null) -const knownProblems: Record = Object.fromEntries([["https://id.registrystack.org/problems/registry-discovery/invalid-request",{"title":"Invalid request","status":400,"code":"request.invalid"}],["https://id.registrystack.org/problems/registry-discovery/not-found",{"title":"Not found","status":404,"code":"request.not-found"}],["https://id.registrystack.org/problems/registry-discovery/result-bound-exceeded",{"title":"Result bound exceeded","status":422,"code":"request.result-bound-exceeded"}],["https://id.registrystack.org/problems/registry-discovery/unavailable",{"title":"Unavailable","status":503,"code":"service.unavailable"}]]) +const knownProblems: Record = Object.fromEntries([["https://id.registrystack.org/problems/registry-discovery/invalid-request",{"status":400,"code":"request.invalid"}],["https://id.registrystack.org/problems/registry-discovery/not-found",{"status":404,"code":"request.not-found"}],["https://id.registrystack.org/problems/registry-discovery/result-bound-exceeded",{"status":422,"code":"request.result-bound-exceeded"}],["https://id.registrystack.org/problems/registry-discovery/unavailable",{"status":503,"code":"service.unavailable"}]]) +const knownCodes = new Set(Object.values(knownProblems).map(problem => problem.code)) function discoveryProblem(value: unknown, headers: Headers): boolean { if (!value || typeof value !== "object") return false - const { type, title, status, code, traceId } = value as Record - if (typeof type !== "string" || typeof title !== "string" || typeof status !== "number" || status < 400 || status >= 600) return false + // A problem is classified by type, status and code; title and detail are prose a server may reword. + const problem = value as Record + const { type, status, code, title, traceId } = problem + if (typeof title !== "string" || typeof type !== "string" || typeof status !== "number" || status < 400 || status >= 600) return false const known = Object.hasOwn(knownProblems, type) ? knownProblems[type] : undefined if ((known || traceId !== undefined || headers.has("traceparent")) && !matchesTrace(headers, traceId)) return false - if (known) return known.title === title && known.status === status && (code === undefined || known.code === code) + // A later release may add a code under a known type; another known type's code stays a contradiction. + const validCode = typeof code === "string" && code.length <= 128 + && /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)*$/u.test(code) const prefix = "https://id.registrystack.org/problems/registry-discovery/" const suffix = type.slice(prefix.length) - return type.startsWith(prefix) && suffix.length <= 128 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(suffix) - && title.length > 0 && [...title].length <= 128 && !/\p{Cc}/u.test(title) + const valid = known + ? known.status === status && (code === undefined || known.code === code || (validCode && !knownCodes.has(code))) + : (code === undefined || validCode) && type.startsWith(prefix) && suffix.length <= 128 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(suffix) + if (valid) { + delete problem.title + delete problem.detail + } + return valid } type Definition = Omit & { problems?: Record; responses: Record> } const definitions: Record = Object.fromEntries([ diff --git a/clients/typescript/generated/render.ts b/clients/typescript/generated/render.ts index 6f70acdd73..a75dbc0d8c 100644 --- a/clients/typescript/generated/render.ts +++ b/clients/typescript/generated/render.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 f55f36da7de7a0417c2085878f09ee28cc47f6b0649b81901780a629722fa0b7 +// Source SHA-256 f2cb933e7724616c306efb314897f3e4ebf0ac8ae7df55be63c2394a0f311549 import { assertClientVersion, type Transport, type Answer, type CallOptions, type JsonValue, type Operation, type Page, type RequestValues, type ResponseVariant, type WireBytes, type WireText } from "../core.ts" import { validator } from "../schema.ts" diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts index b7ed745014..369f8eaedb 100644 --- a/clients/typescript/holder-function.ts +++ b/clients/typescript/holder-function.ts @@ -61,6 +61,42 @@ export interface HolderCreateBinding = HolderTargetBinding | HolderCreateBinding +/** Why the handler gave the answer it gave. */ +export type HolderOutcomeClass = + | 'succeeded' + /** No bearer of the expected shape. */ + | 'unauthenticated' + /** A route, method, attempt key, media type, size or submission outside the binding. */ + | 'request-refused' + /** The preparation threw or rejected. */ + | 'preparation-failed' + /** The preparation returned a value the host's preparation parser refused. */ + | 'preparation-refused' + | 'preparation-deadline' + /** The caller went away before dispatch; no Action call was made. */ + | 'cancelled' + /** The product's own settled 4xx refusal. */ + | 'product-refused' + /** The product may have acted; reconcile by the attempt key. */ + | 'unresolved' + +/** + * One answer, for an operator. It never carries a submitted or prepared value, a product + * answer, or the caller's credential. + */ +export interface HolderOutcome { + class: HolderOutcomeClass + /** The lower-case attempt key, once the handler has read a valid one. */ + attemptKey: string | undefined + /** The HTTP status the handler answered with. */ + status: number +} + +export interface HolderActionOptions { + /** Called once per answer. A hook that throws is logged and leaves the answer unchanged. */ + onOutcome?: (outcome: HolderOutcome) => void | PromiseLike +} + function reply(body: object, status: number): Response { return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) } @@ -117,10 +153,16 @@ async function readSubmission(request: Request): Promise { } } +class PreparationDeadline extends Error { + constructor() { + super('The preparation deadline expired.') + } +} + 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.') + const expired = new PreparationDeadline() let stop!: (reason: unknown) => void const stopped = new Promise((_resolve, reject) => { stop = reject }) const abort = () => stop(signal.reason) @@ -148,15 +190,23 @@ async function prepareInTime(run: (signal: AbortSignal) => unknown, signal: Abor } } +/** A product's settled 4xx refusal. */ +function settledRefusal(error: unknown): error is RegistryError & { status: number } { + return error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown && + error.status !== undefined && error.status >= 400 && error.status < 500 +} + +/** A refusal that says the attempt key was already spent, so the first attempt may have acted. */ +function spentKey(error: RegistryError & { status: number }): boolean { + return error.status === 409 && error.code === 'idempotency.key-reused' || + error.status === 410 && error.code === 'idempotency.expired' +} + /** 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 + if (!settledRefusal(error)) return undefined + if (spentKey(error)) return unresolvedOutcome(error.status) + return reply({ message: 'BReg refused the request.' }, error.status) } /** @@ -181,6 +231,7 @@ function productRefusal(error: unknown): Response | undefined { export function createHolderActionHandler( binding: HolderActionBinding, prepare: (input: Preparation, options: { signal: AbortSignal }) => unknown | Promise, + options: HolderActionOptions = {}, ): (request: Request) => Promise { // Read the binding once: later changes to the object it came from have no effect. const { kind, path, preparationTimeoutMs, parsePreparation } = binding @@ -191,68 +242,100 @@ export function createHolderActionHandler 2_147_483_647) { throw new TypeError('Expected a bounded preparation deadline.') } + const { onOutcome } = options + if (onOutcome !== undefined && typeof onOutcome !== 'function') throw new TypeError('Expected an outcome hook function.') return async request => { + let attemptKey: string | undefined + const report = (outcomeClass: HolderOutcomeClass, response: Response): Response => { + if (onOutcome) { + const failed = () => { console.error('The holder outcome hook failed.') } + try { + // A hook may be async: a rejection is logged like a throw, never left unhandled. + const returned: unknown = onOutcome({ class: outcomeClass, attemptKey, status: response.status }) + if (typeof (returned as PromiseLike | undefined)?.then === 'function') { + Promise.resolve(returned).catch(failed) + } + } catch { + failed() + } + } + return response + } + // A failed preparation: the deadline, the caller going away, or the function itself. + const preparationFailure = (error: unknown): Response => report( + error instanceof PreparationDeadline ? 'preparation-deadline' + : request.signal.aborted ? 'cancelled' : 'preparation-failed', + reply({ message: 'The function could not prepare the request.' }, 502)) + // No usable input: the caller went away, or the host's parser refused the preparation. + const noInput = (): Response => report(request.signal.aborted ? 'cancelled' : 'preparation-refused', + reply({ message: 'The function could not prepare the request.' }, 502)) + const dispatchFailure = (error: unknown): Response => { + const refusal = productRefusal(error) + if (refusal) return report(settledRefusal(error) && spentKey(error) ? 'unresolved' : 'product-refused', refusal) + return report('unresolved', unresolvedOutcome()) + } + const url = new URL(request.url) if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) { - return reply({ message: 'Unknown function route.' }, 404) + return report('request-refused', 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) + if (!credential) return report('unauthenticated', 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) + return report('request-refused', reply({ message: 'Send a JSON request with its attempt key.' }, 400)) } + attemptKey = idempotencyKey let body: unknown try { body = await readSubmission(request) } catch { - return reply({ message: 'Send a valid JSON request.' }, 400) + return report('request-refused', reply({ message: 'Send a valid JSON request.' }, 400)) } - if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413) + if (body === bodyTooLarge) return report('request-refused', 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) + return report('request-refused', reply({ message: 'Send a valid JSON request.' }, 400)) } - if (!created) return reply({ message: 'Send the declared request.' }, 400) + if (!created) return report('request-refused', 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) + } catch (error) { + return preparationFailure(error) } - if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + if (!input || request.signal.aborted) return noInput() 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) + return report('succeeded', reply({ recordId: result.recordId }, 200)) } } catch (error) { - const refusal = productRefusal(error) - if (refusal) return refusal + return dispatchFailure(error) } - return unresolvedOutcome() + return report('unresolved', unresolvedOutcome()) } let submission: HolderSubmission | undefined try { if (body !== undefined) submission = target!.parseSubmission(body) } catch { - return reply({ message: 'Send a valid JSON request.' }, 400) + return report('request-refused', 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) + return report('request-refused', reply({ message: 'Send a record and its reviewed condition.' }, 400)) } const { recordId, ifMatch, preparation } = submission @@ -260,18 +343,17 @@ export function createHolderActionHandler prepare(preparation, { signal }), request.signal, preparationTimeoutMs)) - } catch { - return reply({ message: 'The function could not prepare the request.' }, 502) + } catch (error) { + return preparationFailure(error) } - if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + if (!input || request.signal.aborted) return noInput() try { const result = await target!.invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) - if (result.recordId === recordId) return reply({ recordId }, 200) + if (result.recordId === recordId) return report('succeeded', reply({ recordId }, 200)) } catch (error) { - const refusal = productRefusal(error) - if (refusal) return refusal + return dispatchFailure(error) } - return unresolvedOutcome() + return report('unresolved', unresolvedOutcome()) } } diff --git a/clients/typescript/preview/build.mjs b/clients/typescript/preview/build.mjs index 3cda37aab9..e8ad5330a7 100644 --- a/clients/typescript/preview/build.mjs +++ b/clients/typescript/preview/build.mjs @@ -114,12 +114,16 @@ async function stagePreview(plan, directory) { throw new Error('The preview output must resolve below the UI project.') } const policy = previewPolicy(plan.preview) - const entries = Object.entries(plan.functions) - if (!entries.length || entries.some(([name]) => !localId.test(name)) || - [...policy.functions].some(name => !Object.hasOwn(plan.functions, name))) { + if (!plan.functions || typeof plan.functions !== 'object' || Array.isArray(plan.functions)) { throw new Error('Declare each preview function in the service inventory.') } - for (const [name, path] of entries) { + const inventory = Object.entries(plan.functions) + const selected = new Set([...policy.functions, ...policy.coordinatorFunctions]) + if ((!selected.size && inventory.length) || inventory.some(([name]) => !localId.test(name)) || + [...selected].some(name => !Object.hasOwn(plan.functions, name))) { + throw new Error('Declare each preview function in the service inventory.') + } + for (const [name, path] of inventory) { if (path !== join(project, 'functions', name, 'index.ts')) { throw new Error('Preview function paths must match their declared entries.') } @@ -136,7 +140,7 @@ async function stagePreview(plan, directory) { const stagedUi = join(staged, relative(project, ui)) await mkdir(staged, { mode: 0o700 }) await copySource(ui, stagedUi, output) - await copySource(join(project, 'functions'), join(staged, 'functions')) + if (inventory.length) await copySource(join(project, 'functions'), join(staged, 'functions')) await writeFile(join(staged, 'package.json'), '{"type":"module"}\n', { flag: 'wx' }) const installedModules = join(project, 'node_modules') @@ -154,12 +158,28 @@ async function stagePreview(plan, directory) { await symlink(clientPackage, join(stagedModules, 'client'), 'dir') } return { - entries: entries.map(([name, path]) => [name, join(staged, relative(project, path))]), + entries: inventory.filter(([name]) => selected.has(name)) + .map(([name, path]) => [name, join(staged, relative(project, path))]), pageEntry: join(stagedUi, 'src', 'page.ts'), publicInput: join(stagedUi, 'public'), staged, staticOutput, policy, } } +// The bundle manifest. It leaves out the BReg project's absolute path, so the +// bytes do not depend on where the project was built. +export function previewManifest(plan, functions, staticOutput) { + const { project: _project, ...product } = plan.product + return JSON.stringify({ + version: versionLine, + declarationDigest: plan.declarationDigest, + product, + routeProducts: plan.routeProducts ?? [], + preview: plan.preview, + functions, + staticOutput, + }) + '\n' +} + export async function buildPreview(plan, directory) { if (!isAbsolute(directory) || !localId.test(plan.product?.id) || typeof plan.product.profile !== 'string') { throw new Error('The preview build needs a checked plan and absolute artifact directory.') @@ -180,6 +200,7 @@ export async function buildPreview(plan, directory) { const browser = await bundle({ absWorkingDir: staged, + preserveSymlinks: true, entryPoints: [pageEntry], outfile: join(staticOutput, 'app.js'), format: 'iife', @@ -196,6 +217,12 @@ export async function buildPreview(plan, directory) { throw new Error('The preview output is missing the configured HTML page.') } await bundle({ + // Resolve paths from the staged project, and keep the staged + // node_modules link rather than its target, so the module comments name + // only staged paths: the same wherever the run directory and the project + // checkout are, and free of host directories. + absWorkingDir: staged, + preserveSymlinks: true, entryPoints: { run: join(artifactDirectory, 'run.mjs'), configure: join(artifactDirectory, 'configure.mjs'), @@ -207,13 +234,7 @@ export async function buildPreview(plan, directory) { platform: 'node', target: 'node24', }) - await writeFile(join(directory, 'manifest.json'), JSON.stringify({ - version: versionLine, - declarationDigest: plan.declarationDigest, - product: plan.product, - routeProducts: plan.routeProducts ?? [], - preview: plan.preview, - functions: entries.map(([name]) => name), - staticOutput: relative(directory, staticOutput), - }) + '\n', { flag: 'wx', mode: 0o600 }) + await writeFile(join(directory, 'manifest.json'), + previewManifest(plan, entries.map(([name]) => name), relative(directory, staticOutput)), + { flag: 'wx', mode: 0o600 }) } diff --git a/clients/typescript/preview/config.mjs b/clients/typescript/preview/config.mjs index 3b04538b4a..fc8b5782dc 100644 --- a/clients/typescript/preview/config.mjs +++ b/clients/typescript/preview/config.mjs @@ -68,11 +68,15 @@ export async function prepareRuntimeConfig({ artifact, deployment, run }) { } 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.') + if (artifact.preview.functions.length + (artifact.preview.coordinatorFunctions?.length ?? 0) > 0) { + 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.') + } + } else if (functionHost !== undefined) { + throw new Error('A preview without functions takes no function host.') } return { schema, runId: run.runId, origin, port, breg: run.breg, preview: run.preview } } @@ -138,7 +142,7 @@ export async function configure({ artifact, deployment, runFile }) { for (const product of Object.values(actor.products)) await checkCredentialPath(product.authorizationFile, runFile) } } - await checkCredentialPath(config.preview.functionHost.keyFile, runFile) + if (config.preview.functionHost) await checkCredentialPath(config.preview.functionHost.keyFile, runFile) return config } diff --git a/clients/typescript/preview/gateway.mjs b/clients/typescript/preview/gateway.mjs index 068fe6f799..0d00a0d5fa 100644 --- a/clients/typescript/preview/gateway.mjs +++ b/clients/typescript/preview/gateway.mjs @@ -103,6 +103,15 @@ export function previewPolicy(preview) { || new Set(preview.functions).size !== preview.functions.length) { throw new Error('Expected distinct preview function IDs.') } + const coordinatorFunctions = preview.coordinatorFunctions === undefined ? [] : preview.coordinatorFunctions + if (!Array.isArray(coordinatorFunctions) + || coordinatorFunctions.some(name => typeof name !== 'string' || !localId.test(name) || preview.functions.includes(name)) + || new Set(coordinatorFunctions).size !== coordinatorFunctions.length) { + throw new Error('Expected distinct Coordinator-only function IDs outside the page selection.') + } + if (preview.functions.length + coordinatorFunctions.length > 64) { + throw new Error('The preview exceeds the 64-function limit.') + } if ((preview.actors === undefined) === (preview.breg === undefined)) { throw new Error('Expected either one actor with BReg routes or an actors map.') } @@ -122,6 +131,7 @@ export function previewPolicy(preview) { return { page, functions: new Set(preview.functions), + coordinatorFunctions: new Set(coordinatorFunctions), actors, allowsBreg, } @@ -232,8 +242,8 @@ export async function startPreviewGateway({ functionKey, }) { const products = gatewayProducts({ productId, profile, breg, authorization, preview, products: declaredProducts }) - const applicationOrigin = loopbackOrigin(application) const policy = previewPolicy(preview) + const applicationOrigin = application === undefined && !policy.functions.size ? null : loopbackOrigin(application) if (typeof functionAuthorization !== 'function' && functionAuthorization !== null) { throw new Error('The preview needs the actor credential for its functions, or null to serve none.') } @@ -313,7 +323,7 @@ export async function startPreviewGateway({ || (method === 'POST' && headers.origin !== origin)) { throw new RequestError(403, 'Open the service page to make this request') } - if (functionAuthorization && method === 'POST' && rawPath.startsWith('/api/functions/') && !url.search) { + if (applicationOrigin && 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, functionAuthorization, true) diff --git a/clients/typescript/preview/host.mjs b/clients/typescript/preview/host.mjs index 4238cdbc17..539afc5677 100644 --- a/clients/typescript/preview/host.mjs +++ b/clients/typescript/preview/host.mjs @@ -10,11 +10,6 @@ function same(value, expected) { 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 @@ -32,8 +27,9 @@ export function functionHostAuthorizer(key) { } } -export async function startFunctionHost(handlers, { authorize, port = 0 }) { +export async function startFunctionHost(handlers, { authorize, coordinatorOnly, port = 0 }) { if (typeof authorize !== 'function') throw new TypeError('The private function host requires an authorization check.') + if (!(coordinatorOnly instanceof Set)) throw new TypeError('The private function host requires a Coordinator-only function set.') const server = serve({ hostname: '127.0.0.1', port, @@ -52,10 +48,15 @@ export async function startFunctionHost(handlers, { authorize, port = 0 }) { if (request.method !== 'POST' || !handler) return new Response('Not Found', { status: 404 }) const caller = /^Bearer [A-Za-z0-9._-]+$/u.test(request.headers.get('authorization') ?? '') && authorize(request) - if (!caller) return new Response('Caller required', { status: 401 }) + if (caller !== 'coordinator' && caller !== 'gateway') { + return new Response('Caller required', { status: 401 }) + } + if (caller === 'gateway' && coordinatorOnly.has(name)) { + return new Response('Not Found', { status: 404 }) + } request.headers.delete('x-registry-preview-function') - if (caller === 'coordinator') request.headers.set('authorization', coordinatorBearer) - return handler(request) + if (caller === 'coordinator') request.headers.delete('authorization') + return handler(request, caller === 'gateway' ? 'page' : 'coordinator') }, }) await server.ready() diff --git a/clients/typescript/preview/run.mjs b/clients/typescript/preview/run.mjs index 1087cb883f..c2ce870ff1 100644 --- a/clients/typescript/preview/run.mjs +++ b/clients/typescript/preview/run.mjs @@ -1,7 +1,7 @@ import { writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { artifactDirectory, checkRuntimeConfig, configEnvironment, readArtifact, readAuthorization, readHostKey } from './config.mjs' -import { actorGatewayOptions, startPreviewGateway } from './gateway.mjs' +import { actorGatewayOptions, previewPolicy, startPreviewGateway } from './gateway.mjs' import { functionHostAuthorizer, startFunctionHost } from './host.mjs' async function run() { @@ -9,42 +9,48 @@ async function run() { const artifact = await readArtifact() const config = await checkRuntimeConfig(configFile, artifact) const actors = config.preview.actors + const { coordinatorFunctions } = previewPolicy(artifact.preview) 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() - for (const name of artifact.functions) { - try { - const { default: createHandler } = await import(new URL('./functions/' + name + '.mjs', import.meta.url)) - const handler = await createHandler({ products }) - if (typeof handler !== 'function') throw new TypeError('Expected a request handler.') - handlers.set(name, handler) - } catch { - throw new Error('Cannot initialize preview function ' + name + '. Export the generated defineFunction binding.') - } - } - - const functionKey = await readHostKey(config.preview.functionHost.keyFile) - const privateHost = await startFunctionHost(handlers, { - authorize: functionHostAuthorizer(functionKey), - port: config.preview.functionHost.port, - }) - const gateways = [] + const listeners = [] + const closeListeners = () => Promise.all(listeners.map(listener => listener.close())) try { - await writeFile(join(dirname(configFile), 'application-preview-function-origin'), - privateHost.origin + '\n', { flag: 'wx', mode: 0o600 }) const shared = { - application: privateHost.origin, publicDirectory: join(artifactDirectory, artifact.staticOutput), preview: artifact.preview, - functionKey, + } + const host = config.preview.functionHost + if (host) { + const connection = Object.freeze({ ...config.breg }) + const products = Object.freeze({ [artifact.product.id]: connection }) + const handlers = new Map() + for (const name of artifact.functions) { + try { + const { default: createHandler } = await import(new URL('./functions/' + name + '.mjs', import.meta.url)) + const handler = await createHandler({ products }) + if (typeof handler !== 'function') throw new TypeError('Expected a request handler.') + handlers.set(name, handler) + } catch { + throw new Error('Cannot initialize preview function ' + name + '. Export the generated defineFunction binding.') + } + } + const functionKey = await readHostKey(host.keyFile) + const privateHost = await startFunctionHost(handlers, { + authorize: functionHostAuthorizer(functionKey), + coordinatorOnly: coordinatorFunctions, + port: host.port, + }) + listeners.push(privateHost) + await writeFile(join(dirname(configFile), 'application-preview-function-origin'), + privateHost.origin + '\n', { flag: 'wx', mode: 0o600 }) + shared.application = privateHost.origin + shared.functionKey = functionKey } if (actors === undefined) { - gateways.push(await startPreviewGateway({ + listeners.push(await startPreviewGateway({ ...shared, origin: config.origin, port: config.port, @@ -59,17 +65,17 @@ async function run() { // 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 })) + listeners.push(await startPreviewGateway({ ...shared, ...options })) } } } catch (error) { - await Promise.all([...gateways.map(gateway => gateway.close()), privateHost.close()]) + await closeListeners() throw error } let closing function close() { - closing ??= Promise.all([...gateways.map(gateway => gateway.close()), privateHost.close()]).catch(() => { + closing ??= closeListeners().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 b8463d59ce..effd48261c 100644 --- a/clients/typescript/preview/tests/preview.test.mjs +++ b/clients/typescript/preview/tests/preview.test.mjs @@ -1,13 +1,16 @@ import { strict as assert } from 'node:assert' -import { chmod, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { spawn } from 'node:child_process' +import { once } from 'node:events' +import { chmod, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, 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 { coordinatorBearer, functionHostAuthorizer, startFunctionHost } from '../host.mjs' +import { setTimeout as delay } from 'node:timers/promises' +import { 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 { configEnvironment, configure, healthPath, prepareRuntimeConfig, readHostKey } from '../config.mjs' +import { buildPreview, generationError, generatorArguments, previewManifest } from '../build.mjs' import { createHash } from 'node:crypto' test('preview policy matches both Record revision parameters without expanding methods or routes', () => { @@ -28,6 +31,19 @@ test('preview policy matches both Record revision parameters without expanding m } }) +test('the preview manifest leaves out the BReg project path', () => { + const product = { id: 'businesses', member: 'businesses', project: '/home/builder/service/project', audience: 'urn:example:businesses', profile: 'registrar' } + const plan = { declarationDigest: 'a'.repeat(64), product, preview: { page: '/', functions: ['register'] } } + const manifest = JSON.parse(previewManifest(plan, ['register'], 'project/web/dist')) + assert.deepEqual(manifest.product, { id: 'businesses', member: 'businesses', audience: 'urn:example:businesses', profile: 'registrar' }) + assert.ok(!JSON.stringify(manifest).includes('/home/builder')) + assert.deepEqual(manifest.functions, ['register']) + assert.equal(manifest.staticOutput, 'project/web/dist') + assert.equal(manifest.declarationDigest, plan.declarationDigest) + assert.deepEqual(manifest.routeProducts, []) + assert.equal(plan.product.project, '/home/builder/service/project', 'the checked plan keeps its path') +}) + 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 })) @@ -56,6 +72,74 @@ test('preview build forwards the generator diagnostic', async (t) => { } }) +test('build stages a page-only preview without any function sources or bundles', async t => { + const root = await realpath(await mkdtemp(join(tmpdir(), 'registry-preview-page-only-'))) + t.after(() => rm(root, { recursive: true })) + const file = join(root, 'service.yaml') + const ui = join(root, 'web') + const artifact = join(root, 'artifact') + await mkdir(join(ui, 'src'), { recursive: true }) + await mkdir(join(ui, 'public')) + await writeFile(file, 'fixture declaration') + await writeFile(join(ui, 'src', 'page.ts'), 'document.title = "Page only"') + await writeFile(join(ui, 'public', 'index.html'), '') + + // This page uses no generated bindings. The installed browser journey + // separately proves that the real generator and native tools work together. + const generator = join(root, 'generator') + await writeFile(generator, '#!/usr/bin/env bash\nset -euo pipefail\n', { mode: 0o700 }) + const execPath = process.execPath + process.execPath = generator + try { + await 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: {}, + preview: { page: '/', breg: {}, functions: [] }, + }, artifact) + } finally { + process.execPath = execPath + } + const manifest = JSON.parse(await readFile(join(artifact, 'manifest.json'), 'utf8')) + assert.deepEqual(manifest.functions, []) + assert.match(await readFile(join(artifact, manifest.staticOutput, 'app.js'), 'utf8'), /Page only/u) + await assert.rejects(stat(join(artifact, 'project', 'functions')), { code: 'ENOENT' }) + await assert.rejects(stat(join(artifact, 'functions')), { code: 'ENOENT' }) +}) + +test('prepare requires a host for Coordinator-only functions and omits it for function-free previews', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-page-only-')) + t.after(() => rm(root, { recursive: true })) + const deployment = join(root, 'service.yaml') + await writeFile(deployment, 'fixture declaration') + const declarationDigest = createHash('sha256').update('fixture declaration').digest('hex') + const artifact = { + declarationDigest, + product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' }, + preview: { page: '/', breg: {}, functions: [] }, + } + 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', declarationDigest, authorizationFile: join(root, 'authorization'), + }, + } + const config = await prepareRuntimeConfig({ artifact, deployment, run }) + assert.equal(Object.hasOwn(config.preview, 'functionHost'), false) + const withHost = { ...run, preview: { + ...run.preview, functionHost: { port: 45678, keyFile: join(root, 'key') }, + } } + await assert.rejects(prepareRuntimeConfig({ artifact, deployment, run: withHost }), /without functions/u) + + const coordinatorOnly = { ...artifact, preview: { ...artifact.preview, coordinatorFunctions: ['publish'] } } + await assert.rejects(prepareRuntimeConfig({ artifact: coordinatorOnly, deployment, run }), /reserved function host/u) + const coordinatorConfig = await prepareRuntimeConfig({ artifact: coordinatorOnly, deployment, run: withHost }) + assert.deepEqual(coordinatorConfig.preview.functionHost, withHost.preview.functionHost) +}) + 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 })) @@ -65,7 +149,11 @@ test('prepare binds the run to the declaration, product, audience and loopback a 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 artifact = { + declarationDigest, + product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' }, + preview: { page: '/', functions: ['renew'], breg: {} }, + } const run = { schema: 'registry-stack.local-service-preview/v1', runId: 'fixture-run', origin: 'http://127.0.0.1:23456', port: 23456, insecureLocal: true, @@ -128,7 +216,7 @@ test('gateway permits exact paths and forwards only the chosen principal', async assert.equal(request.headers.get('x-registry-preview-function'), null) return new Response('renewed') }], - ]), { authorize: request => request.headers.get('x-registry-preview-function') === 'test-only-function-key' }) + ]), { authorize: request => request.headers.get('x-registry-preview-function') === 'test-only-function-key' && 'gateway', coordinatorOnly: new Set() }) t.after(() => privateHost.close()) const product = createServer((request, response) => { productCount++ @@ -210,6 +298,187 @@ test('build refuses a changed declaration or a linked function before staging', }, join(root, 'artifact')), /source resolves outside/i) }) +test('preview build and run respect the page and Coordinator-only selections', async t => { + const root = await realpath(await mkdtemp(join(tmpdir(), 'registry-preview-selection-'))) + t.after(() => rm(root, { recursive: true })) + const file = join(root, 'service.yaml') + const ui = join(root, 'web') + const artifact = join(root, 'artifact') + const generator = join(root, 'generator') + await mkdir(join(ui, 'src'), { recursive: true }) + await mkdir(join(ui, 'public')) + await writeFile(file, 'fixture declaration') + await writeFile(join(ui, 'src', 'page.ts'), 'document.title = "Preview"') + await writeFile(join(ui, 'public', 'index.html'), '') + await writeFile(generator, '#!/usr/bin/env bash\nset -euo pipefail\n', { mode: 0o700 }) + const functions = {} + for (const name of ['draft', 'publish', 'unused']) { + const directory = join(root, 'functions', name) + await mkdir(directory, { recursive: true }) + functions[name] = join(directory, 'index.ts') + await writeFile(functions[name], 'export default () => () => new Response(null)') + } + const plan = { + file, workspaceRoot: root, declarationDigest: createHash('sha256').update('fixture declaration').digest('hex'), + product: { id: 'permits', member: 'permits', project: root, profile: 'reader', audience: 'urn:preview' }, + ui: { project: ui, output: join(ui, 'dist') }, functions, + preview: { page: '/', functions: ['draft'], coordinatorFunctions: ['publish'], breg: {} }, + } + const coordinatorArtifact = join(root, 'coordinator-artifact') + const execPath = process.execPath + process.execPath = generator + try { + await buildPreview(plan, artifact) + const coordinatorOnly = { ...plan, preview: { ...plan.preview, functions: [] } } + await buildPreview(coordinatorOnly, coordinatorArtifact) + const coordinatorManifest = JSON.parse(await readFile(join(coordinatorArtifact, 'manifest.json'), 'utf8')) + assert.deepEqual(coordinatorManifest.functions, ['publish']) + await assert.rejects(buildPreview({ + ...coordinatorOnly, preview: { ...coordinatorOnly.preview, coordinatorFunctions: ['unlisted'] }, + }, join(root, 'invalid-artifact')), /Declare each preview function in the service inventory/u) + } finally { + process.execPath = execPath + } + const manifest = JSON.parse(await readFile(join(artifact, 'manifest.json'), 'utf8')) + assert.deepEqual(manifest.functions.sort(), ['draft', 'publish']) + assert.deepEqual((await readdir(join(artifact, 'functions'))).sort(), ['draft.mjs', 'publish.mjs']) + const args = generatorArguments(plan, join(artifact, 'project')) + assert.deepEqual(args.filter((_, index) => args[index - 1] === '--preview-function'), ['draft']) + + // Reserve distinct addresses as the runner does before it launches the artifact. + const reservations = [createServer(), createServer(), createServer()] + await Promise.all(reservations.map(server => new Promise(resolve => server.listen(0, '127.0.0.1', resolve)))) + const [port, hostPort, bregPort] = reservations.map(server => server.address().port) + const origin = 'http://127.0.0.1:' + port + const runFile = join(root, 'application-run.json') + const configFile = join(root, 'config.json') + const authorizationFile = join(root, 'authorization') + const keyFile = join(root, 'function-host-key') + const key = 'synthetic-run-function-host-key-0123456789' + const run = { + schema: 'registry-stack.local-service-preview/v1', + runId: 'fixture-run', origin, port, insecureLocal: true, + breg: { baseUrl: 'http://127.0.0.1:' + bregPort, audience: plan.product.audience }, + preview: { + productId: 'permits', profile: 'reader', declarationDigest: plan.declarationDigest, + authorizationFile, functionHost: { port: hostPort, keyFile }, + }, + } + try { + await writeFile(authorizationFile, 'Authorization: Bearer synthetic.actor.token\n', { mode: 0o600 }) + await writeFile(keyFile, key + '\n', { mode: 0o600 }) + await writeFile(runFile, JSON.stringify(run)) + const coordinatorManifest = JSON.parse(await readFile(join(coordinatorArtifact, 'manifest.json'), 'utf8')) + const prepared = await configure({ artifact: coordinatorManifest, deployment: file, runFile }) + await writeFile(configFile, JSON.stringify(prepared)) + } finally { + await Promise.all(reservations.map(server => new Promise(resolve => server.close(resolve)))) + } + + const runner = spawn(process.execPath, [join(coordinatorArtifact, 'run.mjs')], { + env: { ...process.env, [configEnvironment]: configFile }, stdio: ['ignore', 'ignore', 'pipe'], + }) + let stderr = '' + runner.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk }) + const finished = once(runner, 'close') + try { + const ready = async () => { + for (let attempt = 0; attempt < 200 && runner.exitCode === null; attempt++) { + const response = await fetch(origin + healthPath, { signal: AbortSignal.timeout(250) }).catch(() => undefined) + if (response?.ok) return true + await delay(25) + } + return false + } + assert.equal(await Promise.race([ready(), finished.then(() => false)]), true, stderr) + const endpoint = 'http://127.0.0.1:' + hostPort + '/functions/publish' + const page = await fetch(endpoint, { method: 'POST', headers: { + authorization: 'Bearer synthetic.actor.token', 'x-registry-preview-function': key, + } }) + assert.equal(page.status, 404) + const coordinator = await fetch(endpoint, { method: 'POST', headers: { authorization: 'Bearer ' + key } }) + assert.equal(coordinator.status, 200) + } finally { + runner.kill() + await finished + } +}) + +test('preview policy refuses invalid Coordinator-only selections', () => { + const preview = { page: '/', functions: ['draft'], breg: {} } + for (const coordinatorFunctions of ['publish', [null], ['publish', 'publish'], ['draft']]) { + assert.throws(() => previewPolicy({ ...preview, coordinatorFunctions }), /distinct Coordinator-only function IDs/u) + } +}) + +test('preview policy bounds the combined function selection', () => { + const functions = Array.from({ length: 32 }, (_, index) => 'page-' + index) + const coordinatorFunctions = Array.from({ length: 32 }, (_, index) => 'coordinator-' + index) + const preview = { page: '/', functions, coordinatorFunctions, breg: {} } + assert.equal(previewPolicy(preview).coordinatorFunctions.size, 32) + assert.throws(() => previewPolicy({ + ...preview, coordinatorFunctions: [...coordinatorFunctions, 'over-limit'], + }), /64-function limit/u) +}) + +test('the function host refuses an unrecognized caller kind', async t => { + const host = await startFunctionHost(new Map([['renew', () => new Response(null, { status: 204 })]]), { + authorize: () => 'unknown', coordinatorOnly: new Set(), + }) + t.after(() => host.close()) + const response = await fetch(host.origin + '/functions/renew', { + method: 'POST', headers: { authorization: 'Bearer synthetic-page' }, + }) + assert.equal(response.status, 401) +}) + +test('a Coordinator-only function refuses the page gateway and only admits the host key', async t => { + const root = await mkdtemp(join(tmpdir(), 'registry-preview-coordinator-only-')) + t.after(() => rm(root, { recursive: true })) + await writeFile(join(root, 'index.html'), '

Preview

') + const key = 'synthetic-function-host-key-0123456789abcdefghij' + const admitted = [] + const handle = (request, caller) => { + admitted.push([caller, request.headers.get('authorization')]) + return new Response(null, { status: 204 }) + } + const host = await startFunctionHost(new Map([['publish', handle], ['draft', handle]]), { + authorize: functionHostAuthorizer(key), coordinatorOnly: new Set(['publish']), + }) + t.after(() => host.close()) + const gateway = await startPreviewGateway({ + origin: null, port: 0, productId: 'permits', profile: 'reader', + breg: 'http://127.0.0.1:12345', application: host.origin, functionKey: key, + authorization: () => 'Bearer synthetic-page', publicDirectory: root, + preview: { page: '/', functions: ['draft'], coordinatorFunctions: ['publish'], breg: {} }, + }) + t.after(() => gateway.close()) + const page = { + origin: gateway.origin, 'registry-client': 'page', 'x-registry-preview-caller-kind': 'coordinator', + 'x-registry-preview-function': 'forged', authorization: 'Bearer forged', + } + const post = (url, headers) => fetch(url, { method: 'POST', headers }) + const refused = await post(gateway.origin + '/api/functions/publish', page) + assert.equal(refused.status, 404) + assert.deepEqual(await refused.json(), { message: 'Unknown preview route' }) + assert.equal((await post(gateway.origin + '/api/functions/draft', page)).status, 204) + assert.equal((await post(host.origin + '/functions/publish', { + authorization: 'Bearer synthetic-page', 'x-registry-preview-function': key, + 'x-registry-preview-caller-kind': 'coordinator', + })).status, 404) + assert.equal((await post(host.origin + '/functions/publish', { + authorization: 'Bearer ' + key, 'x-registry-preview-caller-kind': 'page', + })).status, 204) + assert.deepEqual(admitted, [['page', 'Bearer synthetic-page'], ['coordinator', null]]) +}) + +test('the function host requires an explicit Coordinator-only policy', async () => { + for (const coordinatorOnly of [undefined, []]) { + const start = startFunctionHost(new Map(), { authorize: () => false, coordinatorOnly }) + await assert.rejects(start.then(host => host.close()), /requires a Coordinator-only function set/u) + } +}) + 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) @@ -238,15 +507,14 @@ test('the function host binds its reserved port and admits only the run host key seen = request.headers.get('authorization') return new Response('renewed') }], - ]), { authorize, port }) + ]), { authorize, coordinatorOnly: new Set(), 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) + assert.equal(seen, null) }) test('the run host key file must be owner-only, in the run directory, and well formed', async t => { @@ -255,7 +523,11 @@ test('the run host key file must be owner-only, in the run directory, and well f 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 artifact = { + declarationDigest, + product: { id: 'licenses', member: 'licenses', audience: 'urn:preview', profile: 'holder' }, + preview: { page: '/', functions: ['renew'], breg: {} }, + } const authorizationFile = join(root, 'authorization') await writeFile(authorizationFile, 'Authorization: Bearer synthetic.actor.token\n', { mode: 0o600 }) const keyFile = join(root, 'function-host-key') @@ -466,13 +738,11 @@ test('configure refuses an actor credential file that is not owner-only or is a 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) diff --git a/clients/typescript/preview/tests/route-parity-fixtures.mjs b/clients/typescript/preview/tests/route-parity-fixtures.mjs new file mode 100644 index 0000000000..65c7f74e23 --- /dev/null +++ b/clients/typescript/preview/tests/route-parity-fixtures.mjs @@ -0,0 +1,53 @@ +// The upstreams declare the reviewed browser methods, paths and parameter names. +// Session exports module IDs, prefixes and rewrites. Envoy forwards by prefix. +// The business modules come from deploy/examples/business-registration/session.yaml. +// The medical-renewal and permit-review modules are test layouts that mirror the +// development /registry// and /api/functions/ mount convention. +export const deployments = { + 'business-registration': { + selected: 'businesses', + reference: true, + upstreams: { + businesses: { GET: ['/v1/records/businesses', '/v1/records/businesses/{recordId}'] }, + functions: { POST: ['/functions/register-business'] }, + }, + }, + 'medical-renewal': { + selected: 'licences', + modules: [ + { id: 'licences', product: 'breg', prefix: '/registry/licences/', rewrite: '/' }, + { id: 'functions', product: 'breg', prefix: '/api/functions/', rewrite: '/functions/' }, + ], + upstreams: { + licences: { + GET: ['/v1/records/licences', '/v1/records/licences/{recordId}'], + POST: ['/v1/actions/renew/target-conditions'], + }, + functions: { POST: ['/functions/renew'] }, + }, + }, + 'permit-review': { + selected: 'permits', + modules: [ + { id: 'permits', product: 'breg', prefix: '/registry/permits/', rewrite: '/' }, + { id: 'casework', product: 'casework', prefix: '/registry/casework/', rewrite: '/' }, + { id: 'permit-flow', product: 'coordinator', prefix: '/registry/permit-flow/', rewrite: '/' }, + { id: 'functions', product: 'breg', prefix: '/api/functions/', rewrite: '/functions/' }, + ], + upstreams: { + permits: { + GET: ['/v1/records/permit-applications', '/v1/records/permit-applications/{recordId}'], + POST: ['/v1/actions/submit-application'], + }, + casework: { + GET: ['/v1/review-tasks', '/v1/review-tasks/{taskId}/context'], + POST: ['/v1/review-tasks/{taskId}/claim', '/v1/review-tasks/{taskId}/decisions'], + }, + 'permit-flow': { + GET: ['/v1/workflows/permit-flow', '/v1/runs/{runId}'], + POST: ['/v1/runs'], + }, + functions: { POST: ['/functions/assess-permit', '/functions/digest-application'] }, + }, + }, +} diff --git a/clients/typescript/preview/tests/route-parity.mjs b/clients/typescript/preview/tests/route-parity.mjs new file mode 100644 index 0000000000..99ee824534 --- /dev/null +++ b/clients/typescript/preview/tests/route-parity.mjs @@ -0,0 +1,275 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { once } from 'node:events' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { isAbsolute, join } from 'node:path' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { parse } from 'yaml' +import { actorGatewayOptions, startPreviewGateway } from '../gateway.mjs' +import { deployments } from './route-parity-fixtures.mjs' + +const root = fileURLToPath(new URL('../../../../', import.meta.url)) +const examples = join(root, 'products/platform/examples/service-previews') +const reference = join(root, 'deploy/examples/business-registration') +const sampleId = '00000000-0000-4000-8000-000000000001' + +// Deployment-side scope exceptions: +// - Module prefixes forward any method and path. Compare the declared upstream +// browser contract, since Envoy applies prefix routing and upstreams decide admission. +// - /session/* serves Session's sign-in and identity flow. Dev uses synthetic identities. +// - /apply/ serves the reference UI. Page and asset routes are outside the browser API. +const developmentOnly = new Map([ + ['GET /_rstack/ready', 'The development supervisor checks preview readiness.'], + ['GET /_rstack/actor', 'The development-only permit-review page uses this to select its synthetic actor. Deployed pages obtain identity through Session.'], +]) + +function route(method, path) { + return { method, path, parameters: Array.from(path.matchAll(/\{([^{}]+)\}/gu), match => match[1]) } +} + +function describeRoute({ method, path, parameters }) { + return method + ' ' + path + (parameters.length ? ' [' + parameters.join(', ') + ']' : '') +} + +function assertRouteParity(development, deployed, exceptions = new Map()) { + const local = new Set(development.map(describeRoute)) + const production = new Set(deployed.map(describeRoute)) + for (const [exception, reason] of exceptions) { + assert(local.delete(exception), 'Unused development-only exception: ' + exception + ' (' + reason + ')') + assert(!production.has(exception), 'Deployment now serves the development-only route: ' + exception) + } + const developmentExtra = [...local].filter(key => !production.has(key)).sort() + const deploymentExtra = [...production].filter(key => !local.has(key)).sort() + assert(developmentExtra.length === 0 && deploymentExtra.length === 0, + 'Browser route parity failed\nDevelopment only: ' + developmentExtra.join(', ') + + '\nDeployment only: ' + deploymentExtra.join(', ')) +} + +for (const [label, seeded, message] of [ + ['path', route('GET', '/registry/businesses/v1/entries/businesses/{recordId}'), /entries\/businesses/u], + ['method', route('POST', '/registry/businesses/v1/records/businesses/{recordId}'), /POST/u], + ['parameter', route('GET', '/registry/businesses/v1/records/businesses/{businessId}'), /businessId/u], +]) { + test('route parity reports a seeded ' + label + ' change', () => { + const original = route('GET', '/registry/businesses/v1/records/businesses/{recordId}') + assert.throws(() => assertRouteParity([original], [seeded]), message) + }) +} + +test('route parity rejects an unused development-only exception', () => { + const ready = new Map([['GET /_rstack/ready', developmentOnly.get('GET /_rstack/ready')]]) + assert.throws(() => assertRouteParity([], [], ready), /Unused development-only exception: GET \/_rstack\/ready/u) +}) + +test('route parity rejects a development-only exception served by the deployment', () => { + const ready = route('GET', '/_rstack/ready') + const exceptions = new Map([['GET /_rstack/ready', developmentOnly.get('GET /_rstack/ready')]]) + assert.throws(() => assertRouteParity([ready], [ready], exceptions), /Deployment now serves the development-only route: GET \/_rstack\/ready/u) +}) + +function envoyPrefixRewrite(routes, module) { + const matcher = module.prefix.endsWith('/') ? 'prefix' : 'path_separated_prefix' + const envoyRoute = routes.find(candidate => candidate.match[matcher] === module.prefix) + assert(envoyRoute, 'Missing Envoy ' + matcher + ' for ' + module.prefix) + const rewrite = envoyRoute.route.prefix_rewrite + assert.equal(rewrite, module.prefixRewrite) + return rewrite +} + +for (const [prefix, prefixRewrite, matcher, wrongMatcher] of [ + ['/api/functions/register-business', '/functions/register-business', 'path_separated_prefix', 'prefix'], + ['/registry/businesses/', '/', 'prefix', 'path_separated_prefix'], +]) { + test('route parity reads Envoy ' + matcher + ' for ' + prefix, () => { + const routes = [{ match: { [matcher]: prefix }, route: { prefix_rewrite: prefixRewrite } }] + assert.equal(envoyPrefixRewrite(routes, { prefix, prefixRewrite }), prefixRewrite) + }) + + test('route parity rejects Envoy ' + wrongMatcher + ' for ' + prefix, () => { + const routes = [{ match: { [wrongMatcher]: prefix }, route: { prefix_rewrite: prefixRewrite } }] + assert.throws(() => envoyPrefixRewrite(routes, { prefix, prefixRewrite }), /Missing Envoy/u) + }) +} + +async function deployedRoutes(scratch, deployment) { + const binary = process.env.REGISTRY_SESSION_BIN ?? join(root, 'target/debug/registry-session') + assert(isAbsolute(binary), 'Use an absolute REGISTRY_SESSION_BIN path.') + + let runtimePath = join(reference, 'session.yaml') + const runtime = parse(await readFile(runtimePath, 'utf8')) + if (!deployment.reference) { + runtime.modules = deployment.modules.map(({ id, product, prefix, rewrite }) => ({ + id, product, prefix, signIns: ['registrar'], + audience: product === 'breg' ? 'person' : 'urn:example:' + id, + upstream: { cluster: id, prefixRewrite: rewrite }, + })) + runtimePath = join(scratch, 'session.json') + await writeFile(runtimePath, JSON.stringify(runtime)) + } + + const assembly = join(scratch, 'envoy.json') + const inventory = join(scratch, 'inventory.json') + const session = (...args) => execFileSync(binary, [ + '--runtime-config', runtimePath, 'gateway', 'envoy', '--posture', 'production', ...args, + ], { encoding: 'utf8' }) + const clusters = [...runtime.modules, ...runtime.pages].map(entry => entry.upstream.cluster) + const edge = deployment.reference ? parse(await readFile(join(reference, 'edge.yaml'), 'utf8')) : null + const upstreams = clusters.flatMap((name, index) => { + if (!edge) return ['--upstream', name + '=127.0.0.1:' + (8100 + 100 * index)] + const hop = edge.static_resources.listeners.find(listener => listener.name === 'to_' + name) + assert(hop, 'Missing reference first hop for ' + name) + const { address, port_value: port } = hop.address.socket_address + return ['--upstream', name + '=' + address + ':' + port] + }) + session('--standalone-out', assembly, '--listen', new URL(runtime.publicOrigin).host, + '--tls-certificate', join(scratch, 'app.crt'), '--tls-key', join(scratch, 'app.key'), ...upstreams) + session('--verify-assembled', assembly, '--route-inventory-out', inventory, '--checked-route', deployment.selected) + + const checked = JSON.parse(await readFile(inventory, 'utf8')) + const assemblyBytes = await readFile(assembly) + assert.equal(checked.gatewayDigest, 'sha256:' + createHash('sha256').update(assemblyBytes).digest('hex')) + const config = JSON.parse(assemblyBytes) + const [host] = config.static_resources.listeners[0].filter_chains[0].filters[0].typed_config.route_config.virtual_hosts + const routes = [] + assert.deepEqual(checked.modules.map(module => module.id).sort(), Object.keys(deployment.upstreams).sort(), + 'Checked Session modules differ from the declared upstream browser contract.') + // The checked assembly supplies the mounts and rewrites. The upstream + // declarations supply the methods and path templates, including parameter names. + for (const module of checked.modules) { + const rewrite = envoyPrefixRewrite(host.routes, module) + for (const [method, paths] of Object.entries(deployment.upstreams[module.id])) { + for (const path of paths) { + assert(path.startsWith(rewrite), 'Upstream route ' + path + ' falls outside the rewrite ' + rewrite) + routes.push(route(method, module.prefix + path.slice(rewrite.length))) + } + } + } + return routes +} + +async function developmentRoutes(t, scratch, name) { + const project = join(examples, name) + const { preview } = parse(await readFile(join(project, 'dev.yaml'), 'utf8')) + const service = parse(await readFile(join(project, 'service.yaml'), 'utf8')) + const ids = Object.fromEntries(Object.entries(service.products).map(([kind, product]) => { + const members = product.projects ? Object.keys(product.projects) : [kind] + assert.equal(members.length, 1, 'Expected one preview member for ' + kind) + return [kind, members[0]] + })) + const artifact = { + preview, + product: { id: ids.breg }, + routeProducts: Object.entries(ids).map(([kind, id]) => ({ kind, id })), + } + + // The real rstack dev actor inputs are assembled during startup from product + // grants, credentials and reserved listeners. Use synthetic inputs here so + // the route check runs without a product or database startup. The probes + // cover declared routes across actors. Undeclared routes and per-actor + // authorization are outside this check's scope. + const observedTargets = [] + const upstream = createServer((request, response) => { + observedTargets.push(request.url) + response.writeHead(200, { + 'content-type': 'text/plain; charset=utf-8', + 'x-content-type-options': 'nosniff', + }).end('ok') + }) + upstream.listen(0, '127.0.0.1') + await once(upstream, 'listening') + t.after(() => { + upstream.close() + upstream.closeAllConnections() + }) + const origin = 'http://127.0.0.1:' + upstream.address().port + const authorizationFile = join(scratch, 'authorization') + await writeFile(authorizationFile, 'Authorization: Bearer synthetic\n') + const publicDirectory = join(scratch, 'public') + await mkdir(publicDirectory) + await writeFile(join(publicDirectory, preview.page === '/' ? 'index.html' : preview.page.slice(1)), 'Parity') + + const routes = [] + for (const [actor, products] of Object.entries(preview.actors ?? { [preview.actor]: { breg: preview.breg } })) { + const options = preview.actors ? actorGatewayOptions(artifact, [{ + name: actor, + port: 0, + products: Object.fromEntries(Object.entries(ids).map(([kind, id]) => [ + id, { baseUrl: origin, profile: kind === 'breg' ? actor : null, authorizationFile }, + ])), + }])[0] : { + port: 0, productId: ids.breg, profile: actor, breg: origin, authorization: async () => 'Bearer synthetic', + } + const gateway = await startPreviewGateway({ + ...options, application: origin, publicDirectory, preview, + }) + t.after(() => gateway.close()) + const headers = { origin: gateway.origin, 'registry-client': 'page' } + for (const local of ['/_rstack/ready', ...(preview.actors ? ['/_rstack/actor'] : [])]) { + const response = await fetch(gateway.origin + local, { headers }) + assert.equal(response.status, local.endsWith('/ready') ? 204 : 200, local) + await response.text() + routes.push(route('GET', local)) + } + const admitted = [] + for (const [kind, methods] of Object.entries(products)) { + for (const [method, paths] of Object.entries(methods)) { + for (const path of paths) { + admitted.push([route(method.toUpperCase(), '/registry/' + ids[kind] + path), path]) + } + } + } + if (!preview.actors || options.functionAuthorization) { + for (const name of preview.functions) admitted.push([route('POST', '/api/functions/' + name), '/functions/' + name]) + } + for (const [entry, upstreamPath] of admitted) { + const expand = path => path.replace(/\{([^{}]+)\}/gu, (_, name) => name === 'revision' ? '1' : sampleId) + const response = await fetch(gateway.origin + expand(entry.path), { method: entry.method, headers }) + const label = actor + ': ' + describeRoute(entry) + assert.equal(response.status, 200, label) + assert.equal(response.headers.get('content-type'), 'text/plain; charset=utf-8', label) + assert.equal(await response.text(), 'ok', label) + assert.equal(observedTargets.length, 1, label) + assert.equal(new URL(observedTargets.pop(), origin).pathname, expand(upstreamPath), label) + routes.push(entry) + } + } + const exceptions = new Map(developmentOnly) + if (!preview.actors) exceptions.delete('GET /_rstack/actor') + return { routes, exceptions } +} + +test('shipped development routes agree with their declared browser API contracts under checked Session prefixes', async t => { + const shipped = (await readdir(examples, { withFileTypes: true })).filter(entry => entry.isDirectory()).map(entry => entry.name).sort() + assert.deepEqual(Object.keys(deployments).sort(), shipped) + for (const name of shipped) { + await t.test(name, async t => { + const scratch = await mkdtemp(join(tmpdir(), 'registry-route-parity-')) + try { + const deployment = await deployedRoutes(scratch, deployments[name]) + const development = await developmentRoutes(t, scratch, name) + assertRouteParity(development.routes, deployment, development.exceptions) + } finally { + await rm(scratch, { recursive: true }) + } + }) + } +}) + +test('route parity rejects a seeded extra module in a checked Session inventory', async () => { + const deployment = structuredClone(deployments['medical-renewal']) + deployment.modules.push({ id: 'extra', product: 'breg', prefix: '/registry/extra/', rewrite: '/' }) + const scratch = await mkdtemp(join(tmpdir(), 'registry-route-parity-')) + try { + await assert.rejects(deployedRoutes(scratch, deployment), { + message: /Checked Session modules differ/u, + actual: ['extra', 'functions', 'licences'], + expected: ['functions', 'licences'], + }) + } finally { + await rm(scratch, { recursive: true }) + } +}) diff --git a/clients/typescript/tests/discovery.test.ts b/clients/typescript/tests/discovery.test.ts index e1339a0042..a368286732 100644 --- a/clients/typescript/tests/discovery.test.ts +++ b/clients/typescript/tests/discovery.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' import test from 'node:test' +import { readFileSync } from 'node:fs' import { RegistryError, Transport } from '../core.ts' import { Client } from '../generated/discovery.ts' @@ -86,3 +87,87 @@ test('Discovery accepts the fallback and compatible new problem types', async () await assert.rejects(client.call('getV1Services'), (error: unknown) => error instanceof RegistryError && error.kind === 'unexpected' && error.problem === undefined) }) + +test('Discovery classifies a problem by type, status and code, never by its prose', async () => { + const prefix = 'https://id.registrystack.org/problems/registry-discovery/' + const traceId = 'a'.repeat(32) + const problem: Record = { type: prefix + 'invalid-request', title: 'Reworded title', status: 400, + detail: 'Reworded guidance from a compatible server.', code: 'request.invalid', traceId } + const client = new Client(new Transport({ + baseUrl: 'https://directory.example', + fetch: async () => Response.json(problem, { status: problem.status as number, headers: { + 'content-type': 'application/problem+json', traceparent: '00-' + traceId + '-' + 'b'.repeat(16) + '-01', + } }), + })) + await assert.rejects(client.call('getV1Services'), (error: unknown) => + error instanceof RegistryError && error.kind === 'refused' && error.code === 'request.invalid') + problem.code = 'request.query-too-long' + await assert.rejects(client.call('getV1Services'), (error: unknown) => + error instanceof RegistryError && error.kind === 'refused' && error.code === 'request.query-too-long' + && error.problem?.type === prefix + 'invalid-request' && error.traceId === traceId) + for (const code of ['service.unavailable', 'Not A Code', 7]) { + problem.code = code + await assert.rejects(client.call('getV1Services'), (error: unknown) => + error instanceof RegistryError && error.kind === 'unexpected' && error.problem === undefined) + } + problem.type = prefix + 'future-limit' + problem.code = 'request.future-limit' + problem.title = 'x'.repeat(400) + await assert.rejects(client.call('getV1Services'), (error: unknown) => + error instanceof RegistryError && error.kind === 'refused' && error.code === 'request.future-limit' + && error.problem?.type === prefix + 'future-limit') +}) + +test('Discovery validates supplied codes on unrecognised problem types', async () => { + const type = 'https://id.registrystack.org/problems/registry-discovery/future-problem' + const problem: Record = { type, status: 409, title: 'Future problem' } + const client = new Client(new Transport({ + baseUrl: 'https://directory.example', + fetch: async () => Response.json(problem, { status: 409, headers: { + 'content-type': 'application/problem+json', + } }), + })) + + for (const code of ['', 'Request.future', 'request/future', 'request..future', + 'request.future--limit', 'request.future\n', 'x'.repeat(129), 7, null]) { + problem.code = code + await assert.rejects(client.call('getV1Services'), (error: unknown) => + error instanceof RegistryError && error.kind === 'unexpected' + && error.code === undefined && error.problem === undefined, JSON.stringify(code)) + } + for (const code of ['request.future-limit.v2', 'request.invalid', 'x'.repeat(128), undefined]) { + problem.code = code + await assert.rejects(client.call('getV1Services'), (error: unknown) => + error instanceof RegistryError && error.kind === 'refused' + && error.code === code && error.problem?.type === type, JSON.stringify(code)) + } +}) + +test('Discovery requires a string title but classifies a reworded Problem', async (t) => { + const fixtures = JSON.parse(readFileSync(new URL( + '../../../crates/registry-discovery-client/tests/fixtures/http-responses.json', import.meta.url, + ), 'utf8')) as Array<{ name: string; status: number; mediaType: string; body: string; traceparents?: string[]; resolve?: boolean }> + for (const fixture of fixtures.filter(({ name }) => [ + 'reworded-title', 'missing-title', 'mistyped-title', 'status-mismatch', + 'positional-search', 'positional-service', 'positional-resolution', 'positional-alternative', + 'missing-search-items', 'missing-service-id', 'missing-resolve-alternatives', + ].includes(name))) { + await t.test(fixture.name, async () => { + const headers = new Headers({ 'content-type': fixture.mediaType }) + for (const traceparent of fixture.traceparents ?? []) headers.append('traceparent', traceparent) + const client = new Client(new Transport({ + baseUrl: 'https://directory.example', + fetch: async () => new Response(fixture.body, { status: fixture.status, headers }), + })) + const result = fixture.resolve + ? client.call('postV1EvidenceTypesResolve', { body: { requirementId: 'urn:example:requirement' } }) + : client.call('getV1Services') + await assert.rejects(result, (error: unknown) => error instanceof RegistryError + && (fixture.name === 'reworded-title' + ? error.kind === 'refused' && error.code === 'request.invalid' + && error.problem?.title === undefined && error.problem?.detail === undefined && error.detail === undefined + && new TextDecoder().decode(error.raw) === fixture.body + : error.kind === 'unexpected' && error.problem === undefined)) + }) + } +}) diff --git a/clients/typescript/tests/generate-preview.test.ts b/clients/typescript/tests/generate-preview.test.ts index e9c19f0cc0..adc686c845 100644 --- a/clients/typescript/tests/generate-preview.test.ts +++ b/clients/typescript/tests/generate-preview.test.ts @@ -74,7 +74,7 @@ test('preview generation splits page and function bindings and keeps request cre 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])) +const { functionHostAuthorizer, startFunctionHost } = await import(pathToFileURL(process.argv[3])) globalThis.location = { origin: 'http://127.0.0.1:12345' } const calls = [] const networkFetch = globalThis.fetch @@ -153,7 +153,8 @@ const hostedHandler = defineFunction(async (request, licences) => { })({ 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, + authorize: request => request.headers.get('x-registry-preview-function') === functionKey && 'gateway', + coordinatorOnly: new Set(), }) try { const post = (profile, credential) => networkFetch(server.origin + '/functions/renew?profile=' + profile, { @@ -181,38 +182,72 @@ assert.deepEqual(calls.slice(3).map(([url, headers]) => { ['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. +// The same generated handler sees authenticated page and Coordinator callers. 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'), +const observed = [] +const sharedHandler = defineFunction(async (request, licences, caller) => { + observed.push([caller, request.headers.get('authorization'), request.headers.get('cookie'), request.headers.get('proxy-authorization'), request.headers.get('idempotency-key')]) + const list = () => licences.list('licence', { accessProfile: 'licence-officer' }) + if (caller === 'coordinator') { + await assert.rejects(list, /Coordinator.*registry authority/) + } else { + await list() + } + return new Response(null, { status: 204 }) +})({ products: { 'licence-registry': { baseUrl: 'http://127.0.0.1:54323' } } }) +const rejectRegistryCall = defineFunction(async (_request, licences) => { 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]]), { +const sharedHost = await startFunctionHost(new Map([['renew', sharedHandler], ['deny-registry', rejectRegistryCall]]), { authorize: functionHostAuthorizer(hostKey), + coordinatorOnly: new Set(), }) const before = calls.length try { - const response = await networkFetch(coordinatorHost.origin + '/functions/renew', { + const post = headers => networkFetch(sharedHost.origin + '/functions/renew', { method: 'POST', body: '{}', headers: { - authorization: 'Bearer ' + hostKey, 'content-type': 'application/json', 'idempotency-key': 'frozen-key', + 'content-type': 'application/json', 'idempotency-key': 'frozen-key', cookie: 'session=browser', 'proxy-authorization': 'Basic cHJveHk6cHJveHk=', + ...headers, }, }) - assert.equal(response.status, 204) + const coordinator = await post({ + authorization: 'Bearer ' + hostKey, 'x-registry-preview-caller-kind': 'page', + }) + assert.equal(coordinator.status, 204) + assert.equal(calls.length, before, 'Coordinator must refuse before network dispatch') + const page = await post({ + authorization: 'Bearer synthetic-page', 'x-registry-preview-function': hostKey, + 'x-registry-preview-caller-kind': 'coordinator', + }) + assert.equal(page.status, 204) + assert.equal(calls.length, before + 1) + assert.equal(calls[before][1].get('authorization'), 'Bearer synthetic-page') + const denied = await networkFetch(sharedHost.origin + '/functions/deny-registry', { + method: 'POST', headers: { authorization: 'Bearer ' + hostKey }, + }) + assert.equal(denied.status, 403) + assert.deepEqual(await denied.json(), { code: 'preview.coordinator-registry-authority-denied' }) + assert.equal(calls.length, before + 1) } finally { - await coordinatorHost.close() + await sharedHost.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.deepEqual(observed, [ + ['coordinator', null, null, null, 'frozen-key'], + ['page', null, null, null, 'frozen-key'], +]) + +// Exercise the generated binding independently of the host's bearer stripping. +const beforeDirect = calls.length +const refused = await rejectRegistryCall(new Request('http://127.0.0.1:54323/functions/renew', { + method: 'POST', headers: { authorization: 'Bearer unexpected-page-token' }, +}), 'coordinator') +assert.equal(calls.length, beforeDirect, 'an unexpected bearer must never authorize Coordinator dispatch') +assert.equal(refused.status, 403) +assert.deepEqual(await refused.json(), { code: 'preview.coordinator-registry-authority-denied' }) ` }) assert.equal(run.status, 0, run.stderr) }) diff --git a/clients/typescript/tests/holder-function-outcome.test.ts b/clients/typescript/tests/holder-function-outcome.test.ts new file mode 100644 index 0000000000..94e24b0db0 --- /dev/null +++ b/clients/typescript/tests/holder-function-outcome.test.ts @@ -0,0 +1,230 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { RegistryError } from '../core.ts' +import { createHolderActionHandler, type HolderOutcome } from '../holder-function.ts' + +// The outcome hook gives an operator the failure class and the attempt key of +// every answer, never a submitted value, a prepared value or the credential. +const route = '/api/functions/register-business' +const attemptId = '6c0e4c3d-1d0b-4c55-9d43-4ad2a3b3a1f7' +const credential = 'synthetic-registrar-credential' +const submission = { legalName: ' Harbour Bicycle Cooperative ', registrationNumber: 'br-2026-001' } +const recordId = '00000000-0000-4000-8000-000000000001' + +type Input = { legalName: string; registrationNumber: string } + +function exact(value: unknown): Input | undefined { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined + const { legalName, registrationNumber, ...rest } = value as Record + if (Object.keys(rest).length || typeof legalName !== 'string' || typeof registrationNumber !== 'string') return undefined + return { legalName, registrationNumber } +} + +function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string; signal?: AbortSignal } = {}) { + const { path = route, authorization = 'Bearer ' + credential, body = submission, key = attemptId.toUpperCase(), signal } = options + const headers = new Headers({ 'Content-Type': 'application/json', 'Idempotency-Key': key }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body), signal }) +} + +function setup({ + prepare = (value: Input) => ({ legalName: value.legalName.trim(), registrationNumber: value.registrationNumber.toUpperCase() }), + invoke = async () => ({ recordId, revision: 1 }), + preparationTimeoutMs = 1000, +}: { + prepare?: (value: Input, options: { signal: AbortSignal }) => unknown + invoke?: () => Promise<{ recordId: string; revision: number }> + preparationTimeoutMs?: number +} = {}) { + const outcomes: HolderOutcome[] = [] + const handle = createHolderActionHandler({ + kind: 'create', + path: route, + preparationTimeoutMs, + parseSubmission: value => { + const parsed = exact(value) + return parsed && { preparation: parsed } + }, + parsePreparation: exact, + invoke, + }, prepare, { onOutcome: outcome => { outcomes.push(outcome) } }) + return { handle, outcomes } +} + +function refusal(status: number, code: string) { + return new RegistryError({ kind: 'refused', reason: 'status', status, outcomeUnknown: false, problem: { code } }) +} + +test('a successful create reports its class, attempt key and status', async () => { + const { handle, outcomes } = setup() + assert.equal((await handle(request())).status, 200) + assert.deepEqual(outcomes, [{ class: 'succeeded', attemptKey: attemptId, status: 200 }]) +}) + +test('each refusal before preparation reports its class', async () => { + for (const [label, options, expected] of [ + ['unknown route', { path: '/api/functions/other' }, { class: 'request-refused', attemptKey: undefined, status: 404 }], + ['no bearer', { authorization: null }, { class: 'unauthenticated', attemptKey: undefined, status: 401 }], + ['bad attempt key', { key: 'not-a-key' }, { class: 'request-refused', attemptKey: undefined, status: 400 }], + ['undeclared submission', { body: { legalName: 'x' } }, { class: 'request-refused', attemptKey: attemptId, status: 400 }], + ] as const) { + await test(label, async () => { + const { handle, outcomes } = setup() + const response = await handle(request(options)) + assert.equal(response.status, expected.status) + assert.deepEqual(outcomes, [expected]) + }) + } +}) + +test('a preparation failure, refusal, deadline and cancellation are told apart', async () => { + const thrown = setup({ prepare: () => { throw new Error('synthetic function failure') } }) + assert.equal((await thrown.handle(request())).status, 502) + assert.deepEqual(thrown.outcomes, [{ class: 'preparation-failed', attemptKey: attemptId, status: 502 }]) + + const projected = setup({ prepare: () => ({ owner: 'someone-else' }) }) + assert.equal((await projected.handle(request())).status, 502) + assert.deepEqual(projected.outcomes, [{ class: 'preparation-refused', attemptKey: attemptId, status: 502 }]) + + const late = setup({ preparationTimeoutMs: 20, prepare: () => new Promise(() => {}) }) + assert.equal((await late.handle(request())).status, 502) + assert.deepEqual(late.outcomes, [{ class: 'preparation-deadline', attemptKey: attemptId, status: 502 }]) + + const controller = new AbortController() + const cancelled = setup({ prepare: () => { controller.abort(); return new Promise(() => {}) } }) + assert.equal((await cancelled.handle(request({ signal: controller.signal }))).status, 502) + assert.deepEqual(cancelled.outcomes, [{ class: 'cancelled', attemptKey: attemptId, status: 502 }]) +}) + +test('a product refusal and an unresolved answer report their class and status', async () => { + const refused = setup({ invoke: () => Promise.reject(refusal(412, 'precondition.failed')) }) + assert.equal((await refused.handle(request())).status, 412) + assert.deepEqual(refused.outcomes, [{ class: 'product-refused', attemptKey: attemptId, status: 412 }]) + + const lost = setup({ invoke: () => Promise.reject(new Error('synthetic lost receipt')) }) + assert.equal((await lost.handle(request())).status, 502) + assert.deepEqual(lost.outcomes, [{ class: 'unresolved', attemptKey: attemptId, status: 502 }]) + + const spent = setup({ invoke: () => Promise.reject(refusal(409, 'idempotency.key-reused')) }) + assert.equal((await spent.handle(request())).status, 409) + assert.deepEqual(spent.outcomes, [{ class: 'unresolved', attemptKey: attemptId, status: 409 }]) +}) + +test('an outcome never carries a submitted or prepared value or the credential', async () => { + const outcomes: HolderOutcome[] = [] + for (const options of [ + {}, + { prepare: () => { throw new Error(submission.legalName) } }, + { invoke: () => Promise.reject(new Error(credential)) }, + ]) { + const run = setup(options) + await run.handle(request()) + outcomes.push(...run.outcomes) + } + const recorded = JSON.stringify(outcomes) + for (const value of [credential, submission.legalName.trim(), submission.registrationNumber, 'BR-2026-001', recordId]) { + assert.ok(!recorded.includes(value), value) + } + for (const outcome of outcomes) { + assert.deepEqual(Object.keys(outcome).sort(), ['attemptKey', 'class', 'status']) + } +}) + +test('a failing outcome hook leaves the answer unchanged and is logged', async t => { + const logged = t.mock.method(console, 'error', () => {}) + const handle = createHolderActionHandler({ + kind: 'create', + path: route, + preparationTimeoutMs: 1000, + parseSubmission: value => { + const parsed = exact(value) + return parsed && { preparation: parsed } + }, + parsePreparation: exact, + invoke: async () => ({ recordId, revision: 1 }), + }, value => value, { onOutcome: () => { throw new Error('synthetic hook failure') } }) + const response = await handle(request()) + assert.equal(response.status, 200) + assert.deepEqual(await response.json(), { recordId }) + assert.equal(logged.mock.callCount(), 1) + assert.deepEqual(logged.mock.calls[0]?.arguments, ['The holder outcome hook failed.']) +}) + +test('an async outcome hook that rejects leaves the answer unchanged and is logged', async t => { + const logged = t.mock.method(console, 'error', () => {}) + const unhandled: unknown[] = [] + const listener = (reason: unknown) => { unhandled.push(reason) } + process.on('unhandledRejection', listener) + t.after(() => { process.off('unhandledRejection', listener) }) + const handle = createHolderActionHandler({ + kind: 'create', + path: route, + preparationTimeoutMs: 1000, + parseSubmission: value => { + const parsed = exact(value) + return parsed && { preparation: parsed } + }, + parsePreparation: exact, + invoke: async () => ({ recordId, revision: 1 }), + }, value => value, { onOutcome: async () => { throw new Error('synthetic async hook failure') } }) + const response = await handle(request()) + assert.equal(response.status, 200) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(unhandled, []) + assert.equal(logged.mock.callCount(), 1) + assert.deepEqual(logged.mock.calls[0]?.arguments, ['The holder outcome hook failed.']) +}) + +test('a target binding reports its classes', async () => { + const licenceId = '00000000-0000-4000-8000-000000000002' + type Renewal = { newExpiresOn: string } + const renewal = (value: unknown): Renewal | undefined => { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined + const { newExpiresOn, ...rest } = value as Record + return Object.keys(rest).length || typeof newExpiresOn !== 'string' ? undefined : { newExpiresOn } + } + const run = async (body: unknown, invoke: () => Promise<{ recordId: string }>) => { + const outcomes: HolderOutcome[] = [] + const handle = createHolderActionHandler({ + kind: 'target', + path: route, + preparationTimeoutMs: 1000, + parseSubmission: value => { + if (value === null || typeof value !== 'object') return undefined + const { recordId: id, ifMatch, preparation } = value as Record + const parsed = renewal(preparation) + return typeof id === 'string' && typeof ifMatch === 'string' && parsed + ? { recordId: id, ifMatch, preparation: parsed } : undefined + }, + parsePreparation: renewal, + invoke, + }, value => value, { onOutcome: outcome => { outcomes.push(outcome) } }) + const response = await handle(request({ body })) + return { status: response.status, outcomes } + } + const submission = { recordId: licenceId, ifMatch: '"r1"', preparation: { newExpiresOn: '2027-01-01' } } + assert.deepEqual(await run(submission, async () => ({ recordId: licenceId })), + { status: 200, outcomes: [{ class: 'succeeded', attemptKey: attemptId, status: 200 }] }) + assert.deepEqual(await run({ ...submission, ifMatch: 'weak' }, async () => ({ recordId: licenceId })), + { status: 400, outcomes: [{ class: 'request-refused', attemptKey: attemptId, status: 400 }] }) + assert.deepEqual(await run(submission, () => Promise.reject(refusal(412, 'precondition.failed'))), + { status: 412, outcomes: [{ class: 'product-refused', attemptKey: attemptId, status: 412 }] }) + assert.deepEqual(await run(submission, async () => ({ recordId })), + { status: 502, outcomes: [{ class: 'unresolved', attemptKey: attemptId, status: 502 }] }) +}) + +test('the outcome option is optional and checked', () => { + const binding = { + kind: 'create' as const, + path: route, + preparationTimeoutMs: 1000, + parseSubmission: () => undefined, + parsePreparation: exact, + invoke: async () => ({ recordId, revision: 1 }), + } + assert.equal(typeof createHolderActionHandler(binding, value => value), 'function') + assert.throws( + () => createHolderActionHandler(binding, value => value, { onOutcome: 'log' as never }), + /outcome hook/, + ) +}) diff --git a/clients/typescript/tests/live-plan.test.ts b/clients/typescript/tests/live-plan.test.ts new file mode 100644 index 0000000000..6df574b628 --- /dev/null +++ b/clients/typescript/tests/live-plan.test.ts @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { Ajv2020 } from 'ajv/dist/2020.js' +import { stageMainPlan } from './live/harness.ts' + +type ProjectPath = { path: string } +type ServiceProject = ProjectPath | { projects: Record } + +test('the live service project stages one authored inventory with matching audiences', t => { + const root = mkdtempSync(join(tmpdir(), 'rstack-ts-plan-test-')) + t.after(() => rmSync(root, { recursive: true, force: true })) + const project = stageMainPlan(root, 'http://127.0.0.1:8081') + const ajv = new Ajv2020({ strictSchema: false, validateFormats: false }) + + function readCheckedConfig(name: 'dev' | 'service'): T { + const schema = new URL(`../../../products/platform/generated/dev/${name}.v1alpha1.schema.json`, import.meta.url) + const validate = ajv.compile(JSON.parse(readFileSync(schema, 'utf8'))) + const config: unknown = JSON.parse(readFileSync(join(project, `${name}.yaml`), 'utf8')) + assert.ok(validate(config), `${name}.yaml: ${ajv.errorsText(validate.errors)}`) + return config + } + + const dev = readCheckedConfig<{ audiences: Record }>('dev') + const service = readCheckedConfig<{ products: Record }>('service') + assert.equal(Object.hasOwn(dev, 'products'), false) + + const products = ['adapter', 'breg', 'casework', 'coordinator', 'discovery', 'documents', 'messaging', 'render', 'scheduling'] + assert.deepEqual(Object.keys(service.products).sort(), products) + assert.deepEqual(Object.keys(dev.audiences).sort(), products) + assert.equal(new Set(Object.values(dev.audiences)).size, products.length) + for (const product of products) { + const entry = service.products[product] + assert.ok(entry) + const reference = 'projects' in entry ? entry.projects[product] : entry + assert.equal(reference?.path, product) + assert.ok(statSync(join(project, product)).isDirectory()) + } +}) diff --git a/clients/typescript/tests/live/harness.ts b/clients/typescript/tests/live/harness.ts index 0386db3d99..8ace60a5d8 100644 --- a/clients/typescript/tests/live/harness.ts +++ b/clients/typescript/tests/live/harness.ts @@ -840,7 +840,7 @@ async function mintRstackTokens( return tokens } -function stageMainPlan(root: string, dhis2Origin: string): string { +export function stageMainPlan(root: string, dhis2Origin: string): string { const planDir = join(root, 'plan-main') mkdirSync(planDir, { recursive: true }) @@ -883,11 +883,22 @@ function stageMainPlan(root: string, dhis2Origin: string): string { '', ].join('\n')) - // People name roles, and the sibling service.yaml declares each role once. + // The service declares the project inventory and each role once. // The run derives scopes and purposes from the selected profiles. - const serviceRoles = { + const service = { apiVersion: 'id.registrystack.org/formats/rstack/service/v1alpha1', kind: 'RStackService', + products: { + breg: { projects: { breg: { path: 'breg' } } }, + casework: { path: 'casework' }, + coordinator: { projects: { coordinator: { path: 'coordinator' } } }, + documents: { path: 'documents' }, + messaging: { path: 'messaging' }, + scheduling: { path: 'scheduling' }, + render: { path: 'render' }, + discovery: { path: 'discovery' }, + adapter: { path: 'adapter' }, + }, roles: { 'directory-editor': { actorKind: 'human', claims: ['jurisdiction'], accessProfiles: { breg: ['directory-editor'] } }, 'casework-administrator': { actorKind: 'human', accessProfiles: { casework: ['administrator'] } }, @@ -911,17 +922,17 @@ function stageMainPlan(root: string, dhis2Origin: string): string { apiVersion: 'id.registrystack.org/formats/rstack/dev/v1alpha1', kind: 'RStackDev', issuer: 'https://identity.standalone.example.test', - products: [ - { product: 'breg', project: 'breg', audience: 'urn:example:local-directory' }, - { product: 'casework', project: 'casework', audience: 'urn:example:standalone-decision' }, - { product: 'coordinator', project: 'coordinator', audience: 'urn:example:coordinator' }, - { product: 'documents', project: 'documents', audience: 'urn:example:documents' }, - { product: 'messaging', project: 'messaging', audience: 'urn:example:messaging' }, - { product: 'scheduling', project: 'scheduling', audience: 'urn:example:scheduling' }, - { product: 'render', project: 'render', audience: 'urn:example:render' }, - { product: 'discovery', project: 'discovery', audience: 'urn:example:discovery' }, - { product: 'adapter', project: 'adapter', audience: 'urn:example:adapter' }, - ], + audiences: { + breg: 'urn:example:local-directory', + casework: 'urn:example:standalone-decision', + coordinator: 'urn:example:coordinator', + documents: 'urn:example:documents', + messaging: 'urn:example:messaging', + scheduling: 'urn:example:scheduling', + render: 'urn:example:render', + discovery: 'urn:example:discovery', + adapter: 'urn:example:adapter', + }, people: { editor: { subject: 'synthetic-directory-editor', @@ -1024,7 +1035,7 @@ function stageMainPlan(root: string, dhis2Origin: string): string { } writeFileSync(join(planDir, 'dev.yaml'), JSON.stringify(devPlan, null, 2) + '\n') - writeFileSync(join(planDir, 'service.yaml'), JSON.stringify(serviceRoles, null, 2) + '\n') + writeFileSync(join(planDir, 'service.yaml'), JSON.stringify(service, null, 2) + '\n') writeFileSync(join(planDir, 'dev-journeys.yaml'), JSON.stringify({ apiVersion: 'id.registrystack.org/formats/rstack/journeys/v1alpha1', kind: 'RStackJourneys', @@ -1395,6 +1406,7 @@ export async function startLiveEnvironment(options: StartLiveEnvironmentOptions 'personAudience: urn:example:local-directory', 'modules:', ' - id: breg', + ' product: breg', ' prefix: /api/breg/', ' audience: person', ' signIns: [staff]', diff --git a/crates/registry-adapter-core/src/runtime.rs b/crates/registry-adapter-core/src/runtime.rs index 2d1b7c1cb0..ce0584b4fa 100644 --- a/crates/registry-adapter-core/src/runtime.rs +++ b/crates/registry-adapter-core/src/runtime.rs @@ -597,7 +597,7 @@ pub fn record_endpoint_posture( static ANONYMOUS_HTTPS: ExplicitProductionSetting = ExplicitProductionSetting { code: "adapter.posture.anonymous-https", key: "anonymousHttps", - summary: "a fixed HTTPS source is reached without an application credential", + summary: "A fixed HTTPS source is reached without an application credential", }; for (index, endpoint) in endpoints.iter().enumerate() { if endpoint.anonymous_https.is_some() { diff --git a/crates/registry-adapter-engine/src/job_sources.rs b/crates/registry-adapter-engine/src/job_sources.rs index 15378b0fcd..42bd6a82dc 100644 --- a/crates/registry-adapter-engine/src/job_sources.rs +++ b/crates/registry-adapter-engine/src/job_sources.rs @@ -863,6 +863,7 @@ pub fn job_store_transport_diagnostic( ) -> (&'static str, &'static str) { use registry_platform_config::{DatabaseTransport, DatabaseTransportError}; match error { + DatabaseTransportError::Url(..) => (error.message(), error.suggested_action()), DatabaseTransportError::Conflict => ( "store.transport and store.testOnlyPlaintext are both set", "Remove store.testOnlyPlaintext, and keep store.transport.", diff --git a/crates/registry-adapter-engine/src/load.rs b/crates/registry-adapter-engine/src/load.rs index 1cee780125..94af5390e4 100644 --- a/crates/registry-adapter-engine/src/load.rs +++ b/crates/registry-adapter-engine/src/load.rs @@ -518,7 +518,7 @@ fn secret_refusal_fix(error: &SecretError) -> &'static str { } SecretError::UnsafeFile(check) => check.suggested_action(), SecretError::UnsafePublicDocument(check) => check.public_suggested_action(), - SecretError::PrivateKeyInPublicDocument | SecretError::PublicDocumentNotText => { + SecretError::PrivateKeyInPublicDocument => { error.suggested_action() } SecretError::Read => "check that the service user can read the secret file", diff --git a/crates/registry-adapter-job/src/hook_ingress.rs b/crates/registry-adapter-job/src/hook_ingress.rs index 009394178a..22b6849e76 100644 --- a/crates/registry-adapter-job/src/hook_ingress.rs +++ b/crates/registry-adapter-job/src/hook_ingress.rs @@ -437,9 +437,7 @@ 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::PrivateKeyInPublicDocument => 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 be28eed68e..d2ce8e4c5b 100644 --- a/crates/registry-adapter-job/src/runtime_destination.rs +++ b/crates/registry-adapter-job/src/runtime_destination.rs @@ -25,8 +25,8 @@ use registry_platform_crypto::delivery_signature::DeliveryKeys; 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}, + destination::{DestinationPolicyError, EventDestinationPolicy}, + select::{select_destination, DestinationSelectionError, TransportClass}, }; #[cfg(feature = "signed-coordinator-event")] use registry_platform_yaml::ExternalId; @@ -265,11 +265,65 @@ fn parse_runtime_bindings( if text.starts_with("missing field ") { format!("the runtime destinations block was refused: {text}") } else { - "the runtime destinations block was refused".to_string() + signed_destination_url_refusal(bindings) + .unwrap_or_else(|| "the runtime destinations block was refused".to_string()) } }) } +// The shared URL type rejects invalid URLs before transport selection can +// explain the rule. Diagnose only refused signed-event URLs here. +fn signed_destination_url_refusal(bindings: &serde_json::Value) -> Option { + bindings.as_object()?.iter().find_map(|(id, entry)| { + if entry.get("type")?.as_str()? != "signed-coordinator-event" { + return None; + } + let binding = LocalId::new(id).ok()?; + let url = entry.get("baseUrl")?.as_str()?; + if Url::new(url).is_ok() { + return None; + } + if url.split_once(':').is_some_and(|(scheme, _)| { + scheme.starts_with(|character: char| character.is_ascii_alphabetic()) + && scheme.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.') + }) + && !scheme.eq_ignore_ascii_case("https") + && !scheme.eq_ignore_ascii_case("http") + }) { + return Some(signed_origin_scheme_refusal(&binding)); + } + Some(signed_destination_refusal( + "origin", + &format!("/destinations/{binding}/baseUrl"), + "the signed-event destination URL is invalid", + "Use an HTTPS origin or an explicit loopback HTTP origin with a valid host and port. Remove any user information.", + )) + }) +} + +fn signed_destination_refusal(rule: &str, pointer: &str, reason: &str, remedy: &str) -> String { + registry_platform_yaml::Diagnostic::error( + format!("adapter.job.destination-{rule}"), + pointer, + format!( + "{}: {reason}", + registry_adapter_core::ADAPTER_JOB_RUNTIME_KIND + ), + remedy, + ) + .render_human() +} + +fn signed_origin_scheme_refusal(binding: &LocalId) -> String { + signed_destination_refusal( + "origin-scheme", + &format!("/destinations/{binding}/baseUrl"), + "signed-event destinations require HTTPS or explicit loopback HTTP", + "Use HTTPS for the destination or use HTTP with an explicit loopback host.", + ) +} + fn missing_binding(binding: &LocalId) -> String { format!( "the job's destination binding `{binding}` is not in the runtime `destinations` block; add `destinations.{binding}` or change the job's `destination.binding`" @@ -585,11 +639,22 @@ fn signed_destination_policy( core: &AdapterEndpointBindings, configured_tls: bool, ) -> Result { - let refused = "the signed-event destination policy was refused"; + let pointer = format!("/destinations/{binding}/baseUrl"); // 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())?; + select_destination(&base_url.to_url(), None, &[]).map_err(|error| match error { + DestinationSelectionError::UnsupportedScheme + | DestinationSelectionError::PrivateNetworkNotDeclared => { + signed_origin_scheme_refusal(binding) + } + _ => signed_destination_refusal( + "origin", + &pointer, + &error.to_string(), + "Use an HTTPS origin or an explicit loopback HTTP origin without user information.", + ), + })?; let private_cidrs = core .allowed_private_cidrs .iter() @@ -603,9 +668,58 @@ fn signed_destination_policy( selected.profile(), &private_cidrs, ) - .map_err(|_| refused.to_owned())?; + .map_err(|error| { + if error == DestinationPolicyError::InvalidOriginId { + return signed_destination_refusal( + "origin-id", + &format!("/destinations/{binding}"), + &error.to_string(), + "Use a binding key ending in a letter or digit and update destination.binding in the job.", + ); + } + let (rule, path, remedy) = match error { + DestinationPolicyError::OriginHasResourceComponents => ( + "origin-path", + pointer.as_str(), + "Drop the path, query and fragment. Keep only the origin.", + ), + DestinationPolicyError::PrivateCidrDenied + | DestinationPolicyError::PrivateCidrNotCanonical + | DestinationPolicyError::TooManyPrivateCidrs => ( + "private-range", + "/allowedPrivateCidrs", + "Remove ineligible ranges and use only eligible, canonical private networks, with at most 16 entries.", + ), + DestinationPolicyError::LocalhostNamespaceDenied => ( + "private-range", + pointer.as_str(), + "Use a public or explicitly allowed private HTTPS origin. Use HTTP for an explicit loopback host.", + ), + DestinationPolicyError::ProductionRequiresHttps + | DestinationPolicyError::DevelopmentRequiresHttp + | DestinationPolicyError::DevelopmentRequiresLoopbackHost => { + return signed_origin_scheme_refusal(binding); + } + DestinationPolicyError::OriginUrlTooLong => ( + "origin", + pointer.as_str(), + "Shorten the origin URL to at most 2048 bytes.", + ), + _ => ( + "origin", + pointer.as_str(), + "Use an HTTPS origin or an explicit loopback HTTP origin with a valid host and nonzero port.", + ), + }; + signed_destination_refusal(rule, path, &error.to_string(), remedy) + })?; if configured_tls && selected.transport() != TransportClass::VerifiedTls { - return Err("the signed-event destination TLS material was refused".to_owned()); + return Err(signed_destination_refusal( + "tls-transport", + &format!("/destinations/{binding}/tlsTrustProfile"), + "a signed-event TLS trust profile requires verified HTTPS", + "Use HTTPS for the destination. For a loopback HTTP receiver, remove tlsTrustProfile.", + )); } Ok(policy) } @@ -1014,6 +1128,54 @@ mod tests { } } + #[test] + fn signed_destination_url_parse_refusals_are_value_free() { + for (url, rule, remedy) in [ + ("ftp://origin-canary.invalid", "origin-scheme", "Use HTTPS"), + ( + "https://userinfo-canary@origin-canary.invalid", + "origin", + "Remove any user information", + ), + ] { + let bindings = serde_json::json!({ + "coordinator-test": { + "type": "signed-coordinator-event", + "baseUrl": url, + "hmacSha256KeyRef": "secret:file/key-canary", + "attemptTimeoutMilliseconds": 1000, + } + }); + let refusal = parse_runtime_bindings(&bindings).unwrap_err(); + assert!(refusal.contains(&format!("error[adapter.job.destination-{rule}]"))); + assert!(refusal.contains("/destinations/coordinator-test/baseUrl")); + assert!(refusal.contains("AdapterJobRuntimeConfig")); + assert!(refusal.contains(remedy)); + for canary in ["origin-canary", "userinfo-canary", "key-canary"] { + assert!(!refusal.contains(canary)); + } + } + } + + #[cfg(feature = "signed-coordinator-event")] + #[test] + fn signed_destination_origin_id_refusal_names_the_binding_key() { + let binding = LocalId::new("coordinator-").unwrap(); + let base_url = Url::new("https://origin-canary.invalid").unwrap(); + let core = serde_json::from_value(serde_json::json!({ + "id": "test-runtime", + "endpoints": [], + })) + .unwrap(); + let Err(refusal) = signed_destination_policy(&binding, &base_url, &core, false) else { + panic!("the origin id policy refuses a trailing separator"); + }; + assert!(refusal.contains("error[adapter.job.destination-origin-id]")); + assert!(refusal.contains("/destinations/coordinator-")); + assert!(refusal.contains("update destination.binding")); + assert!(!refusal.contains("origin-canary")); + } + #[cfg(feature = "signed-coordinator-event")] #[tokio::test] async fn duplicate_keys_refuse_every_job_using_the_runtime() { diff --git a/crates/registry-adapter-job/src/store.rs b/crates/registry-adapter-job/src/store.rs index 2c51791e9c..2fad44e59f 100644 --- a/crates/registry-adapter-job/src/store.rs +++ b/crates/registry-adapter-job/src/store.rs @@ -10,7 +10,6 @@ use std::collections::BTreeMap; use std::fmt; -use std::str::FromStr as _; use std::time::{Duration, SystemTime}; use deadpool_postgres::{ @@ -582,7 +581,7 @@ pub fn build_pool_in_posture( config, resolver, development, - "runtimeUrlRef", + registry_platform_config::DatabaseMember::RuntimeUrl, config.runtime_url_ref.as_str(), ) } @@ -597,7 +596,7 @@ pub fn build_migration_pool( config, resolver, development, - "migrationUrlRef", + registry_platform_config::DatabaseMember::MigrationUrl, reference.as_str(), ), None => build_pool_in_posture(config, resolver, development), @@ -608,7 +607,7 @@ fn build_pool_for( config: &JobStoreConfig, resolver: &SecretResolver, development: Option<®istry_platform_config::DevelopmentWitness>, - member: &str, + member: registry_platform_config::DatabaseMember, reference: &str, ) -> Result { let invalid = |what: &str| StoreError::Pool(format!("store: {what}")); @@ -618,7 +617,7 @@ fn build_pool_for( .map_err(job_store_transport_error)?; let protected = resolver .resolve(reference) - .map_err(|error| store_secret_error(member, reference, &error))?; + .map_err(|error| store_secret_error(member.key(), reference, &error))?; let url = std::str::from_utf8(protected.expose_secret()).map_err(|_| { StoreError::Pool(format!( "store.{member}: put a PostgreSQL URL in the secret" @@ -628,6 +627,7 @@ fn build_pool_for( config, url, development, + member, ®istry_platform_config::resolve_database_host, )?; let pool = if verified_tls { @@ -662,8 +662,11 @@ fn job_store_transport_error( } _ => message.to_owned(), }; + let field = error + .url_member() + .map_or_else(|| "store".to_owned(), |member| format!("store.{member}")); StoreError::Pool(format!( - "store: {}: {message}; next: {action}", + "{field}: {}: {message}; next: {action}", error.code() )) } @@ -676,21 +679,19 @@ fn driver_config( config: &JobStoreConfig, url: &str, development: Option<®istry_platform_config::DevelopmentWitness>, + member: registry_platform_config::DatabaseMember, resolve: ®istry_platform_config::HostResolver, ) -> Result<(tokio_postgres::Config, bool), StoreError> { let invalid = |what: &str| StoreError::Pool(format!("store: {what}")); - let postgres = tokio_postgres::Config::from_str(url) - .map_err(|_| invalid("the connection url is invalid"))?; + let database = config.database_config(); + let postgres = registry_platform_postgres::parse_runtime_url(url, &database, development) + .map_err(|error| job_store_transport_error(error.at_url(member)))?; if postgres.get_user().is_none() || postgres.get_dbname().is_none() { return Err(invalid("the connection url names no user or database")); } - let (transport, mut postgres) = registry_platform_postgres::postgres_connection( - &config.database_config(), - postgres, - development, - resolve, - ) - .map_err(job_store_transport_error)?; + let (transport, mut postgres) = + registry_platform_postgres::postgres_connection(&database, postgres, development, resolve) + .map_err(job_store_transport_error)?; let verified_tls = !config.test_only_plaintext && transport == registry_platform_config::DatabaseTransport::VerifiedTls; postgres.ssl_mode(if verified_tls { @@ -779,25 +780,20 @@ pub(crate) fn postgres_tls_from_native_and_pem( pem: &[u8], ) -> Result { let mut roots = native_postgres_root_store()?; - if add_pem_roots(&mut roots, pem)? == 0 { - return Err(()); - } + add_pem_roots(&mut roots, pem)?; postgres_tls_from_root_store(roots) } fn postgres_root_store_from_pem(pem: &[u8]) -> Result { - let mut roots = rustls::RootCertStore::empty(); - let _ = add_pem_roots(&mut roots, pem)?; - Ok(roots) + registry_platform_postgres::pem_root_store(pem).map_err(|_| ()) } +/// Add a bundle's roots, each already checked usable, and count them. +#[cfg(feature = "job-postgres")] fn add_pem_roots(roots: &mut rustls::RootCertStore, pem: &[u8]) -> Result { - use rustls::pki_types::pem::PemObject as _; - let mut count = 0_usize; - for certificate in rustls::pki_types::CertificateDer::pem_slice_iter(pem) { - roots.add(certificate.map_err(|_| ())?).map_err(|_| ())?; - count += 1; - } + let certificates = registry_platform_postgres::pem_roots(pem).map_err(|_| ())?; + let count = certificates.len(); + roots.add_parsable_certificates(certificates); Ok(count) } @@ -2312,6 +2308,27 @@ mod storage_time_tests { mod driver_config_tests { use super::*; + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config: JobStoreConfig = serde_json::from_value(serde_json::json!({ + "runtimeUrlRef": "secret:env/JOB_STORE_URL", + })) + .unwrap(); + let (postgres, tls) = driver_config( + &config, + "postgresql://app@db.example/registry?sslmode=verify-full", + None, + registry_platform_config::DatabaseMember::RuntimeUrl, + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert!(tls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping @@ -2332,6 +2349,7 @@ mod driver_config_tests { &config, "postgresql://app@localhost:5433/adapter_job", None, + registry_platform_config::DatabaseMember::RuntimeUrl, &fixed, ) .unwrap(); 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 45e2054b43..d972c820f8 100644 --- a/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs +++ b/crates/registry-adapter-job/tests/signed_coordinator_event_postgres.rs @@ -313,50 +313,100 @@ async fn signed_destination_refuses_invalid_transports_and_origins_before_keys() .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 [ + let origin_pointer = "/destinations/coordinator-test/baseUrl"; + for (base_url, tls_profile, cidr, rule, pointer, remedy) in [ // The job fixture intentionally lists a CIDR covering this address. ( "http://192.168.10.8:41001/".to_owned(), None, - policy_refused, + None, + "origin-scheme", + origin_pointer, + "Use HTTPS", + ), + ( + format!("http://{address}/path-canary?query-canary#fragment-canary"), + None, + None, + "origin-path", + origin_pointer, + "Drop the path, query and fragment", + ), + ( + "https://localhost:41001/".to_owned(), + None, + None, + "private-range", + origin_pointer, + "Use a public or explicitly allowed private HTTPS origin", ), ( - format!("http://{address}/?resource=unexpected"), + "https://origin-canary.invalid".to_owned(), None, - policy_refused, + Some("127.0.0.0/8"), + "private-range", + "/allowedPrivateCidrs", + "Remove ineligible ranges", ), - ("https://localhost:41001/".to_owned(), None, policy_refused), ( format!("http://{address}/"), - Some("private-ca"), - "the signed-event destination TLS material was refused", + Some("profile-canary"), + None, + "tls-transport", + "/destinations/coordinator-test/tlsTrustProfile", + "remove tlsTrustProfile", + ), + ( + "ftp://origin-canary.invalid".to_owned(), + None, + None, + "origin-scheme", + origin_pointer, + "Use HTTPS", ), ] { document["destinations"] = json!({ "coordinator-test": { "type": "signed-coordinator-event", "baseUrl": base_url, - "hmacSha256KeyRef": "secret:file/missing-key", - "attemptTimeoutMilliseconds": 2000 + "hmacSha256KeyRef": "secret:file/key-canary", + "attemptTimeoutMilliseconds": 2000, } }); - if let Some(profile) = tls_trust_profile { + if let Some(profile) = tls_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 + let mut runtime = JobRuntimeConfig::load(&fixture.runtime).unwrap(); + if let Some(cidr) = cidr { + runtime.core.allowed_private_cidrs = serde_json::from_value(json!([cidr])).unwrap(); + } + let check = check_destination_runtime(&program.job, &runtime).unwrap_err(); + assert!( + check.contains(&format!("error[adapter.job.destination-{rule}]")), + "{check}" ); + assert!(check.contains(pointer), "{check}"); + assert!(check.contains(remedy), "{check}"); + assert!(!check.contains(&base_url)); + for canary in [ + "origin-canary", + "path-canary", + "query-canary", + "fragment-canary", + "127.0.0.0/8", + "profile-canary", + "key-canary", + ] { + assert!(!check.contains(canary)); + } assert_eq!( activate_destination(&program, &runtime, &resolver) .await .err() .as_deref(), - Some(expected) + Some(check.as_str()) ); } assert!( diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index f8dc460e39..b816540f9e 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -6,7 +6,6 @@ use std::collections::HashMap; use std::net::SocketAddr; -use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, SystemTime}; @@ -335,8 +334,11 @@ pub(crate) fn check_database(config: &DatabaseConfig) -> Result<(), ServeError> } fn database_transport_error(error: registry_platform_config::DatabaseTransportError) -> ServeError { + let field = error + .url_member() + .map_or("database", |_| error.database_field()); ServeError::Configuration(format!( - "database: {}: {error}; next: {}", + "{field}: {}: {error}; next: {}", error.code(), error.suggested_action() )) @@ -350,10 +352,16 @@ pub(crate) fn pool( ) -> Result { let invalid = |what: &str| ServeError::Configuration(format!("database: {what}")); check_database(config)?; - let reference = if migration { - &config.migration_url_ref + let (reference, member) = if migration { + ( + &config.migration_url_ref, + registry_platform_config::DatabaseMember::MigrationUrl, + ) } else { - &config.runtime_url_ref + ( + &config.runtime_url_ref, + registry_platform_config::DatabaseMember::RuntimeUrl, + ) }; let protected = resolver .resolve(reference) @@ -364,6 +372,7 @@ pub(crate) fn pool( config, url, development, + member, ®istry_platform_config::resolve_database_host, )?; let manager_config = ManagerConfig { @@ -392,10 +401,12 @@ fn driver_config( config: &DatabaseConfig, url: &str, development: Option<®istry_platform_config::DevelopmentWitness>, + member: registry_platform_config::DatabaseMember, resolve: ®istry_platform_config::HostResolver, ) -> Result<(PgConfig, bool), ServeError> { let invalid = |what: &str| ServeError::Configuration(format!("database: {what}")); - let postgres = PgConfig::from_str(url).map_err(|_| invalid("the connection url is invalid"))?; + let postgres = registry_platform_postgres::parse_runtime_url(url, config, development) + .map_err(|error| database_transport_error(error.at_url(member)))?; if postgres.get_user().is_none() || postgres.get_dbname().is_none() { return Err(invalid("the connection url names no user or database")); } @@ -427,20 +438,8 @@ fn tls_connector( let certificate = resolver .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 _; - let mut count = 0_usize; - for certificate in - rustls::pki_types::CertificateDer::pem_slice_iter(certificate.expose_secret()) - { - roots - .add(certificate.map_err(|_| invalid("a trusted root was not valid PEM"))?) - .map_err(|_| invalid("a trusted root was refused"))?; - count += 1; - } - if count == 0 { - return Err(invalid("the trusted root held no certificate")); - } + let roots = registry_platform_postgres::pem_root_store(certificate.expose_secret()) + .map_err(|error| invalid(error.message()))?; let client = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); @@ -2357,6 +2356,24 @@ audit: {retentionDays: 90} ); } + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config = static_key_runtime().database; + let (postgres, tls) = driver_config( + &config, + "postgresql://app@db.example/registry?sslmode=verify-full", + None, + registry_platform_config::DatabaseMember::RuntimeUrl, + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert!(tls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping @@ -2379,6 +2396,7 @@ audit: {retentionDays: 90} &runtime.database, "postgresql://app@localhost:5433/adapter", None, + registry_platform_config::DatabaseMember::RuntimeUrl, &fixed, ) .unwrap(); diff --git a/crates/registry-adapter/tests/facade_refusals.rs b/crates/registry-adapter/tests/facade_refusals.rs index 6a0968067f..21e2fcddad 100644 --- a/crates/registry-adapter/tests/facade_refusals.rs +++ b/crates/registry-adapter/tests/facade_refusals.rs @@ -350,6 +350,21 @@ async fn every_refusal_keeps_its_answer_and_is_counted_and_logged_under_its_chec let mut wanted: Vec = cases.iter().map(|case| case.check.to_owned()).collect(); wanted.sort(); assert_eq!(logged, wanted, "one value-free line per refusal"); + for (check, claim) in [("token-audience", "aud claim"), ("token-time", "exp claim")] { + assert!( + stderr + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .any(|event| { + event["fields"]["message"] == "request refused" + && event["fields"]["failed_check"] == check + && event["fields"]["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(claim)) + }), + "the isolated {check} control names {claim}" + ); + } for secret in tokens.iter().map(|(_, value)| value.as_str()).chain([ reader.as_str(), "stranger", diff --git a/crates/registry-adapterctl/src/job_provision.rs b/crates/registry-adapterctl/src/job_provision.rs index 04d74553d4..a4c88841af 100644 --- a/crates/registry-adapterctl/src/job_provision.rs +++ b/crates/registry-adapterctl/src/job_provision.rs @@ -4,9 +4,10 @@ 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, DatabaseMember, DeclaredPosture}; +use registry_platform_config::{DatabaseMember, DeclaredPosture, SecretError}; use registry_platform_provision::{ - provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, + provision_transport, read_ca_bundle, secret_refusal, secret_refusal_code, url_not_text_refusal, + ProductDatabase, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::{Diagnostic, SecretReference, Source}; use zeroize::Zeroizing; @@ -35,8 +36,8 @@ pub(crate) fn load( .join(path) }; let path_as_given = path.display().to_string(); - let refuse = |path: &str, message: String, action: &str| { - let mut diagnostic = diagnostic(path, message, action); + let in_file = |mut diagnostic: Diagnostic| { + diagnostic.artifact = Some(ADAPTER_JOB_RUNTIME_KIND.to_owned()); diagnostic.source = Some(Source { file: path_as_given.to_owned(), line: None, @@ -44,6 +45,8 @@ pub(crate) fn load( }); vec![diagnostic] }; + let refuse = + |path: &str, message: String, action: &str| in_file(diagnostic(path, message, action)); let runtime = JobRuntimeConfig::load_trusted(&absolute, declared).map_err(|error| { error .diagnostics() @@ -73,33 +76,26 @@ pub(crate) fn load( ) })?; let resolver = runtime.secret_resolver().map_err(|error| { - refuse( + in_file(Diagnostic::error( + secret_refusal_code(&error), "/secretProviders", error.to_string(), error.suggested_action(), - ) + )) })?; + let secret_refused = |member: DatabaseMember, error: &SecretError| { + in_file(secret_refusal("store", member, 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), - error.suggested_action(), - ) - }) + member + .read(&resolver, reference.as_str()) + .map_err(|error| secret_refused(member, &error)) }; 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())) - .map_err(|_| { - refuse( - &format!("/store/{member}"), - format!("store.{member} is not UTF-8 text"), - "Put a PostgreSQL URL in the secret.", - ) - }) + .map_err(|_| in_file(url_not_text_refusal("store", member))) }; Ok(ProvisionInput { product: ProductDatabase { @@ -113,9 +109,11 @@ pub(crate) fn load( ca_pem: store .ca_bundle_ref .as_ref() - .map(|reference| resolve(DatabaseMember::CaBundle, reference)) - .transpose()? - .map(|secret| secret.expose_secret().to_vec()), + .map(|reference| { + read_ca_bundle(&resolver, "store", reference.as_str()) + .map_err(|refused| in_file(*refused)) + }) + .transpose()?, 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 3ba29612c9..d421970473 100644 --- a/crates/registry-adapterctl/src/provision.rs +++ b/crates/registry-adapterctl/src/provision.rs @@ -11,11 +11,12 @@ use registry_adapter_core::{ ADAPTER_RUNTIME_KIND, }; use registry_platform_config::{ - describe_secret_failure, DatabaseMember, DeclaredPosture, RuntimeConfigLoader, RuntimeEnvelope, + DatabaseMember, DeclaredPosture, RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretProvider, SecretResolver, }; use registry_platform_provision::{ - provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, + provision_transport, read_ca_bundle, secret_refusal, secret_refusal_code, url_not_text_refusal, + ProductDatabase, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; @@ -37,6 +38,17 @@ fn refused(code: &str, path: &str, message: String, action: &str) -> Box Vec { + diagnostic.artifact = Some(ADAPTER_RUNTIME_KIND.to_owned()); + vec![diagnostic] +} + +/// The shared refusal of a database member's secret or public document. +fn secret_refused(member: DatabaseMember, error: &SecretError) -> Vec { + in_runtime_file(secret_refusal("database", member, error)) +} + /// Reads the runtime file exactly as `adapter serve` does and resolves the /// two database URLs and the CA behind `database.caBundleRef`. pub(crate) fn load( @@ -72,35 +84,22 @@ pub(crate) fn load( } .map_err(|error| { refuse( - "config.refused", + secret_refusal_code(&error), "/secretProviders", error.to_string(), - "Correct secretProviders in the runtime file, then run provision again.", + error.suggested_action(), ) })?; 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), - error.suggested_action(), - ) - }) + member + .read(&secrets, reference) + .map_err(|error| secret_refused(member, &error)) }; 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( - "config.refused", - &format!("/database/{member}"), - format!("database.{member} is not UTF-8 text"), - "Put a PostgreSQL URL in the secret, then run provision again.", - ) - }) + .map_err(|_| in_runtime_file(url_not_text_refusal("database", member))) }; let migration_url = url( DatabaseMember::MigrationUrl, @@ -111,9 +110,11 @@ pub(crate) fn load( .database .ca_bundle_ref .as_deref() - .map(|reference| resolve(DatabaseMember::CaBundle, reference)) - .transpose()? - .map(|secret| secret.expose_secret().to_vec()); + .map(|reference| { + read_ca_bundle(&secrets, "database", reference) + .map_err(|refused| in_runtime_file(*refused)) + }) + .transpose()?; Ok(ProvisionInput { product: product(), migration_url, diff --git a/crates/registry-adapterctl/tests/job_provision_cli.rs b/crates/registry-adapterctl/tests/job_provision_cli.rs index a7b10dda69..4b4db8ece6 100644 --- a/crates/registry-adapterctl/tests/job_provision_cli.rs +++ b/crates/registry-adapterctl/tests/job_provision_cli.rs @@ -118,6 +118,7 @@ fn print_sql_refuses_an_unsafe_store_secret_at_its_member() { assert!(report.contains("/store/migrationUrlRef"), "{report}"); let report: serde_json::Value = serde_json::from_str(&report).unwrap(); let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "platform.provision.secret-file-unsafe"); assert_eq!(diagnostic["source"]["file"], runtime); assert!( diagnostic["suggestedAction"] @@ -379,10 +380,10 @@ fn post_load_refusals_name_the_job_store() { ), ( "ca", - "admin-ca-invalid", + "ca-bundle-no-certificate", "domain-refusal", 1, - "", + "/store/caBundleRef", "store.caBundleRef", ), ( diff --git a/crates/registry-adapterctl/tests/provision_cli.rs b/crates/registry-adapterctl/tests/provision_cli.rs index b66ce28400..eaa1785534 100644 --- a/crates/registry-adapterctl/tests/provision_cli.rs +++ b/crates/registry-adapterctl/tests/provision_cli.rs @@ -165,6 +165,64 @@ fn a_runtime_file_the_loader_refuses_is_reported_without_connecting() { assert!(output.stdout.is_empty()); } +#[test] +fn a_missing_database_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!( + diagnostic["code"], "platform.provision.secret-unavailable", + "{diagnostic}" + ); + assert_eq!( + diagnostic["path"], "/database/runtimeUrlRef", + "{diagnostic}" + ); +} + +#[test] +fn a_ca_bundle_without_a_certificate_is_refused_in_print_mode() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let bundle = directory.path().join("secrets/database-ca.pem"); + std::fs::write(&bundle, "a bundle that holds no certificate\n").unwrap(); + std::fs::set_permissions(&bundle, std::fs::Permissions::from_mode(0o644)).unwrap(); + let document = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = document.replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca.pem\n", + ); + assert_ne!(document, with_ca, "the runtime file names the CA bundle"); + std::fs::write(&runtime, with_ca).unwrap(); + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + assert_eq!(output.status.code(), Some(1)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let diagnostic = &report["diagnostics"][0]; + assert_eq!( + diagnostic["code"], "platform.provision.ca-bundle-no-certificate", + "{diagnostic}" + ); + assert_eq!(diagnostic["path"], "/database/caBundleRef", "{diagnostic}"); +} + #[test] fn both_administrator_flags_are_refused() { let directory = scratch(); diff --git a/crates/registry-breg/src/action_outcome.rs b/crates/registry-breg/src/action_outcome.rs index b110d80a0c..28099eac69 100644 --- a/crates/registry-breg/src/action_outcome.rs +++ b/crates/registry-breg/src/action_outcome.rs @@ -738,12 +738,7 @@ pub(crate) fn decode_slot_mutations( mutations.push(CompiledPlanMutation::Clear { field }); } } - // The compiler emits an empty create ceiling only when the target has a - // server-generated field and no authored field is required from the handler. - let generated_only_create = operation == Operation::Create - && write.fields.is_empty() - && write.required_fields.is_empty(); - if mutations.is_empty() && !generated_only_create { + if mutations.is_empty() && !write.allows_empty_mutations() { return Err(WriteMutationDiagnostic::new( PlanError::Result, "Return at least one set or clear mutation for the slot.", diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index eb54b8263b..8c3c41a63b 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -18,10 +18,11 @@ use crate::model::{ ActionRouteKind, CompiledAccessInventory, CompiledAction, CompiledActionInput, CompiledActionInventory, CompiledActionRoute, CompiledEntity, CompiledEventDeliveryInventory, CompiledManifestProjection, CompiledMetadataInventory, CompiledModuleIdentity, - CompiledQueryInventory, CompiledQueryKind, CompiledQueryOperation, - CompiledQueryTemporalBinding, CompiledQueryTemporalSemantics, CompiledQueryTemporalValueKind, - CompiledRecipients, CompiledRevisionKind, CompiledRoute, CompiledRouteInventory, - CompiledStatisticalDataset, DisclosureWithhold, HttpMethod, + CompiledPlanEffect, CompiledPlanMutation, CompiledPlanValue, CompiledQueryInventory, + CompiledQueryKind, CompiledQueryOperation, CompiledQueryTemporalBinding, + CompiledQueryTemporalSemantics, CompiledQueryTemporalValueKind, CompiledRecipients, + CompiledRevisionKind, CompiledRoute, CompiledRouteInventory, CompiledStatisticalDataset, + DisclosureWithhold, HttpMethod, }; use crate::physical_names::{hex_prefix, PhysicalNameInventory}; use crate::record_profile::{link_header_value, CONTEXT_IDENTIFIER, PROFILE_IDENTIFIER}; @@ -1883,19 +1884,80 @@ fn invoke_may_refuse_write( .iter() .any(|profile_id| action_may_refuse_write(action, entities, profile_id)), OpenApiAccessProfiles::Selected(profile_id) => { - action_may_refuse_write(action, entities, profile_id) + route + .access_profiles + .iter() + .any(|profile| profile == profile_id) + && action_may_refuse_write(action, entities, profile_id) } } } -/// Whether the plan of `action`, written as `profile_id`, may be refused as -/// outside what the profile may write, as `operation_may_refuse_write` -/// decides for a record route. A plan Create is refused when a bound -/// `record` condition withholds the state it writes. A plan Patch is refused -/// when any bound condition applies: a `record` condition that withholds the -/// resulting state, or a `fields` or `history` condition whose mark the -/// Patch would lift or whose withheld field it would overwrite. -pub(crate) fn action_may_refuse_write( +fn action_may_refuse_write( + action: &CompiledAction, + entities: &BTreeMap, + profile_id: &str, +) -> bool { + if action_may_refuse_disclosure_write(action, entities, profile_id) { + return true; + } + if !action.evidence.is_empty() { + return false; + } + let Some(grant) = action.permissions.iter().find(|grant| { + grant.profile_id == profile_id && grant.operations.contains(&Operation::Invoke) + }) else { + return false; + }; + action.effects.iter().any(|effect| { + effect.operation == Operation::Create + && create_effect_may_be_request_only(action, effect) + && grant.targets.iter().any(|target| { + target.operation == Operation::Create + && target.entity_id == effect.target.entity_id + && entities.get(&target.entity_id).is_some_and(|entity| { + target.row_boundaries.iter().any(|boundary| { + entity + .fields + .get(&boundary.field) + .is_none_or(|field| field.generate.is_none()) + }) + }) + }) + }) +} + +fn create_effect_may_be_request_only(action: &CompiledAction, effect: &CompiledPlanEffect) -> bool { + if let Some(handler) = &action.handler { + let Some(slot) = handler.writes.iter().find(|slot| slot.id == effect.id) else { + return false; + }; + let ceiling = &slot.ceiling; + let can_set_without_effect = |field: &String| { + ceiling + .reference_sources + .get(field) + .is_none_or(|sources| !sources.inputs.is_empty()) + }; + // A request-only emission must supply every required field and at + // least one mutation, unless the ceiling admits a generated-only Create. + return ceiling.allows_empty_mutations() + || (ceiling.required_fields.iter().all(can_set_without_effect) + && ceiling.fields.iter().any(can_set_without_effect)); + } + !effect.mutations.iter().any(|mutation| { + matches!( + mutation, + CompiledPlanMutation::Set { + value: CompiledPlanValue::FromEffect { .. }, + .. + } + ) + }) +} + +/// Whether disclosure conditions can refuse a Create or Patch by this profile. +pub(crate) fn action_may_refuse_disclosure_write( action: &CompiledAction, entities: &BTreeMap, profile_id: &str, diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index dbdcb4ede1..1b1ad4578b 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -62,6 +62,7 @@ use crate::postgres::{ PostgresRecordMutationService, PostgresRecordReadService, PostgresRevisionReadService, PreparedSchemaTestCatalogVerifier, PreparedSchemaTestDatabase, RuntimePool, }; +use crate::problem::ProblemCode; use crate::runtime_config::{RuntimeConfig, RuntimeConfigError}; #[cfg(feature = "postgres-test")] use crate::startup::PreparedServer; @@ -5323,6 +5324,13 @@ fn problem_contract( status: u16, code: Option<&str>, ) -> Option<(&'static str, &'static [&'static str])> { + const WRITE_OUTSIDE_BOUNDARY: ProblemCode = ProblemCode::WriteOutsideBoundary; + const WRITE_OUTSIDE_BOUNDARY_RESPONSE: (u16, &str) = ( + WRITE_OUTSIDE_BOUNDARY.status(), + WRITE_OUTSIDE_BOUNDARY.code(), + ); + const WRITE_OUTSIDE_BOUNDARY_DETAILS: &[&str] = &[WRITE_OUTSIDE_BOUNDARY.description()]; + match (status, code?) { (400, "query.invalid") => Some(("Bad Request", &["The query request is invalid."])), (400, "request.invalid") => Some(("Bad Request", &["The request is invalid."])), @@ -5334,6 +5342,10 @@ fn problem_contract( "Forbidden", &["No access profile admits this caller for this request."], )), + WRITE_OUTSIDE_BOUNDARY_RESPONSE => Some(( + WRITE_OUTSIDE_BOUNDARY.title(), + WRITE_OUTSIDE_BOUNDARY_DETAILS, + )), (503, "action.evidence-failed") => Some(( "Service Unavailable", &["The declared Evidence dependency could not be accepted."], @@ -8587,6 +8599,14 @@ journeys: let (_, details) = problem_contract(status, Some(code)).expect("registered problem"); assert_eq!(details.len(), 1, "{code} carries exactly one detail"); } + assert_eq!( + problem_contract(403, Some("write.outside-boundary")), + Some(( + "Forbidden", + &["The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."][..], + )), + ); + assert!(problem_contract(412, Some("write.outside-boundary")).is_none()); assert!(problem_contract(400, Some("request.plan_refused")).is_none()); assert!(problem_contract(503, Some("request.plan_refused")).is_none()); } diff --git a/crates/registry-breg/src/history_maintenance.rs b/crates/registry-breg/src/history_maintenance.rs index a12c0d1b4a..fce1dc16a2 100644 --- a/crates/registry-breg/src/history_maintenance.rs +++ b/crates/registry-breg/src/history_maintenance.rs @@ -62,6 +62,7 @@ impl From for HistoryMaintenanceError { match error { PostgresKernelError::RoleInvariant(_) => Self::MigrationAuthority, PostgresKernelError::Configuration(_) + | PostgresKernelError::DatabaseTransport(_) | PostgresKernelError::FieldPatternSyntax { .. } | PostgresKernelError::FieldPatternExistingRows { .. } | PostgresKernelError::FieldEncryptionBlindCollision { .. } diff --git a/crates/registry-breg/src/migration_reconcile.rs b/crates/registry-breg/src/migration_reconcile.rs index cf5acc356c..10bf36ee2b 100644 --- a/crates/registry-breg/src/migration_reconcile.rs +++ b/crates/registry-breg/src/migration_reconcile.rs @@ -210,6 +210,7 @@ impl From for ReconcileError { Self::NotExecutable(ReconcileOutcome::InProgress) } PostgresKernelError::Configuration(_) + | PostgresKernelError::DatabaseTransport(_) | PostgresKernelError::FieldPatternSyntax { .. } | PostgresKernelError::FieldPatternExistingRows { .. } | PostgresKernelError::FieldEncryptionBlindCollision { .. } diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index 284262e5fe..a4e8c6ec47 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -404,6 +404,16 @@ pub struct CompiledPlanWrite { pub reference_sources: BTreeMap, } +impl CompiledPlanWrite { + pub(crate) fn allows_empty_mutations(&self) -> bool { + // The compiler accepts an empty Create ceiling only for a target + // with a server-generated field and no required authored fields. + self.operation == Operation::Create + && self.fields.is_empty() + && self.required_fields.is_empty() + } +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct CompiledPlanReferenceSources { diff --git a/crates/registry-breg/src/mutation/action.rs b/crates/registry-breg/src/mutation/action.rs index 216bb8761f..084c6b8d4e 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -1683,75 +1683,54 @@ impl MutationTransaction { .cloned() }) }); - if let Some(frozen) = frozen { + let effects = if let Some(frozen) = frozen { validate_frozen_evidence(frozen)?; match &frozen.outcome { - Ok(ActionHandlerOutcome::Effects(effects)) => *candidate = Some(effects.clone()), + Ok(ActionHandlerOutcome::Effects(effects)) => effects, Ok(ActionHandlerOutcome::Refusal(refusal)) => { - let mut refusal = refusal.clone(); - refusal.field = refusal.field.and_then(|id| { - action - .inputs - .iter() - .find(|input| input.id == id) - .map(|input| input.api_name.clone()) - }); - return Err(MutationError::ActionRefusal(refusal)); + return Err(action_plan_refusal(action, refusal.clone())); } Err(error) => return Err(error.clone()), } - } - - // Receipt recovery precedes computation. Once verified, retain this - // candidate and the host-reserved identities across confirmed aborts. - if candidate.is_none() { - *candidate = Some(if action.handler.is_some() { - // Keep receipt recovery and evaluation under the same key lock. - // The blocking worker receives only owned compiled declarations - // and bounded inputs, so cancellation cannot leave a worker - // holding database authority or committing late effects. - let compiled_action = action.clone(); - let handler_inputs = input_values.clone(); - let evaluation_date = trusted_evaluation_date(action, registry, trusted_now) - .map_err(MutationError::ActionHandlerFailure)?; - let outcome = tokio::task::spawn_blocking(move || { - evaluate_admitted_action_detailed_with_date( - &compiled_action, - &handler_inputs, - evaluation_date, - deadline.into_std(), + } else { + // Receipt recovery precedes computation. Retain the candidate and + // the host-reserved identities across confirmed aborts. + if candidate.is_none() { + *candidate = Some( + match evaluate_request_action_plan( + action, + registry, + input_values, + trusted_now, + deadline, ) - }) - .await - .map_err(|_| MutationError::Unavailable)? - .map_err(|diagnostic| { - // Locations are compiled identifiers and the cause is a - // static repair message. Never render Rhai errors, source, - // input values, or script-selected unknown identifiers. - diagnostic.log_failure(action, "invoke"); - MutationError::ActionHandlerFailure(diagnostic.kind) - })?; - match outcome { - ActionHandlerOutcome::Effects(effects) => effects, - ActionHandlerOutcome::Refusal(mut refusal) => { - refusal.field = refusal.field.and_then(|id| { - action - .inputs - .iter() - .find(|input| input.id == id) - .map(|input| input.api_name.clone()) - }); - return Err(MutationError::ActionRefusal(refusal)); - } - } - } else { - action.effects.clone() - }); - } + .await? + { + ActionHandlerOutcome::Effects(effects) => effects, + ActionHandlerOutcome::Refusal(refusal) => { + return Err(action_plan_refusal(action, refusal)); + } + }, + ); + } + candidate.as_ref().ok_or(MutationError::Unavailable)? + }; if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); } - let effects = candidate.as_ref().ok_or(MutationError::Unavailable)?; + // Evidence admission already checked request-only Creates using these + // same effects and reserved IDs. A timer firing has no Invoke caller. + if frozen.is_none() && timer_authority.is_none() { + refuse_create_outside_boundary( + registry, + effects, + action, + claims, + target_authority, + input_values, + reserved_creates, + )?; + } let application_reference = action_application_reference( self.audit.profile(), &self.expected.activation_id, @@ -3405,6 +3384,108 @@ fn action_target_group_context( } } +async fn evaluate_request_action_plan( + action: &CompiledAction, + registry: &CompiledRegistry, + input_values: &ActionInputs, + trusted_now: time::OffsetDateTime, + deadline: tokio::time::Instant, +) -> Result { + if action.handler.is_none() { + return Ok(ActionHandlerOutcome::Effects(action.effects.clone())); + } + // The blocking worker owns only bounded inputs and compiled declarations. + // It holds no database authority and cannot commit after cancellation. + let compiled_action = action.clone(); + let handler_inputs = input_values.clone(); + let evaluation_date = trusted_evaluation_date(action, registry, trusted_now) + .map_err(MutationError::ActionHandlerFailure)?; + tokio::task::spawn_blocking(move || { + evaluate_admitted_action_detailed_with_date( + &compiled_action, + &handler_inputs, + evaluation_date, + deadline.into_std(), + ) + }) + .await + .map_err(|_| MutationError::Unavailable)? + .map_err(|diagnostic| { + diagnostic.log_failure(action, "invoke"); + MutationError::ActionHandlerFailure(diagnostic.kind) + }) +} + +fn action_plan_refusal( + action: &CompiledAction, + mut refusal: crate::action_handler::ActionHandlerRefusal, +) -> MutationError { + refusal.field = refusal.field.and_then(|id| { + action + .inputs + .iter() + .find(|input| input.id == id) + .map(|input| input.api_name.clone()) + }); + MutationError::ActionRefusal(refusal) +} + +/// Refuse an Action whose create would write a row outside the caller's +/// target row boundary, deciding from the request alone: the caller's inputs, +/// the Action's literals and the identifiers reserved for its creates. It runs +/// before any target is read or guard evaluated, so the refusal depends on +/// nothing the caller cannot already see. A row the request does not decide, +/// because a value comes from another effect's Record, is left to the write, +/// which refuses it with the generic precondition failure. +fn refuse_create_outside_boundary( + registry: &CompiledRegistry, + effects: &[CompiledPlanEffect], + action: &CompiledAction, + claims: &ActionClaimContext, + target_authority: &BTreeMap>, + input_values: &ActionInputs, + reserved_creates: &BTreeMap, +) -> Result<(), MutationError> { + let mut creates = effects + .iter() + .filter(|effect| matches!(effect.target.binding, CompiledPlanTargetBinding::Create)) + .peekable(); + if creates.peek().is_none() { + return Ok(()); + } + check_current_action_grant(claims)?; + crate::postgres::validate_invoke_target_boundaries(registry, action, claims, target_authority) + .map_err(|_| MutationError::InvalidRequest)?; + for effect in creates { + let entity = registry + .entities() + .get(&effect.target.entity_id) + .ok_or(MutationError::InvalidRequest)?; + let boundaries = target_authority + .get(&effect.target.entity_id) + .ok_or(MutationError::InvalidRequest)?; + let record_id = *reserved_creates + .get(&effect.id) + .ok_or(MutationError::InvalidRequest)?; + // No prior rows: a value taken from another effect's Record makes + // the row undecided here. + let Ok(row) = + action_effect_document(action, entity, effect, input_values, &BTreeMap::new(), None) + else { + continue; + }; + if matches!( + crate::postgres::create_row_matches_request_boundaries( + entity, &row, record_id, boundaries, + ), + Ok(false) + ) { + return Err(MutationError::WriteOutsideBoundary); + } + } + Ok(()) +} + fn reserve_action_create_ids( action: &CompiledAction, ) -> Result, MutationError> { @@ -3911,6 +3992,7 @@ pub(crate) struct PreparedEvidenceAction { pub(crate) action: CompiledAction, pub(crate) inputs: ActionInputs, pub(crate) commit_requests: Vec<(CompiledEvidenceCapability, EvidenceSubjects)>, + pub(crate) request_plan: Option>, preconditions: BTreeMap, binding: crate::idempotency::ResolvedIdempotencyBinding, reserved_creates: BTreeMap, @@ -4138,6 +4220,30 @@ impl MutationTransaction { return Ok(Err(outcome)); } let trusted_now = time::OffsetDateTime::now_utc(); + let reserved_creates = reserve_action_create_ids(action)?; + // Commit Evidence governs the write. Only Evidence available to the + // Plan itself makes its candidate dependent on external values. + let request_plan = if action.evidence.is_empty() { + let outcome = + evaluate_request_action_plan(action, registry, &normalized, trusted_now, deadline) + .await; + // Guards retain precedence over planner failures and declared + // refusals. Only a Create candidate can give the early boundary refusal. + if let Ok(ActionHandlerOutcome::Effects(effects)) = &outcome { + refuse_create_outside_boundary( + registry, + effects, + action, + claims, + target_authority, + &normalized, + &reserved_creates, + )?; + } + Some(outcome) + } else { + None + }; // This transaction proves current admission only. Its locks and entire // pooled connection are released before any Evidence request. let guard_failure = self @@ -4203,7 +4309,8 @@ impl MutationTransaction { commit_requests, preconditions: input.preconditions, binding, - reserved_creates: reserve_action_create_ids(action)?, + reserved_creates, + request_plan, application_id, trusted_now, attempt: None, diff --git a/crates/registry-breg/src/postgres/config.rs b/crates/registry-breg/src/postgres/config.rs index 19f2c69bbc..38b0643dfa 100644 --- a/crates/registry-breg/src/postgres/config.rs +++ b/crates/registry-breg/src/postgres/config.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{error::Error as _, fmt, str::FromStr, sync::OnceLock, time::Duration}; +use std::{error::Error as _, fmt, sync::OnceLock, time::Duration}; use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; use tokio_postgres::NoTls; @@ -131,7 +131,7 @@ impl fmt::Debug for ConnectionConfig { impl ConnectionConfig { pub fn require_tls(url: &str, pool_bounds: PoolBounds) -> Result { - Self::require_tls_config(parse_connection(url)?, pool_bounds) + Self::require_tls_config(parse_connection(url, true)?, pool_bounds) } pub fn require_tls_config(mut postgres: Config, pool_bounds: PoolBounds) -> Result { @@ -162,7 +162,7 @@ impl ConnectionConfig { ca_der: &[u8], pool_bounds: PoolBounds, ) -> Result { - let mut postgres = parse_connection(url)?; + let mut postgres = parse_connection(url, true)?; postgres.ssl_mode(SslMode::Require); name_session(&mut postgres); if postgres.get_user().is_none() || postgres.get_dbname().is_none() { @@ -214,7 +214,7 @@ impl ConnectionConfig { /// Production configuration loaders must not expose this constructor. #[cfg(feature = "postgres-test")] pub fn test_only_plaintext(url: &str, pool_bounds: PoolBounds) -> Result { - let mut postgres = parse_connection(url)?; + let mut postgres = parse_connection(url, false)?; postgres.ssl_mode(SslMode::Disable); Self::from_test_config(postgres, pool_bounds) } @@ -352,13 +352,14 @@ impl ConnectionConfig { } } -fn parse_connection(url: &str) -> Result { +fn parse_connection(url: &str, verified_tls: bool) -> Result { if url.trim().is_empty() { return Err(PostgresKernelError::Configuration( "database URL must not be empty", )); } - Config::from_str(url).map_err(|_| PostgresKernelError::Configuration("database URL is invalid")) + registry_platform_postgres::parse_database_url(url, verified_tls) + .map_err(PostgresKernelError::DatabaseTransport) } pub(crate) fn ensure_crypto_provider() -> Result<()> { @@ -398,28 +399,8 @@ fn custom_ca_connector(ca_der: &[u8]) -> Result { /// Every certificate of a PEM bundle as a trust store. fn roots_from_pem(roots_pem: &[u8]) -> Result { - use rustls::pki_types::{pem::PemObject as _, CertificateDer}; - - if roots_pem.is_empty() || roots_pem.len() > MAX_CUSTOM_CA_DER_BYTES { - return Err(PostgresKernelError::Configuration( - "custom root certificates must be between 1 byte and 1 MiB", - )); - } - let mut roots = rustls::RootCertStore::empty(); - for certificate in CertificateDer::pem_slice_iter(roots_pem) { - let certificate = certificate.map_err(|_| { - PostgresKernelError::Configuration("custom root certificates are not valid PEM") - })?; - roots.add(certificate).map_err(|_| { - PostgresKernelError::Configuration("custom root certificate is invalid") - })?; - } - if roots.is_empty() { - return Err(PostgresKernelError::Configuration( - "custom root certificates hold no PEM certificate", - )); - } - Ok(roots) + registry_platform_postgres::pem_root_store(roots_pem) + .map_err(|error| PostgresKernelError::Configuration(error.message())) } fn connector_from_roots(roots: rustls::RootCertStore) -> Result { @@ -734,7 +715,7 @@ mod tests { let url = "postgresql://registry_runtime@registry.example/registry"; let config = ConnectionConfig::require_tls_config_with_roots_pem( - parse_connection(url).unwrap(), + parse_connection(url, false).unwrap(), bundle.as_bytes(), valid_bounds(), ) diff --git a/crates/registry-breg/src/postgres/context.rs b/crates/registry-breg/src/postgres/context.rs index a1136086f9..1d0334d95e 100644 --- a/crates/registry-breg/src/postgres/context.rs +++ b/crates/registry-breg/src/postgres/context.rs @@ -1648,6 +1648,54 @@ fn validate_snapshot_boundaries( } } +/// Validate the full target authority for an Invoke before inspecting any +/// prospective Create, including claims on fields left to the write. +pub(crate) fn validate_invoke_target_boundaries( + registry: &CompiledRegistry, + action: &crate::model::CompiledAction, + claims: &ActionClaimContext, + target_authority: &BTreeMap>, +) -> Result<()> { + claims.validate()?; + let grant = action + .permissions + .iter() + .find(|grant| { + grant.profile_id == claims.access_profile() + && grant.operations.contains(&Operation::Invoke) + }) + .ok_or_else(invalid_context)?; + for target in grant.entity_target_locks() { + let actual = target_authority + .get(&target.entity_id) + .ok_or_else(invalid_context)?; + validate_target_boundaries(registry, &target.entity_id, actual, &target.row_boundaries)?; + } + Ok(()) +} + +/// Whether a create's row satisfies the row boundaries the request itself +/// decides, before generated identifiers are allocated. A boundary on a +/// generated field is left to the write, which checks the allocated value. +pub(crate) fn create_row_matches_request_boundaries( + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + boundaries: &[RowBoundaryContext], +) -> Result { + let decided = boundaries + .iter() + .filter(|boundary| { + entity + .fields + .get(boundary.field()) + .is_none_or(|field| field.generate.is_none()) + }) + .cloned() + .collect::>(); + snapshot_matches_boundaries(entity, row, record_id, &decided) +} + pub(crate) fn snapshot_matches_boundaries( entity: &crate::model::CompiledEntity, row: &serde_json::Map, @@ -2851,6 +2899,28 @@ mod tests { .is_err()); } + #[test] + fn invoke_target_claims_must_match_the_compiled_boundary_type() { + let registry = compiled_action_context_registry(); + let action = ®istry.actions().actions[0]; + let claims = ActionClaimContext::new( + action.id.clone(), + "principal".into(), + "contact-registrar".into(), + Some("contact-registration".into()), + BTreeSet::new(), + ) + .unwrap(); + for (claim, valid) in [("zone-a".to_owned(), true), ("a".repeat(65), false)] { + let authority = + BTreeMap::from([("household".to_owned(), vec![equals("jurisdiction", &claim)])]); + assert_eq!( + validate_invoke_target_boundaries(®istry, action, &claims, &authority).is_ok(), + valid + ); + } + } + #[test] fn timer_patch_context_refuses_a_non_anchor_target() { let registry = compiled_timer_context_registry(); diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index 85d0e9d571..b861eadbed 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -56,9 +56,10 @@ pub use config::{ TlsPolicy, }; pub(crate) use context::{ - begin_action_transaction, begin_timer_action_transaction, snapshot_matches_boundaries, - ActionClaimContext, ImmediateActionLinkBinding, ImmediateActionLinkContext, - ImmediateActionTargetBinding, ImmediateActionTargetContext, + begin_action_transaction, begin_timer_action_transaction, + create_row_matches_request_boundaries, snapshot_matches_boundaries, + validate_invoke_target_boundaries, ActionClaimContext, ImmediateActionLinkBinding, + ImmediateActionLinkContext, ImmediateActionTargetBinding, ImmediateActionTargetContext, }; pub(crate) use context::{ begin_proposal_transaction, ProposalAuthority, ProposalAuthorityOperation, ProposalTargetPhase, @@ -397,6 +398,8 @@ pub(crate) mod stored_bytes_probe { /// A value-free PostgreSQL kernel error suitable for an operational boundary. #[derive(Debug, Error)] pub enum PostgresKernelError { + #[error("[{}] {}. {}", .0.code(), .0, .0.suggested_action())] + DatabaseTransport(registry_platform_config::DatabaseTransportError), #[error("invalid PostgreSQL configuration: {0}")] Configuration(&'static str), /// Only authored identifiers are retained; the expression and database error are discarded. diff --git a/crates/registry-breg/src/postgres/mutation.rs b/crates/registry-breg/src/postgres/mutation.rs index 137268056e..5c7e99c70a 100644 --- a/crates/registry-breg/src/postgres/mutation.rs +++ b/crates/registry-breg/src/postgres/mutation.rs @@ -465,7 +465,7 @@ impl PostgresRecordMutationService { ) -> Result { let route_id = input.route_id; let correlation = input.correlation; - let prepared = { + let mut prepared = { let client = self .pool .get() @@ -489,8 +489,15 @@ impl PostgresRecordMutationService { Err(receipt) => return Ok(receipt), } }; // Drop the entire pooled connection before evaluation or acquisition. - let mut frozen = match self.evidence_evaluator.as_ref() { - Some(evaluator) if prepared.action.handler.is_some() => { + let mut frozen = match ( + self.evidence_evaluator.as_ref(), + prepared.request_plan.take(), + ) { + (Some(_), Some(outcome)) => crate::action_evidence::FrozenEvidenceEvaluation { + outcome, + acquisitions: Vec::new(), + }, + (Some(evaluator), None) => { let evaluation_date = crate::action_handler::trusted_evaluation_date( &prepared.action, &self.registry, @@ -506,13 +513,7 @@ impl PostgresRecordMutationService { ) .await } - Some(_) => crate::action_evidence::FrozenEvidenceEvaluation { - outcome: Ok(crate::action_handler::ActionHandlerOutcome::Effects( - prepared.action.effects.clone(), - )), - acquisitions: Vec::new(), - }, - None => crate::action_evidence::FrozenEvidenceEvaluation { + (None, _) => crate::action_evidence::FrozenEvidenceEvaluation { outcome: Err(MutationError::Unavailable), acquisitions: Vec::new(), }, diff --git a/crates/registry-breg/src/proposal_artifacts.rs b/crates/registry-breg/src/proposal_artifacts.rs index 6f7e52b696..8aaec7be4e 100644 --- a/crates/registry-breg/src/proposal_artifacts.rs +++ b/crates/registry-breg/src/proposal_artifacts.rs @@ -63,7 +63,19 @@ pub(crate) fn append_proposal_openapi( } } apply_may_refuse_write |= permitted(ProposalOperation::Apply) - && action_may_refuse_write(action, entities, &grant.profile_id); + && (action_may_refuse_disclosure_write(action, entities, &grant.profile_id) + || grant.targets.iter().any(|target| { + // Apply admits a Create by its frozen after-state and + // a Patch by its current row. Only a Patch can cross + // the row boundary after admission. + target.row_boundaries.iter().any(|boundary| { + action.target_uses.iter().any(|effect| { + effect.operation == Operation::Patch + && effect.entity_id == target.entity_id + && effect.fields.contains(&boundary.field) + }) + }) + })); apply_may_fill_written_slot |= permitted(ProposalOperation::Apply) && !proposal.promotions.is_empty(); let field_guard = action.requires.iter().any(|guard| !guard.field.is_empty()); @@ -378,7 +390,6 @@ pub(crate) fn append_proposal_openapi( ); } if operation == ProposalOperation::Apply && apply_may_refuse_write { - document["responses"]["403"] = json!({"description":"The application writes outside what the selected access profile may write: a disclosure condition binds it on a record type the plan patches (`write.outside-boundary`)"}); append_problem_codes(&mut document, &[ProblemCode::WriteOutsideBoundary]); } if operation == ProposalOperation::Apply && apply_may_fill_written_slot { diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 37725e8c2b..f2bda3adb3 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -16,12 +16,12 @@ use jsonwebtoken::jwk::JwkSet; use registry_platform_audit::{AuditDestination, AuditDestinationKind, AuditProfile}; use registry_platform_config::{ check_metrics_bind_address, check_metrics_bind_apart, Admitted, AllowedClients, AuditKeyConfig, - CallerIssuerCore, CallerIssuerEntry, CallerIssuers, ClientRule, DatabaseTransport, - DatabaseTransportError, DeclaredPosture, DevelopmentWitness, ExplicitProductionSetting, - FoundExplicitSetting, JwksSource, LoadedRuntimeConfig, MetricsBindError, - PackageConfig as SharedPackageConfig, Posture, PostureReport, RemovedKey, RuntimeConfigLoader, - RuntimeEnvelope, SecretError, SecretFileCheck, SecretReference, SecretResolver, SettingOrigin, - TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, + CallerIssuerCore, CallerIssuerEntry, CallerIssuers, ClientRule, DatabaseMember, + DatabaseTransport, DatabaseTransportError, DeclaredPosture, DevelopmentWitness, + ExplicitProductionSetting, FoundExplicitSetting, JwksSource, LoadedRuntimeConfig, + MetricsBindError, PackageConfig as SharedPackageConfig, Posture, PostureReport, RemovedKey, + RuntimeConfigLoader, RuntimeEnvelope, SecretError, SecretFileCheck, SecretReference, + SecretResolver, SettingOrigin, TaskGrantStatusConfig, REMOVED_OIDC_JWKS_SOURCE_KIND, }; use registry_platform_crypto::{delivery_signature::DeliveryKeys, PublicJwk, SigningAlgorithm}; #[cfg(feature = "schema")] @@ -633,7 +633,7 @@ impl RuntimeConfigError { Self::DatabaseTransport(DatabaseTransportError::TestOnlyPlaintext) => { "/database/testOnlyPlaintext" } - Self::DatabaseTransport(_) => "/database/transport", + Self::DatabaseTransport(error) => error.database_pointer(), Self::InvalidPackage => "/package", Self::PackageRootUnavailable | Self::UnsafePackageRoot => "/package/root", Self::InvalidOidc | Self::InvalidStaticJwks(_) => ISSUERS_POINTER, @@ -2199,6 +2199,7 @@ impl RuntimeConfig { self.database_connection_config_for( &self.database.runtime_url_ref, self.database.roles.runtime(), + DatabaseMember::RuntimeUrl, ) } @@ -2206,6 +2207,7 @@ impl RuntimeConfig { self.database_connection_config_for( &self.database.migration_url_ref, self.database.roles.migration(), + DatabaseMember::MigrationUrl, ) } @@ -2213,13 +2215,17 @@ impl RuntimeConfig { &self, url_ref: &SecretReference, expected_role: &SqlIdentifier, + member: DatabaseMember, ) -> Result { let secret = self.secret_resolver()?.resolve_reference(url_ref)?; let url = std::str::from_utf8(secret.expose_secret()).map_err(|_| RuntimeConfigError::Secret)?; - let postgres = url - .parse::() - .map_err(|_| RuntimeConfigError::InvalidDatabase)?; + let postgres = registry_platform_postgres::parse_runtime_url( + url, + &self.database.transport, + self.development_witness(), + ) + .map_err(|error| RuntimeConfigError::DatabaseTransport(error.at_url(member)))?; if postgres.get_user() != Some(expected_role.as_str()) { return Err(RuntimeConfigError::InvalidDatabase); } @@ -2956,7 +2962,7 @@ static SCOPELESS_WITHOUT_SUBJECT_RULE: ExplicitProductionSetting = ExplicitProdu code: "breg.posture.scopeless-without-subject-rule", key: "accessProfiles", summary: - "a profile admits declared-kind tokens with no scope and no row rule keyed on the subject", + "A profile admits declared-kind tokens with no scope and no row rule keyed on the subject", }; impl fmt::Debug for AuthenticationConfig { diff --git a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs index f5af5b2ce9..b87c64c93b 100644 --- a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs +++ b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs @@ -5,8 +5,8 @@ use std::collections::BTreeSet; use jsonschema::{Draft, JSONSchema}; use serde_json::{json, Value}; -use crate::compiler::{compile_project, CompileProfile}; -use crate::contract::{parse_project_json, Operation}; +use crate::compiler::{compile_project, compile_project_with_assets, CompileProfile}; +use crate::contract::{parse_project_json, ModuleAssetSource, Operation}; use crate::model::{CompiledRegistry, HttpMethod}; #[test] @@ -1173,7 +1173,8 @@ fn compiled_bound_writer_registry() -> CompiledRegistry { #[test] fn a_caller_document_declares_a_record_condition_write_refusal_to_a_bound_writer() { for effect in ["patch", "create"] { - let registry = compiled_record_condition_writer_registry(effect); + let registry = + compiled_record_condition_writer_registry(effect, json!("unrestricted"), true); let action = registry .actions() .actions @@ -1222,29 +1223,88 @@ fn a_caller_document_declares_a_record_condition_write_refusal_to_a_bound_writer } } +#[test] +fn bounded_proposal_apply_documents_admission_and_write_refusals() { + let row_boundaries = json!([{"field": "phone", "claim": "phone", "operator": "equals"}]); + for (effect, bound_condition, declares_refusal) in [ + ("create", false, false), + ("patch", false, true), + ("create", true, true), + ] { + let registry = compiled_record_condition_writer_registry( + effect, + row_boundaries.clone(), + bound_condition, + ); + let visible = BTreeSet::from([( + "propose-person".to_owned(), + "registrar".to_owned(), + crate::model::ProposalOperation::Apply, + )]); + for filter in [None, Some(&visible)] { + let mut paths = serde_json::Map::new(); + super::append_proposal_openapi( + &mut paths, + registry.actions(), + registry.entities(), + filter, + ) + .unwrap(); + let apply = &paths["/v1/proposals/{proposal_id}/apply"]["post"]; + let case = format!("{effect}, bound condition: {bound_condition}, filter: {filter:?}"); + assert_eq!( + apply["responses"]["412"]["content"]["application/problem+json"]["examples"] + ["precondition.failed"]["value"]["status"], + 412, + "{case}" + ); + let forbidden = &apply["responses"]["403"]["content"]["application/problem+json"]; + assert_eq!( + forbidden["schema"]["allOf"][1]["properties"]["code"]["enum"], + if declares_refusal { + json!(["profile.not-authorized", "write.outside-boundary"]) + } else { + json!(["profile.not-authorized"]) + }, + "{case}" + ); + assert_eq!( + declares_write_boundary_refusal(apply), + declares_refusal, + "{case}" + ); + } + } +} + /// `registrar` and `officer` both write a person through an immediate Action /// and apply a manual Proposal whose plan runs one `effect`, `patch` or -/// `create`. A `record` condition withholds a protected person from every -/// profile but `officer`. -fn compiled_record_condition_writer_registry(effect: &str) -> CompiledRegistry { +/// `create`. When `bound_condition` is set, a `record` condition also +/// withholds protected people from `registrar`. +fn compiled_record_condition_writer_registry( + effect: &str, + row_boundaries: Value, + bound_condition: bool, +) -> CompiledRegistry { let phone = json!({"id": "phone", "apiName": "phone", "type": "string", "maximumLength": 32, "required": true, "classification": "internal"}); - let targets = json!([{"recordType": "person", "rowBoundaries": "unrestricted"}]); + let protected = json!({"id": "protected", "type": "boolean", + "required": true, "classification": "internal"}); + let set = json!({"phone": {"fromInput": "phone"}, "protected": {"fromInput": "protected"}}); + let targets = json!([{"recordType": "person", "rowBoundaries": row_boundaries}]); let (inputs, plan, commit_guards) = if effect == "patch" { ( json!([{"id": "person", "apiName": "personId", "type": "reference", - "target": "person", "required": true, "classification": "internal"}, phone]), + "target": "person", "required": true, "classification": "internal"}, phone, protected]), json!({"type": "fixed", "effects": [ - {"id": "contact", "target": {"fromInput": "person"}, "operation": "patch", - "set": {"phone": {"fromInput": "phone"}}}]}), + {"id": "contact", "target": {"fromInput": "person"}, "operation": "patch", "set": set}]}), json!({"targets": [{"input": "person", "revision": "unchanged"}]}), ) } else { ( - json!([phone]), + json!([phone, protected]), json!({"type": "fixed", "effects": [ - {"id": "contact", "target": {"recordType": "person"}, "operation": "create", - "set": {"phone": {"fromInput": "phone"}}}]}), + {"id": "contact", "target": {"recordType": "person"}, "operation": "create", "set": set}]}), json!({}), ) }; @@ -1260,10 +1320,10 @@ fn compiled_record_condition_writer_registry(effect: &str) -> CompiledRegistry { {"action": "propose-person", "operations": ["start"], "targets": targets}], "proposals": [{"action": "propose-person", "ownership": "caller", "operations": ["get", "list", "edit", "submit", "cancel", "apply"], - "readableInputs": if effect == "patch" { json!(["person", "phone"]) } else { json!(["phone"]) }, + "readableInputs": if effect == "patch" { json!(["person", "phone", "protected"]) } else { json!(["phone", "protected"]) }, "targets": targets}]}}) }; - let source = json!({"datasets": {"test-dataset": {}}, + let mut source = json!({"datasets": {"test-dataset": {}}, "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", "kind": "BRegProject", "project": {"id": "record-condition-writer", "version": "1", "defaultLanguage": "en", "canonicalBaseIri": "https://record-condition-writer.example.test"}, @@ -1272,9 +1332,7 @@ fn compiled_record_condition_writer_registry(effect: &str) -> CompiledRegistry { "fields": [ {"id": "family-name", "type": "string", "maximumLength": 64, "classification": "internal"}, {"id": "protected", "type": "boolean", "classification": "internal"}, - {"id": "phone", "type": "string", "maximumLength": 32, "classification": "internal"}], - "disclosureConditions": {"hide-protected": {"when": [{"type": "field-equals", "field": "protected", "value": true}], - "withhold": "record", "exemptProfiles": ["officer"]}}}}, + {"id": "phone", "type": "string", "maximumLength": 32, "classification": "internal"}]}}, "actions": { "write-person": {"inputs": inputs, "plan": plan, "execution": {"mode": "immediate"}}, @@ -1284,6 +1342,12 @@ fn compiled_record_condition_writer_registry(effect: &str) -> CompiledRegistry { "application": {"mode": "manual"}, "retention": {"mode": "operator-erase"}}}}}, "accessProfiles": {"registrar": profile("registrar", true), "officer": profile("officer", false)} }); + if bound_condition { + source["recordTypes"]["person"]["disclosureConditions"] = json!({ + "hide-protected": {"when": [{"type": "field-equals", "field": "protected", "value": true}], + "withhold": "record", "exemptProfiles": ["officer"]} + }); + } let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).expect("fixture parses"); compile_project(&project, &[], CompileProfile::Authoring).expect("fixture compiles") @@ -1367,3 +1431,187 @@ fn compiled_required_filter_registry(required: bool) -> CompiledRegistry { parse_project_json(&serde_json::to_vec(&source).unwrap()).expect("fixture parses"); compile_project(&project, &[], CompileProfile::Authoring).expect("fixture compiles") } + +/// An immediate Action that creates into a row-bounded target grant answers +/// `403 write.outside-boundary` for a row outside the boundary, so its +/// invoke route documents that refusal; an unrestricted grant does not. +#[test] +fn an_action_create_into_a_bounded_target_documents_the_boundary_refusal() { + let compile = |row_boundaries: Value| { + let source = json!({"datasets": {"test-dataset": {}}, + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": {"id": "bounded-create", "version": "1", "defaultLanguage": "en", + "canonicalBaseIri": "https://bounded-create.example.test"}, + "recordTypes": {"person": {"primaryDataset": "test-dataset", "route": "people", + "mutationMode": "mutable", "classification": "internal", + "fields": [ + {"id": "name", "type": "string", "maximumLength": 64, "required": true, + "classification": "internal"}, + {"id": "jurisdiction", "type": "string", "maximumLength": 16, + "required": true, "classification": "internal"}]}}, + "actions": {"register-person": { + "execution": {"mode": "immediate"}, + "inputs": [ + {"id": "name", "type": "string", "maximumLength": 64, "required": true, + "classification": "internal"}, + {"id": "jurisdiction", "type": "string", "maximumLength": 16, + "required": true, "classification": "internal"}], + "plan": {"type": "fixed", "effects": [ + {"id": "person", "target": {"recordType": "person"}, "operation": "create", + "set": {"name": {"fromInput": "name"}, + "jurisdiction": {"fromInput": "jurisdiction"}}}]}}}, + "accessProfiles": {"registrar": {"default": true, + "principalClaim": "registry_principal", + "requiredScopes": ["registry.register"], + "permissions": {"actions": [{"action": "register-person", + "operations": ["invoke"], + "targets": [{"recordType": "person", "rowBoundaries": row_boundaries}], + "results": ["person"]}]}}}}); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Authoring).unwrap() + }; + for (row_boundaries, documented) in [ + ( + json!([{"field": "jurisdiction", "claim": "jurisdiction", "operator": "equals"}]), + true, + ), + (json!("unrestricted"), false), + ] { + let registry = compile(row_boundaries); + let action = ®istry.actions().actions[0]; + assert_eq!( + super::action_may_refuse_write(action, registry.entities(), "registrar"), + documented + ); + } +} + +#[test] +fn scripted_create_documents_the_boundary_refusal_when_its_row_can_be_request_only() { + for (case, required_reference, reference_input, scalar_write, documented) in [ + ( + "required reference from another effect", + true, + false, + true, + false, + ), + ( + "optional reference may be omitted", + false, + false, + true, + true, + ), + ("required reference from input", true, true, true, true), + ( + "only optional reference from another effect", + false, + false, + false, + false, + ), + ( + "only optional reference from input", + false, + true, + false, + true, + ), + ] { + let person_fields = if scalar_write { + json!(["group", "jurisdiction"]) + } else { + json!(["group"]) + }; + let boundary_field = if scalar_write { "jurisdiction" } else { "id" }; + let mut source = json!({"datasets": {"test-dataset": {}}, + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": {"id": "scripted-create", "version": "1", "defaultLanguage": "en", + "canonicalBaseIri": "https://scripted-create.example.test"}, + "recordTypes": { + "group": {"primaryDataset": "test-dataset", "route": "groups", + "mutationMode": "mutable", "classification": "internal", "fields": [ + {"id": "name", "type": "string", "maximumLength": 64, + "required": true, "classification": "internal"}]}, + "person": {"primaryDataset": "test-dataset", "route": "people", + "mutationMode": "mutable", "classification": "internal", "fields": [ + {"id": "group", "type": "reference", "target": "group", + "required": required_reference, "classification": "internal"}, + {"id": "jurisdiction", "type": "string", "maximumLength": 16, + "required": scalar_write, "classification": "internal"}]}}, + "actionPlans": {"register-plan": {"runtime": "rhai", "source": "plans/register.rhai", + "entrypoint": "plan", "abi": "registry.action-plan/v1", "capabilities": []}}, + "actions": {"register-person": {"execution": {"mode": "immediate"}, + "inputs": [{"id": "jurisdiction", "type": "string", "maximumLength": 16, + "required": true, "classification": "internal"}], + "plan": {"type": "scripted", "actionPlan": "register-plan", + "inputs": ["jurisdiction"], "writes": [ + {"id": "group", "target": {"recordType": "group"}, + "operation": "create", "fields": ["name"]}, + {"id": "person", "target": {"recordType": "person"}, + "operation": "create", "fields": person_fields}]}}}, + "accessProfiles": {"registrar": {"default": true, + "principalClaim": "registry_principal", "requiredScopes": ["registry.register"], + "permissions": {"actions": [{"action": "register-person", "operations": ["invoke"], + "targets": [ + {"recordType": "group", "rowBoundaries": "unrestricted"}, + {"recordType": "person", "rowBoundaries": [ + {"field": boundary_field, "claim": "boundary", "operator": "equals"}]}], + "results": ["person"]}]}}}}); + let mut person_values = Vec::new(); + if scalar_write { + person_values.push("jurisdiction: ctx.inputs.jurisdiction"); + } + if reference_input { + source["actions"]["register-person"]["inputs"] + .as_array_mut() + .unwrap() + .push( + json!({"id": "group", "type": "reference", "target": "group", + "required": true, "classification": "internal"}), + ); + source["actions"]["register-person"]["plan"]["inputs"] = + json!(["jurisdiction", "group"]); + person_values.push(r#"group: #{fromInput: "group"}"#); + } else if required_reference || !scalar_write { + person_values.push(r#"group: #{fromEffect: "group"}"#); + } + let person_values = person_values.join(", "); + let script = format!( + r#"fn plan(ctx) {{ + #{{effects: [ + #{{id: "group", set: #{{name: "Example"}}}}, + #{{id: "person", set: #{{{person_values}}}}} + ]}} + }}"# + ); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project_with_assets( + &project, + &[], + &[ModuleAssetSource { + module: None, + path: "plans/register.rhai".into(), + bytes: script.into_bytes(), + }], + CompileProfile::Authoring, + ) + .unwrap(); + let openapi = generated_openapi(®istry); + let invoke = &openapi["paths"]["/v1/actions/register-person"]["post"]; + assert_eq!( + invoke["responses"]["412"]["content"]["application/problem+json"]["examples"] + ["precondition.failed"]["value"]["status"], + 412, + "{case}" + ); + assert_eq!( + declares_write_boundary_refusal(invoke), + documented, + "{case}" + ); + } +} diff --git a/crates/registry-breg/tests/authentication_refusals.rs b/crates/registry-breg/tests/authentication_refusals.rs index b972c6e87b..49c0b95264 100644 --- a/crates/registry-breg/tests/authentication_refusals.rs +++ b/crates/registry-breg/tests/authentication_refusals.rs @@ -945,6 +945,20 @@ async fn every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wir "{}: the line carries the request trace id", case.name ); + let expected_remedy = match case.name { + "wrong-audience" => Some("aud claim"), + "expired-token" => Some("exp claim"), + _ => None, + }; + if let Some(claim) = expected_remedy { + assert!( + fields["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(claim)), + "{}: the operator diagnostic names the token claim", + case.name + ); + } let mut keys: BTreeSet<&str> = fields.keys().map(String::as_str).collect(); // A refusal an operator fixes in configuration names the setting in // `remedy`, fixed text that holds no caller value. diff --git a/crates/registry-breg/tests/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index 374bd2e89d..188d7d13b2 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -137,7 +137,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/asset-registration-actions/modules/asset-registration-actions-core/module.yaml" )), ddl_sha256: "43acdae956eb2f932fb22a2cccc5cee5ed19cf806f2f28bbc677eff219d00b99", - revision: "sha256:6d9e4da6a98799e51faf07bf39ac5bd741d0bdb7086d9f0281ffed4ef36d6706", + revision: "sha256:2ab48b17d42c7e06b9ca0bb33de9d3e17e7864656dc98fee4c15f386e55ddf55", }, Fixture { name: "facility-registry-actions", @@ -148,7 +148,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/facility-registry-actions/modules/facility-registry-actions-core/module.yaml" )), ddl_sha256: "6439a877ee6508b999a77242542695d8ccddc6d80518699d90eddc32b305780b", - revision: "sha256:a0f2d6ba534425b7f1ce68af3e76ed44ee2938232c6c6db1e07818e818eda863", + revision: "sha256:9b46e4f5bf7d5d115411768b94b44db919c84648adc4cb6c5d8d9b976d3c6d6f", }, Fixture { name: "household-contact-actions", @@ -159,7 +159,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/household-contact-actions/modules/household-contact-actions-core/module.yaml" )), ddl_sha256: "f82f2f8376df97fb184c04d31c8e42c291f7a03dbd909828e1bf61612106de35", - revision: "sha256:7513e3f517649641bfda36027e5ff437c5a6139ec5ec7224913dcd1c34a5e43a", + revision: "sha256:a75cbc6e65d24415a55a5a949b01bfbbe68c3588ff2749b8ae7f68cd2934aa42", }, ]; diff --git a/crates/registry-breg/tests/disclosure_exposure.rs b/crates/registry-breg/tests/disclosure_exposure.rs index c71be4ef56..79213fb0ce 100644 --- a/crates/registry-breg/tests/disclosure_exposure.rs +++ b/crates/registry-breg/tests/disclosure_exposure.rs @@ -234,13 +234,27 @@ fn declared_workflow_write_refusals(registry: &CompiledRegistry) -> [bool; 2] { let apply = &openapi["paths"]["/v1/proposals/{proposal_id}/apply"]["post"]; assert!(!invoke.is_null(), "the fixture has no Action invoke"); assert!(!apply.is_null(), "the fixture has no Proposal apply"); + let apply_problem = &apply["responses"]["403"]["content"]["application/problem+json"]; + let refusal = apply_problem["examples"].get("write.outside-boundary"); + if let Some(example) = refusal { + assert_eq!(example["value"]["code"], "write.outside-boundary"); + assert_eq!(example["value"]["status"], 403); + } + let apply_codes = apply_problem["schema"]["allOf"][1]["properties"]["code"]["enum"] + .as_array() + .expect("Proposal Apply declares its 403 problem codes"); + assert_eq!( + refusal.is_some(), + apply_codes + .iter() + .any(|code| code == "write.outside-boundary"), + "Proposal Apply's schema and examples agree on the refusal" + ); [ invoke["responses"]["403"]["content"]["application/problem+json"]["examples"] .get("write.outside-boundary") .is_some(), - apply["responses"]["403"]["description"] - .as_str() - .is_some_and(|description| description.contains("`write.outside-boundary`")), + refusal.is_some(), ] } diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index 40c7add613..ea35c82ec7 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -4762,7 +4762,7 @@ destinations: assert_eq!(found.len(), 1, "{:?}", check.explicit_settings); assert_eq!( found[0].setting.summary, - "a profile admits declared-kind tokens with no scope and no row rule keyed on the subject" + "A profile admits declared-kind tokens with no scope and no row rule keyed on the subject" ); assert_eq!( found[0].origin, diff --git a/crates/registry-breg/tests/postgres_action_evidence.rs b/crates/registry-breg/tests/postgres_action_evidence.rs index 3930beab0a..29040825fe 100644 --- a/crates/registry-breg/tests/postgres_action_evidence.rs +++ b/crates/registry-breg/tests/postgres_action_evidence.rs @@ -23,7 +23,7 @@ use registry_breg::{ action_evidence::ActionEvidenceEvaluator, api::{ router, HttpService, ReadRuntimeIdentity, ReadinessProbe, ServiceFuture, - VerifiedRequestClaims, + VerifiedClaimValue, VerifiedRequestClaims, }, compiler::{compile_project_with_assets, CompileProfile}, contract::{parse_project_yaml, ModuleAssetSource}, @@ -253,7 +253,11 @@ async fn send( } .into()]), Some("land-registration".into()), - BTreeMap::new(), + BTreeMap::from([( + "permitted-parcels".into(), + VerifiedClaimValue::direct_string_set(["guarded", "new", "refused", "expired"]) + .unwrap(), + )]), ) .unwrap(); let mut request = Request::builder() @@ -361,6 +365,13 @@ async fn commit_evidence_is_guard_only_and_replay_never_reacquires() { "subjects":{"farmer":{"profile":"farmer-number-v1","selectors":{"farmer-number":{"type":"input","input":"farmer-number"}}}}, "requires":[{"output":"active","equals":true}],"maximumObservationAgeSeconds":60 })).unwrap()); + let profile = project.access_profiles.iter_mut() + .find(|profile| profile.id == "landholding-registrar").unwrap(); + profile.permissions.actions[0].targets[0].row_boundaries.push( + serde_json::from_value(json!({ + "field": "parcel-code", "claim": "permitted-parcels", "operator": "in" + })).unwrap(), + ); }).await; let provider = EvidenceProvider::start().await; let (app, _) = app( @@ -370,6 +381,19 @@ async fn commit_evidence_is_guard_only_and_replay_never_reacquires() { &provider, None, ); + let refused = send( + app.clone(), + ACTION, + "outside-parcel-boundary", + input("out-of-scope", false), + true, + ) + .await; + assert_eq!(refused.0, StatusCode::FORBIDDEN, "{}", refused.1); + assert_eq!(refused.1["code"], "write.outside-boundary"); + assert_eq!(provider.calls(), 0); + assert_eq!(counts(&database, ®istry).await, vec![0; 6]); + let first = send( app.clone(), ACTION, diff --git a/crates/registry-breg/tests/postgres_immediate_actions.rs b/crates/registry-breg/tests/postgres_immediate_actions.rs index 5f3e80af53..a0192c43a6 100644 --- a/crates/registry-breg/tests/postgres_immediate_actions.rs +++ b/crates/registry-breg/tests/postgres_immediate_actions.rs @@ -1481,11 +1481,15 @@ async fn action_conditions_and_invocation_refuse_aliases_wrong_records_and_bound .await, ) .await; - assert_eq!(boundary_escape.status, StatusCode::PRECONDITION_FAILED); - assert_eq!(boundary_escape.body["code"], "precondition.failed"); + // The new person's jurisdiction comes from the caller's own input, so a + // row outside the caller's boundary is refused from the request alone, + // before any target read, with the 403 a direct create answers. It used + // to be the generic 412; the answer still names no value. + assert_eq!(boundary_escape.status, StatusCode::FORBIDDEN); + assert_eq!(boundary_escape.body["code"], "write.outside-boundary"); assert_eq!( boundary_escape.body["detail"], - "The mutation precondition failed." + "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition." ); assert_eq!( boundary_escape @@ -4150,3 +4154,296 @@ async fn a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_ "the hidden record is untouched" ); } + +/// The action project plus two Actions that create a person beside a guarded +/// household target: `file-person-open` guards on `status-note` being unset, +/// which holds for a seeded household, and `file-person-uncoded` guards on +/// `household-code` being `H-UNCODED`, which fails for one. `contact-registrar` +/// reads no household field, so either guard is unreadable to it; +/// `contact-reader` invokes the same Actions and reads both guarded fields. +fn guarded_create_registry() -> registry_breg::CompiledRegistry { + let mut source: Value = serde_json::from_slice(ACTION_PROJECT).expect("action project is JSON"); + let inputs = json!([ + {"id": "household", "apiName": "householdId", "type": "reference", + "target": "household", "required": true, "classification": "restricted"}, + {"id": "person-code", "apiName": "personCode", "type": "string", + "maximumLength": 64, "required": true, "classification": "restricted"}, + {"id": "legal-name", "apiName": "legalName", "type": "string", + "maximumLength": 160, "required": true, "classification": "restricted"}, + {"id": "jurisdiction", "apiName": "jurisdiction", "type": "string", + "maximumLength": 64, "required": true, "classification": "restricted"} + ]); + let plan = json!({"type": "fixed", "effects": [ + {"id": "person", "target": {"recordType": "person"}, "operation": "create", + "set": {"person-code": {"fromInput": "person-code"}, + "legal-name": {"fromInput": "legal-name"}, + "jurisdiction": {"fromInput": "jurisdiction"}}} + ]}); + for (action, guard) in [ + ( + "file-person-open", + json!({"input": "household", "field": "status-note", "isNull": true, + "reason": "household-closed"}), + ), + ( + "file-person-uncoded", + json!({"input": "household", "field": "household-code", "equals": "H-UNCODED", + "reason": "household-coded"}), + ), + ] { + source["actions"][action] = json!({ + "inputs": inputs.clone(), + "execution": {"mode": "immediate"}, + "commitGuards": {"targets": [guard]}, + "plan": plan.clone() + }); + } + let boundary = json!([{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]); + let grants = ["file-person-open", "file-person-uncoded"].map(|action| { + json!({ + "action": action, "operations": ["invoke"], + "targets": [ + {"recordType": "household", "rowBoundaries": boundary.clone()}, + {"recordType": "person", "rowBoundaries": boundary.clone()} + ], + "results": ["person"] + }) + }); + source["accessProfiles"]["contact-registrar"]["permissions"]["actions"] + .as_array_mut() + .expect("the registrar grants Actions") + .extend(grants.clone()); + source["accessProfiles"]["contact-reader"] = json!({ + "principalClaim": "registry_principal", + "requiredScopes": ["registry:contact:read-register"], + "requiredPurposes": ["contact-registration"], + "permissions": { + "records": [{ + "recordType": "household", "operations": ["get"], + "readableFields": ["household-code", "status-note", "jurisdiction"], + "rowBoundaries": boundary.clone() + }], + "actions": grants + } + }); + let project = parse_project_json(&serde_json::to_vec(&source).expect("project serializes")) + .expect("guarded create project parses"); + compile_project(&project, &[], CompileProfile::Authoring) + .expect("guarded create project compiles") +} + +/// Invoke one of the guarded create Actions for `household`, with the +/// condition the caller obtained for the visible household when the Action +/// asks for one. +#[allow(clippy::too_many_arguments)] +async fn invoke_guarded_create( + app: &axum::Router, + claims: VerifiedRequestClaims, + action: &str, + key: &str, + household: &str, + jurisdiction: &str, + condition: &Value, +) -> ResponseParts { + let mut body = json!({"input": { + "householdId": household, + "personCode": format!("P-{key}"), + "legalName": "Guarded Person", + "jurisdiction": jurisdiction + }}); + if let Some(preconditions) = condition.get("preconditions") { + body["preconditions"] = preconditions.clone(); + } + response_parts( + send( + app, + Method::POST, + &format!("/v1/actions/{action}"), + Some(claims), + &[ + ("content-type", "application/json"), + ("idempotency-key", key), + ], + serde_json::to_vec(&body).expect("invoke body serializes"), + ) + .await, + ) + .await +} + +/// A create whose new row is outside the caller's target row boundary is +/// refused with `403 write.outside-boundary` from the request alone, before +/// any target is read or any guard evaluated. The answer is the same whether +/// the guard passes, fails on a field the caller reads, or fails on a field +/// it cannot read, and whether the named target is visible, hidden or +/// missing, so the refusal discloses nothing about records outside the +/// boundary. The same create inside the boundary is unchanged: it applies, or +/// answers the guard refusal it answered before. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_action_create_outside_the_boundary_is_refused_before_targets_and_guards() { + let (database, registry, identity) = install_action_registry(guarded_create_registry()).await; + for (id, code, jurisdiction) in [ + (HOUSEHOLD_ID, "H-001", "zone-a"), + (OTHER_HOUSEHOLD_ID, "H-002", "zone-b"), + ] { + seed_household(&database, ®istry, &identity, id, code, jurisdiction).await; + } + let app = action_router(&database, registry.clone(), identity); + let registrar = action_claims(); + let reader = action_claims_for("registry:contact:read-register", "zone-a"); + let mut conditions = BTreeMap::new(); + for (profile, claims) in [("registrar", ®istrar), ("reader", &reader)] { + for action in ["file-person-open", "file-person-uncoded"] { + let compiled = registry + .actions() + .actions + .iter() + .find(|compiled| compiled.id == action) + .expect("guarded Action compiles"); + // A guard-only target asks for no condition and serves no + // target-conditions route. + if registry_breg::plan::condition_inputs(compiled).is_empty() { + conditions.insert((profile, action), json!({})); + continue; + } + let condition = response_parts( + send( + &app, + Method::POST, + &format!("/v1/actions/{action}/target-conditions"), + Some(claims.clone()), + &[("content-type", "application/json")], + serde_json::to_vec(&json!({"input": {"householdId": HOUSEHOLD_ID}})) + .expect("condition body serializes"), + ) + .await, + ) + .await; + assert_eq!(condition.status, StatusCode::OK, "{profile} {action}"); + conditions.insert((profile, action), condition.body); + } + } + let before = action_counts(&database, ®istry).await; + let people_before = entity_count(&database, ®istry, "person").await; + let missing_household = Uuid::new_v4().to_string(); + + let mut refusals = Vec::new(); + for (profile, claims, action, household, key) in [ + ( + "registrar", + ®istrar, + "file-person-open", + HOUSEHOLD_ID, + "out-open", + ), + ( + "registrar", + ®istrar, + "file-person-uncoded", + HOUSEHOLD_ID, + "out-hidden-guard", + ), + ( + "reader", + &reader, + "file-person-uncoded", + HOUSEHOLD_ID, + "out-read-guard", + ), + ( + "registrar", + ®istrar, + "file-person-open", + OTHER_HOUSEHOLD_ID, + "out-hidden-target", + ), + ( + "registrar", + ®istrar, + "file-person-open", + missing_household.as_str(), + "out-missing", + ), + ] { + let refused = invoke_guarded_create( + &app, + claims.clone(), + action, + key, + household, + "zone-b", + &conditions[&(profile, action)], + ) + .await; + assert_eq!( + refused.status, + StatusCode::FORBIDDEN, + "{key}: {}", + refused.body + ); + assert_eq!(refused.body["code"], "write.outside-boundary", "{key}"); + for concealed in ["zone-b", "P-out", "Guarded Person"] { + assert!( + !refused.body.to_string().contains(concealed), + "{key} disclosed {concealed}: {}", + refused.body + ); + } + refusals.push((key, without_trace(refused.body))); + } + for (key, body) in &refusals { + assert_eq!(body, &refusals[0].1, "{key} answers differently"); + } + assert_eq!( + entity_count(&database, ®istry, "person").await, + people_before + ); + assert_eq!( + action_counts(&database, ®istry).await.without_audit(), + before.without_audit() + ); + + // Inside the boundary nothing changes: a guard the caller cannot read + // fails with the generic 412, one it reads names the guard, and a passing + // guard applies the create. + let unreadable_guard = invoke_guarded_create( + &app, + registrar.clone(), + "file-person-uncoded", + "in-hidden-guard", + HOUSEHOLD_ID, + "zone-a", + &conditions[&("registrar", "file-person-uncoded")], + ) + .await; + assert_eq!(unreadable_guard.status, StatusCode::PRECONDITION_FAILED); + assert_eq!(unreadable_guard.body["code"], "precondition.failed"); + let readable_guard = invoke_guarded_create( + &app, + reader.clone(), + "file-person-uncoded", + "in-read-guard", + HOUSEHOLD_ID, + "zone-a", + &conditions[&("reader", "file-person-uncoded")], + ) + .await; + assert_eq!(readable_guard.status, StatusCode::PRECONDITION_FAILED); + assert_eq!(readable_guard.body["code"], "action.guard-failed"); + let applied = invoke_guarded_create( + &app, + registrar, + "file-person-open", + "in-open", + HOUSEHOLD_ID, + "zone-a", + &conditions[&("registrar", "file-person-open")], + ) + .await; + assert_eq!(applied.status, StatusCode::OK, "{}", applied.body); + assert_eq!( + entity_count(&database, ®istry, "person").await, + people_before + 1 + ); + database.cleanup().await; +} diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index c3468c6a0f..e1efb0d9d8 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -2118,8 +2118,20 @@ async fn admitted_apply_outside_the_callers_write_boundary_persists_nothing() { } source["actions"]["correct-name"]["plan"]["effects"][0]["set"] = json!({"jurisdiction":{"fromInput":"value"}}); - let fixture = - client_http::ClientFixture::start(compile(source), caller(&["zone-a", "zone-b"])).await; + let registry = compile(source); + let openapi: Value = serde_json::from_slice( + ®istry + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + ) + .unwrap(); + let examples = &openapi["paths"]["/v1/proposals/{proposal_id}/apply"]["post"]["responses"] + ["403"]["content"]["application/problem+json"]["examples"]; + assert!(examples.get("write.outside-boundary").is_some()); + assert!(examples.get("profile.not-authorized").is_some()); + let fixture = client_http::ClientFixture::start(registry, caller(&["zone-a", "zone-b"])).await; let client = &fixture.http.client; let draft = start(&fixture, "zone-b", "boundary-start").await; let submitted = client diff --git a/crates/registry-breg/tests/postgres_tls.rs b/crates/registry-breg/tests/postgres_tls.rs index 51235ae17d..73ae1c5380 100644 --- a/crates/registry-breg/tests/postgres_tls.rs +++ b/crates/registry-breg/tests/postgres_tls.rs @@ -2,9 +2,12 @@ #![cfg(feature = "postgres-tls-test")] -use std::{env, fs, str::FromStr, time::Duration}; +use std::{env, fs, os::unix::fs::PermissionsExt as _, str::FromStr, time::Duration}; -use registry_breg::postgres::{ConnectionConfig, DatabaseConnectionCause, PoolBounds}; +use base64::Engine as _; +use registry_breg::postgres::{ConnectionConfig, DatabaseConnectionCause}; +use registry_breg::runtime_config::load_runtime_config_without_package_root; +use registry_platform_config::{DeclaredPosture, Posture, PostureSource}; use tokio::{net::TcpStream, time::timeout}; use tokio_postgres::{config::Host, Config}; @@ -40,6 +43,53 @@ fn tcp_connection_identity(url: &str) -> (String, u16, Option, Option ConnectionConfig { + let directory = tempfile::tempdir().expect("private runtime fixture"); + let directory = directory.path().canonicalize().unwrap(); + let mut url = url::Url::parse(input).expect("TLS test database URL must parse"); + let user = url.username().to_owned(); + let retained: Vec<_> = url + .query_pairs() + .filter(|(key, _)| key != "sslmode") + .map(|(key, value)| (key.into_owned(), value.into_owned())) + .collect(); + url.query_pairs_mut() + .clear() + .extend_pairs(retained) + .append_pair("sslmode", "verify-full"); + let write = |name, contents: &str| { + let path = directory.join(name); + fs::write(&path, contents).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + path + }; + write("runtime-database-url", url.as_str()); + let ca = base64::engine::general_purpose::STANDARD.encode(ca_der); + write( + "database-ca", + &format!("-----BEGIN CERTIFICATE-----\n{ca}\n-----END CERTIFICATE-----\n"), + ); + let runtime = include_str!("../../../products/breg/examples/minimal/runtime.example.yaml") + .replace("/var/lib/breg/secrets", directory.to_str().unwrap()) + .replace(" runtime: breg_runtime", &format!(" runtime: {user}")) + .replace( + "database:\n", + "database:\n caBundleRef: secret:file/database-ca\n", + ); + let path = write("runtime.yaml", &runtime); + let config = load_runtime_config_without_package_root( + &path, + DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Default, + }, + ) + .expect("load the BReg runtime configuration"); + config + .runtime_database_connection_config() + .expect("parse the verified TLS URL and configured CA") +} + #[tokio::test] async fn custom_ca_requires_a_trusted_tls_server() { let database_url = required_env("BREG_TEST_TLS_DATABASE_URL"); @@ -51,20 +101,9 @@ async fn custom_ca_requires_a_trusted_tls_server() { "the wrong-root fixture must differ from the trusted CA" ); - let bounds = PoolBounds::new( - 1, - Duration::from_secs(5), - Duration::from_secs(5), - Duration::from_secs(5), - ) - .expect("TLS test pool bounds are valid"); - let trusted = ConnectionConfig::require_tls_with_custom_ca(&database_url, &trusted_ca, bounds) - .expect("trusted CA DER and database URL must parse"); - assert_eq!( - format!("{trusted:?}"), - format!("ConnectionConfig {{ tls_policy: RequireCustomCa, pool_bounds: {bounds:?}, .. }}"), - "Debug must not disclose the URL or CA certificate" - ); + let trusted = runtime_connection(&database_url, &trusted_ca); + assert!(format!("{trusted:?}").contains("RequireCustomCa")); + assert!(!format!("{trusted:?}").contains(&database_url)); let trusted_pool = trusted.build_pool().expect("TLS pool must build"); trusted_pool @@ -113,9 +152,7 @@ async fn custom_ca_requires_a_trusted_tls_server() { .expect("hostname-mismatch URL must reach the PostgreSQL listener"); drop(mismatch_tcp); - let hostname_mismatch = - ConnectionConfig::require_tls_with_custom_ca(&hostname_mismatch_url, &trusted_ca, bounds) - .expect("trusted CA and hostname-mismatch URL must parse"); + let hostname_mismatch = runtime_connection(&hostname_mismatch_url, &trusted_ca); let hostname_mismatch_pool = hostname_mismatch .build_pool() .expect("hostname-mismatch pool must build"); @@ -127,8 +164,7 @@ async fn custom_ca_requires_a_trusted_tls_server() { "a trusted chain with a hostname absent from the certificate SAN is a TLS refusal" ); - let untrusted = ConnectionConfig::require_tls_with_custom_ca(&database_url, &wrong_ca, bounds) - .expect("the wrong-root fixture must still be valid DER"); + let untrusted = runtime_connection(&database_url, &wrong_ca); let untrusted_pool = untrusted.build_pool().expect("wrong-root pool must build"); assert_eq!( untrusted_pool.startup_connection_cause_for_test().await, diff --git a/crates/registry-bregctl/src/provision.rs b/crates/registry-bregctl/src/provision.rs index a92bdb44e5..ab6a087df4 100644 --- a/crates/registry-bregctl/src/provision.rs +++ b/crates/registry-bregctl/src/provision.rs @@ -16,9 +16,10 @@ use registry_breg::runtime_config::{ load_runtime_config_without_package_root, RuntimeConfig, RuntimeConfigError, RUNTIME_CONFIG_KIND, }; -use registry_platform_config::DatabaseMember; +use registry_platform_config::{DatabaseMember, SecretError}; use registry_platform_provision::{ - provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, Spatial, + provision_transport, read_ca_bundle, secret_refusal, url_not_text_refusal, ProductDatabase, + ProvisionInput, SchemaLayout, Spatial, }; use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; @@ -29,6 +30,17 @@ fn refused(code: &str, path: &str, message: String, action: &str) -> Vec Vec { + in_runtime_file(secret_refusal("database", member, error)) +} + +/// A shared provision refusal, as a finding about the runtime file. +fn in_runtime_file(mut diagnostic: Diagnostic) -> Vec { + diagnostic.artifact = Some(RUNTIME_CONFIG_KIND.to_owned()); + vec![diagnostic] +} + fn runtime_file_refused(file: &Path, error: &RuntimeConfigError) -> Vec { let diagnostics = error.diagnostics(Some(file)); if diagnostics.is_empty() { @@ -84,51 +96,38 @@ pub(crate) fn load( })?; let config = load_runtime_config_without_package_root(&absolute, posture) .map_err(|error| runtime_file_refused(&absolute, &error))?; - // The same checks `apply` makes: each URL parses and logs in as the role - // the file names for it. - config - .migration_database_connection_config() - .and_then(|_| config.runtime_database_connection_config()) - .map_err(|error| runtime_file_refused(&absolute, &error))?; let secrets = config .secret_resolver() .map_err(|error| runtime_file_refused(&absolute, &error))?; + // Each member is read first, so a refused secret is reported at its member + // with the shared code rather than by the connection check below. let resolve = |member: DatabaseMember, reference| { - let read = member.read_reference(&secrets, reference); - read.map_err(|error| { - refused( - "config.refused", - &format!("/database/{member}"), - registry_platform_config::describe_secret_failure( - &format!("database.{member}"), - reference.as_str(), - &error, - ), - error.suggested_action(), - ) - }) + member + .read_reference(&secrets, reference) + .map_err(|error| secret_refused(member, &error)) }; 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())) - .map_err(|_| { - refused( - "config.refused", - &format!("/database/{member}"), - format!("database.{member} is not UTF-8 text"), - "Put a PostgreSQL URL in the secret, then run provision again.", - ) - }) + .map_err(|_| in_runtime_file(url_not_text_refusal("database", member))) }; let database = config.database(); 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(DatabaseMember::CaBundle, reference)) - .transpose()? - .map(|secret| secret.expose_secret().to_vec()); + .map(|reference| { + read_ca_bundle(&secrets, "database", reference.as_str()) + .map_err(|refused| in_runtime_file(*refused)) + }) + .transpose()?; + // The same checks `apply` makes: each URL parses and logs in as the role + // the file names for it. + config + .migration_database_connection_config() + .and_then(|_| config.runtime_database_connection_config()) + .map_err(|error| runtime_file_refused(&absolute, &error))?; let spatial = package .map(|package| spatial(&config, package)) .transpose()? diff --git a/crates/registry-bregctl/tests/provision_cli.rs b/crates/registry-bregctl/tests/provision_cli.rs index 2ae650c75d..22123e2627 100644 --- a/crates/registry-bregctl/tests/provision_cli.rs +++ b/crates/registry-bregctl/tests/provision_cli.rs @@ -16,7 +16,7 @@ const RUNTIME_PASSWORD: &str = "runtime-password-for-print-mode"; 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" + "Explicit production setting platform.posture.jwt-access-token at /authentication/oidc/issuers/primary/accessTokenType. This setting admits access tokens typed JWT. ID tokens stay refused.\n" ); } @@ -295,7 +295,10 @@ fn a_missing_runtime_url_secret_is_refused() { std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); assert_eq!( loader_refusal(&runtime), - ("breg.runtime.secret".to_owned(), String::new()) + ( + "platform.provision.secret-unavailable".to_owned(), + "/database/runtimeUrlRef".to_owned() + ) ); } @@ -307,7 +310,10 @@ fn a_runtime_url_that_is_not_utf8_is_refused() { std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); assert_eq!( loader_refusal(&runtime), - ("breg.runtime.secret".to_owned(), String::new()) + ( + "platform.provision.secret-value-invalid".to_owned(), + "/database/runtimeUrlRef".to_owned() + ) ); } @@ -326,6 +332,29 @@ fn a_url_user_that_differs_from_the_runtime_role_is_refused() { assert_eq!(path, "/database"); } +#[test] +fn a_ca_bundle_without_a_certificate_is_refused_in_print_mode() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let bundle = directory.path().join("secrets/database-ca.pem"); + std::fs::write(&bundle, "a bundle that holds no certificate\n").unwrap(); + std::fs::set_permissions(&bundle, std::fs::Permissions::from_mode(0o644)).unwrap(); + let text = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = text.replace( + " pool:\n", + " caBundleRef: secret:file/database-ca.pem\n pool:\n", + ); + assert_ne!(text, with_ca, "the runtime file gains the CA reference"); + std::fs::write(&runtime, with_ca).unwrap(); + assert_eq!( + loader_refusal(&runtime), + ( + "platform.provision.ca-bundle-no-certificate".to_owned(), + "/database/caBundleRef".to_owned() + ) + ); +} + #[test] fn a_missing_ca_bundle_is_refused() { let directory = scratch(); @@ -339,7 +368,10 @@ fn a_missing_ca_bundle_is_refused() { std::fs::write(&runtime, with_ca).unwrap(); assert_eq!( loader_refusal(&runtime), - ("breg.runtime.secret".to_owned(), String::new()) + ( + "platform.provision.secret-unavailable".to_owned(), + "/database/caBundleRef".to_owned() + ) ); } diff --git a/crates/registry-casework-client-node/__test__/facade.test-d.ts b/crates/registry-casework-client-node/__test__/facade.test-d.ts index 356d9099ae..59f9d259da 100644 --- a/crates/registry-casework-client-node/__test__/facade.test-d.ts +++ b/crates/registry-casework-client-node/__test__/facade.test-d.ts @@ -72,7 +72,9 @@ void client.previewClockRecompute(token, 'administrator', recompute) void client.applyClockRecompute(token, 'administrator', 'recompute-1', { previewId: id }) const error = {} as CaseworkClientError const unknown: boolean = error.outcomeUnknown +const problemType: string | undefined = error.problemType void unknown +void problemType // @ts-expect-error WorkItem lifecycle was removed void client.listWorkItems(token, profile, {}) // @ts-expect-error generic source action execution was removed diff --git a/crates/registry-casework-client-node/__test__/facade.test.js b/crates/registry-casework-client-node/__test__/facade.test.js index a21a2c71fa..34d298b818 100644 --- a/crates/registry-casework-client-node/__test__/facade.test.js +++ b/crates/registry-casework-client-node/__test__/facade.test.js @@ -3,6 +3,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const http = require('node:http'); +const directResponses = require('../../registry-casework-client/tests/fixtures/direct-response-additions.json'); const POLICY_DIGEST = 'sha256:38ea436942f78766fc2db332c18e3ed545ec4e907d3386ec41b0c2eeb60e7f6c'; @@ -22,14 +23,7 @@ test('description accepts a development peer and ignores additive response membe 'content-type': 'application/json', traceparent: '00-0123456789abcdef0123456789abcdef-0123456789abcdef-01', }); - response.end(JSON.stringify({ - projectId: 'fixture', - policyVersion: 'v1', - queues: [], - reviewPolicies: [], - contextProviders: [], - futureMember: { safeToIgnore: true }, - })); + response.end(JSON.stringify(directResponses.description)); }); }); await listen(server); @@ -39,6 +33,11 @@ test('description accepts a development peer and ignores additive response membe const client = new CaseworkClient({ baseUrl: `http://127.0.0.1:${server.address().port}/` }); const description = await client.description('one-call-secret', 'staff'); assert.equal(description.value.projectId, 'fixture'); + assert.equal(description.value.futureMember, undefined); + assert.deepEqual(description.value.reviewPolicies[0].stages[0].asks, { + answerWithin: { hours: 1 }, + pauseClocks: true, + }); }); test('accepted-result binding diagnostics are bounded and precede token or HTTP effects', async () => { @@ -191,7 +190,7 @@ test('review task context uses the exact route and forwards the optional source source: 'professional-licences', type: 'change-request', id: 'correction-42', version: '1', digest: `sha256:${'a'.repeat(64)}`, }, - asks: [{"askId": "00000000-0000-4000-8000-000000000007", "taskId": "00000000-0000-0000-0000-000000000000", "text": "Why?", "wants": [{"kind": "answer"}], "askedAt": "2026-11-27T00:00:00Z", "state": "open", "answer": {"text": "source answer from BReg", "documents": [], "answeredAt": "2026-11-27T01:00:00Z"}}], + asks: directResponses.asks, requesterReference: 'correction-42', policy: { id: 'registry-correction', version: '1', digest: POLICY_DIGEST }, policyClosure: { @@ -231,7 +230,17 @@ test('review task context uses the exact route and forwards the optional source 'reviewer', ); - assert.deepEqual(result.value.asks[0].answer, {"text": "source answer from BReg", "documents": [], "answeredAt": "2026-11-27T01:00:00Z"}); + const [ask] = result.value.asks; + assert.deepEqual(ask.wants, [{ kind: 'answer' }, { kind: 'document' }]); + assert.equal(ask.answer.text, 'Synthetic answer'); + assert.equal(ask.answer.futureAnswerMember, undefined); + const [document] = ask.answer.documents; + assert.equal(document.id, 'document-1'); + assert.equal(document.byteSize, 42); + assert.equal(document.futureDocumentMember, undefined); + assert.deepEqual(document.download, { + method: 'GET', operation: 'read-document', accessProfile: 'reviewer', path: '/documents/document-1', + }); assert.equal(result.value.context.projection.displayReference, 'Correction 42'); assert.equal(observed.path, '/v1/review-tasks/00000000-0000-0000-0000-000000000000/context?accessProfile=staff'); assert.equal(observed.headers.authorization, 'Bearer one-call-secret'); @@ -586,8 +595,109 @@ test('absence list carries caller pagination and the next cursor', async (contex assert.equal(observed.headers['registry-review-profile'], undefined); }); +test('ask responses require their contract shapes', async context => { + const fixtures = require('../../registry-casework-client/tests/fixtures/ask-response-shapes.json'); + const { inspect } = require('node:util'); + const { CaseworkClient } = require('../client'); + for (const fixture of fixtures) { + await context.test(fixture.name, async subtest => { + let requests = 0; + const server = http.createServer((request, response) => { + requests += 1; + request.resume(); + request.on('end', () => { + response.writeHead(fixture.status, { + 'content-type': fixture.status === 200 ? 'application/json' : 'application/problem+json', + traceparent: '00-0123456789abcdef0123456789abcdef-0123456789abcdef-01', + ...fixture.headers, + }); + response.end(fixture.body); + }); + }); + await listen(server); + subtest.after(() => new Promise(resolve => server.close(resolve))); + const client = new CaseworkClient({ baseUrl: `http://127.0.0.1:${server.address().port}/` }); + const task = '00000000-0000-0000-0000-000000000001'; + const call = () => ({ + context: () => client.reviewTaskContext('fixture-token', 'staff', task), + ask: () => client.askApplicant('fixture-token', 'staff', task, 2, 'ask-1', { + text: 'Send the signed form.', wants: [{ kind: 'answer' }], + }), + policy: () => client.reviewPolicy('fixture-token', 'staff', 'review'), + policies: () => client.reviewPolicies('fixture-token', 'staff'), + description: () => client.description('fixture-token', 'staff'), + })[fixture.route](); + if (fixture.accepted) { + await call(); + } else { + await assert.rejects(call, error => { + assert.equal(error.status, fixture.status); + if (fixture.status === 400) { + assert.equal(error.kind, 'problem'); + assert.equal(error.validation.path, '$.remote-path-canary'); + assert.deepEqual(error.validation.allowed, ['remote-value-canary']); + assert.doesNotMatch(inspect(error), /remote-(path|value)-canary/); + } else { + assert.equal(error.kind, 'protocol'); + assert.equal(error.protocolFailure, 'body'); + if (fixture.route === 'ask') assert.equal(error.outcomeUnknown, true); + } + return true; + }); + } + assert.equal(requests, 1); + }); + } +}); + +test('direct and Review-backed problems share the raw HTTP contract', async (context) => { + const fixtures = require('../../registry-casework-client/tests/fixtures/problem-responses.json'); + const { inspect } = require('node:util'); + const { CaseworkClient } = require('../client'); + for (const fixture of fixtures) { + await context.test(fixture.name, async (subtest) => { + const server = http.createServer((request, response) => { + response.writeHead(fixture.status, { + 'content-type': 'application/problem+json', + traceparent: '00-0123456789abcdef0123456789abcdef-0123456789abcdef-01', + ...fixture.headers, + }); + response.end(fixture.body); + }); + await listen(server); + subtest.after(() => new Promise((resolve) => server.close(resolve))); + const client = new CaseworkClient({ baseUrl: `http://127.0.0.1:${server.address().port}/` }); + for (const [route, call] of [ + ['direct', () => client.description('fixture-token', 'requester')], + ['delegated', () => client.reviewResults('fixture-token', 'requester', {})], + ]) { + await assert.rejects(call, (error) => { + assert.equal(error.kind, fixture[route] ? 'problem' : 'protocol'); + assert.equal(error.status, fixture.status); + const diagnostic = `${error} ${inspect(error)} ${JSON.stringify(error)}`; + assert.doesNotMatch(diagnostic, /Synthetic future/); + if (fixture[route]) { + const body = JSON.parse(fixture.body); + assert.equal(error.code, body.code); + assert.equal(error.problemType, body.type); + assert.equal(error.traceId, body.traceId); + assert.equal(error.outcomeUnknown, fixture.status >= 500); + assert.equal(error.validation, undefined); + if (body.code !== 'request.invalid') { + assert.equal(error.detail, undefined); + assert.ok(!diagnostic.includes(body.code)); + assert.ok(!diagnostic.includes(body.type)); + } + } + return true; + }); + } + }); + } +}); + test('unknown future problem code stays a problem without recovery metadata', async (context) => { - const server = problemServer('review.future-safe'); + const server = problemServer(directResponses.problem); await listen(server); context.after(() => new Promise((resolve) => server.close(resolve))); @@ -599,9 +709,14 @@ test('unknown future problem code stays a problem without recovery metadata', as (error) => { assert.equal(error.kind, 'problem'); assert.equal(error.code, 'review.future-safe'); + assert.equal(error.problemType, directResponses.problem.type); + assert.equal(error.status, directResponses.problem.status); + assert.equal(error.traceId, directResponses.problem.traceId); assert.equal(error.detail, undefined); assert.equal(error.message, 'Registry Casework refused the request'); assert.equal(error.originalAttemptId, undefined); + assert.equal(error.validation, undefined); + assert.equal(error.outcomeUnknown, false); return true; }, ); @@ -722,23 +837,15 @@ function listen(server) { }); } -function problemServer(code, extraHeaders = {}) { +function problemServer(problem) { return http.createServer((request, response) => { request.resume(); request.on('end', () => { - response.writeHead(409, { + response.writeHead(problem.status, { 'content-type': 'application/problem+json', traceparent: '00-0123456789abcdef0123456789abcdef-0123456789abcdef-01', - ...extraHeaders, }); - response.end(fixtureStringify({ - type: `https://id.registrystack.org/problems/registry-casework/${code.replaceAll('.', '/')}`, - title: code, - status: 409, - detail: 'Safe detail.', - code, - traceId: '0123456789abcdef0123456789abcdef', - })); + response.end(JSON.stringify(problem)); }); }); } diff --git a/crates/registry-casework-client-node/client.d.ts b/crates/registry-casework-client-node/client.d.ts index 6056b0bcbb..baec2f4f4d 100644 --- a/crates/registry-casework-client-node/client.d.ts +++ b/crates/registry-casework-client-node/client.d.ts @@ -200,6 +200,7 @@ export class CaseworkClientError extends Error { */ readonly outcomeUnknown: boolean readonly code?: CaseworkProblemCode + readonly problemType?: string readonly detail?: string readonly status?: SafeInteger readonly traceId?: string diff --git a/crates/registry-casework-client-node/client.js b/crates/registry-casework-client-node/client.js index ddc2380134..7d60ada4f3 100644 --- a/crates/registry-casework-client-node/client.js +++ b/crates/registry-casework-client-node/client.js @@ -13,8 +13,19 @@ class CaseworkClientError extends Error { this.name = 'CaseworkClientError'; this.kind = envelope.kind; this.outcomeUnknown = envelope.outcomeUnknown === true; - for (const field of ['code', 'detail', 'status', 'traceId', 'validation', 'transportKind', 'protocolFailure']) { - if (envelope[field] !== undefined && envelope[field] !== null) this[field] = envelope[field]; + for (const field of ['code', 'problemType', 'detail', 'status', 'traceId', 'validation', 'transportKind', 'protocolFailure']) { + if (envelope[field] === undefined || envelope[field] === null) continue; + // Keep remote validation metadata and future identifiers available + // without putting them in default inspection or JSON output. + if (field === 'validation' || (envelope.unknownProblemCode && (field === 'code' || field === 'problemType'))) { + Object.defineProperty(this, field, { + value: envelope[field], + writable: true, + configurable: true, + }); + } else { + this[field] = envelope[field]; + } } } } diff --git a/crates/registry-casework-client-node/src/lib.rs b/crates/registry-casework-client-node/src/lib.rs index 582ae3adab..b3044940be 100644 --- a/crates/registry-casework-client-node/src/lib.rs +++ b/crates/registry-casework-client-node/src/lib.rs @@ -11,12 +11,12 @@ use napi_derive::napi; use registry_casework_client::{ AbsenceInput, AbsencesQuery, AssignmentRequest, BootstrapDirectoryRequest, CaseworkAuth, CaseworkClient as CoreClient, CaseworkClientConfig as CoreConfig, CaseworkClientError, - DelegateRequest, DirectoryTargetsQuery, HolidaySetRevisionInput, OwnReviewDecisionQuery, - ReviewCancelRequest, ReviewCaseloadApplyRequest, ReviewCaseloadMoveRequest, - ReviewClockRecomputeApplyRequest, ReviewClockRecomputeRequest, ReviewCreateRequest, - ReviewNoteRequest, ReviewPageQuery, ReviewRequestAccepted, ReviewResultResponse, - ReviewStaffingQuery, ReviewTaskAskRequest, ReviewTaskDecisionRequest, ReviewTaskDraftInput, - SubmissionDigest, SupervisoryReviewTaskQuery, + CaseworkProblemCode, DelegateRequest, DirectoryTargetsQuery, HolidaySetRevisionInput, + OwnReviewDecisionQuery, ReviewCancelRequest, ReviewCaseloadApplyRequest, + ReviewCaseloadMoveRequest, ReviewClockRecomputeApplyRequest, ReviewClockRecomputeRequest, + ReviewCreateRequest, ReviewNoteRequest, ReviewPageQuery, ReviewRequestAccepted, + ReviewResultResponse, ReviewStaffingQuery, ReviewTaskAskRequest, ReviewTaskDecisionRequest, + ReviewTaskDraftInput, SubmissionDigest, SupervisoryReviewTaskQuery, }; use serde::Serialize; use serde_json::{json, Value}; @@ -1574,6 +1574,7 @@ fn client_error(error: CaseworkClientError) -> NapiError { CaseworkClientError::Problem { status, code, + problem_type, detail, trace_id, validation, @@ -1585,6 +1586,8 @@ fn client_error(error: CaseworkClientError) -> NapiError { "kind": "problem", "status": status, "code": code.code(), + "problemType": problem_type, + "unknownProblemCode": matches!(code, CaseworkProblemCode::Unknown(_)), "traceId": trace_id, "validation": validation.map(|validation| json!({ "path": validation.path, diff --git a/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi b/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi index fdcd3cd411..f3cc80045a 100644 --- a/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi +++ b/crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi @@ -417,6 +417,7 @@ class ValidationDetail(TypedDict): class CaseworkClientError(Exception): kind: CaseworkErrorKind code: CaseworkProblemCode | None + problem_type: str | None detail: str | None status: SafeInteger | None trace_id: str | None diff --git a/crates/registry-casework-client-py/src/lib.rs b/crates/registry-casework-client-py/src/lib.rs index 44c4d701e9..30bf51b8f0 100644 --- a/crates/registry-casework-client-py/src/lib.rs +++ b/crates/registry-casework-client-py/src/lib.rs @@ -44,6 +44,7 @@ struct MappedError { kind: &'static str, message: String, code: Option, + problem_type: Option, detail: Option, status: Option, trace_id: Option, @@ -62,6 +63,9 @@ fn to_py_err(py: Python<'_>, mapped: MappedError) -> PyErr { instance .setattr("code", mapped.code) .expect("fresh exception accepts attributes"); + instance + .setattr("problem_type", mapped.problem_type) + .expect("fresh exception accepts attributes"); instance .setattr("detail", mapped.detail) .expect("fresh exception accepts attributes"); @@ -150,12 +154,14 @@ fn client_error(py: Python<'_>, error: RustClientError) -> PyErr { RustClientError::Problem { status, code, + problem_type, detail, trace_id, validation, } => { mapped.status = Some(status); mapped.code = Some(code.code().to_owned()); + mapped.problem_type = problem_type; mapped.detail = detail; mapped.trace_id = trace_id; mapped.validation = validation.map(|value| { diff --git a/crates/registry-casework-client-py/tests/python/test_native_requests.py b/crates/registry-casework-client-py/tests/python/test_native_requests.py index 76d1dc0a3e..abbaa16a09 100644 --- a/crates/registry-casework-client-py/tests/python/test_native_requests.py +++ b/crates/registry-casework-client-py/tests/python/test_native_requests.py @@ -4,6 +4,7 @@ import threading import unittest from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path from urllib.parse import parse_qs, urlsplit from bootstrap import ensure_built @@ -23,11 +24,21 @@ POLICY_DIGEST = ( "sha256:38ea436942f78766fc2db332c18e3ed545ec4e907d3386ec41b0c2eeb60e7f6c" ) +DIRECT_RESPONSES = json.loads(( + Path(__file__).resolve().parents[3] + / "registry-casework-client/tests/fixtures/direct-response-additions.json" +).read_text(encoding="utf-8")) + +PROBLEM_RESPONSES = json.loads(( + Path(__file__).resolve().parents[3] + / "registry-casework-client/tests/fixtures/problem-responses.json" +).read_text(encoding="utf-8")) class _Handler(BaseHTTPRequestHandler): observations: list[dict[str, str]] = [] review_feed_responses: list[dict] = [] + problem_response: dict | None = None def do_GET(self) -> None: # noqa: N802 parts = urlsplit(self.path) @@ -43,6 +54,8 @@ def do_GET(self) -> None: # noqa: N802 "source_profile": self.headers.get("registry-source-profile", ""), "source_authorization": self.headers.get("registry-source-authorization", ""), }) + if self.respond_raw_fixture(): + return if f"cursor={EXPIRED_CURSOR}" in self.path: self.respond_problem( "cursor.expired", @@ -132,7 +145,7 @@ def do_GET(self) -> None: # noqa: N802 "version": "1", "digest": f"sha256:{'a' * 64}", }, - "asks": [{'askId': '00000000-0000-4000-8000-000000000007', 'taskId': '00000000-0000-4000-8000-000000000001', 'text': 'Why?', 'wants': [{'kind': 'answer'}], 'askedAt': '2026-11-27T00:00:00Z', 'state': 'open', 'answer': {'text': 'source answer from BReg', 'documents': [], 'answeredAt': '2026-11-27T01:00:00Z'}}], + "asks": [{**ask, "taskId": ITEM_ID} for ask in DIRECT_RESPONSES["asks"]], "requesterReference": "correction-42", "policy": { "id": "registry-correction", @@ -221,21 +234,35 @@ def do_GET(self) -> None: # noqa: N802 "items": [], "nextCursor": "absence-next", }) + elif parts.path == "/tenant/v1/casework" and query.get("accessProfile") == ["future"]: + problem = DIRECT_RESPONSES["problem"] + self.respond( + problem, status=problem["status"], media_type="application/problem+json", + traceparent=f"00-{problem['traceId']}-00f067aa0ba902b7-01", + ) else: - self.respond({ - "projectId": "fixture", - "policyVersion": "v1", - "queues": [], - "reviewPolicies": [], - "contextProviders": [], - "calendars": [], - "clocks": [], - "futureMember": {"safeToIgnore": True}, - }) + self.respond(DIRECT_RESPONSES["description"]) + + def respond_raw_fixture(self) -> bool: + if self.problem_response is None: + return False + fixture = self.problem_response + body = fixture["body"].encode("utf-8") + self.send_response(fixture["status"]) + self.send_header("content-type", "application/json" if fixture["status"] == 200 else "application/problem+json") + self.send_header("traceparent", "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01") + self.send_header("content-length", str(len(body))) + for name, value in fixture["headers"].items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(body) + return True def do_POST(self) -> None: # noqa: N802 length = int(self.headers.get("content-length", "0")) body = json.loads(self.rfile.read(length)) + if self.respond_raw_fixture(): + return parts = urlsplit(self.path) query = parse_qs(parts.query) self.observations.append({ @@ -333,13 +360,14 @@ def respond( value: object, status: int = 200, media_type: str = "application/json", + traceparent: str = TRACEPARENT, ) -> None: value = normalized_fixture(value) body = json.dumps(value).encode() self.send_response(status) self.send_header("content-type", media_type) self.send_header("cache-control", "no-store") - self.send_header("traceparent", TRACEPARENT) + self.send_header("traceparent", traceparent) self.send_header("content-length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -420,10 +448,98 @@ def test_separate_human_source_credential_is_explicit_and_not_retained(self) -> def test_description_ignores_additive_response_members(self) -> None: description = self.client.description("staff-token", "staff") self.assertEqual(description["value"]["projectId"], "fixture") + self.assertNotIn("futureMember", description["value"]) + self.assertEqual( + description["value"]["reviewPolicies"][0]["stages"][0]["asks"], + {"answerWithin": {"hours": 1}, "pauseClocks": True}, + ) self.assertEqual(_Handler.observations[0]["access_profile"], "staff") self.assertEqual(_Handler.observations[0]["profile"], "") self.assertEqual(_Handler.observations[0]["review_profile"], "") + def test_ask_responses_require_their_contract_shapes(self) -> None: + fixtures = json.loads(( + Path(__file__).resolve().parents[3] + / "registry-casework-client/tests/fixtures/ask-response-shapes.json" + ).read_text(encoding="utf-8")) + self.addCleanup(setattr, _Handler, "problem_response", None) + task = "00000000-0000-0000-0000-000000000001" + for fixture in fixtures: + _Handler.problem_response = fixture + route = fixture["route"] + with self.subTest(fixture=fixture["name"]): + call = { + "policy": lambda: self.client.review_policy("fixture-token", "staff", "review"), + "policies": lambda: self.client.review_policies("fixture-token", "staff"), + "description": lambda: self.client.description("fixture-token", "staff"), + "context": lambda: self.client.review_task_context("fixture-token", "staff", task), + "ask": lambda: self.client.ask_applicant( + "fixture-token", "staff", task, 2, "ask-1", + {"text": "Send the signed form.", "wants": [{"kind": "answer"}]}, + ), + }[route] + if fixture["accepted"]: + call() + continue + with self.assertRaises(CaseworkClientError) as raised: + call() + error = raised.exception + self.assertEqual(error.status, fixture["status"]) + if fixture["status"] == 400: + self.assertEqual(error.kind, "problem") + self.assertEqual(error.validation["path"], "$.remote-path-canary") + self.assertEqual(error.validation["allowed"], ["remote-value-canary"]) + self.assertNotIn("remote-path-canary", repr(error)) + self.assertNotIn("remote-value-canary", repr(error)) + else: + self.assertEqual(error.kind, "protocol") + self.assertEqual(error.protocol_failure, "body") + if route == "ask": + self.assertTrue(error.outcome_unknown) + + def test_direct_and_review_problem_boundaries_share_raw_http_fixtures(self) -> None: + self.addCleanup(setattr, _Handler, "problem_response", None) + for fixture in PROBLEM_RESPONSES: + _Handler.problem_response = fixture + for route, call in ( + ("direct", self.client.description), + ("delegated", self.client.review_results), + ): + with self.subTest(fixture=fixture["name"], route=route): + with self.assertRaises(CaseworkClientError) as raised: + call("fixture-token", "requester") + error = raised.exception + self.assertEqual(error.kind, "problem" if fixture[route] else "protocol") + self.assertEqual(error.status, fixture["status"]) + diagnostic = f"{error!s} {error!r}" + self.assertNotIn("Synthetic future", diagnostic) + if fixture[route]: + body = json.loads(fixture["body"]) + self.assertEqual(error.code, body["code"]) + self.assertEqual(error.problem_type, body["type"]) + self.assertEqual(error.trace_id, body["traceId"]) + self.assertEqual(error.outcome_unknown, fixture["status"] >= 500) + self.assertIsNone(error.validation) + if body["code"] != "request.invalid": + self.assertIsNone(error.detail) + self.assertNotIn(body["code"], diagnostic) + self.assertNotIn(body["type"], diagnostic) + + def test_description_preserves_unknown_problem_identifiers(self) -> None: + with self.assertRaises(CaseworkClientError) as raised: + self.client.description("staff-token", "future") + error = raised.exception + problem = DIRECT_RESPONSES["problem"] + self.assertEqual(error.kind, "problem") + self.assertEqual(error.problem_type, problem["type"]) + self.assertEqual(error.code, problem["code"]) + self.assertEqual(error.status, problem["status"]) + self.assertEqual(error.trace_id, problem["traceId"]) + self.assertIsNone(error.detail) + self.assertIsNone(error.validation) + self.assertFalse(error.outcome_unknown) + self.assertEqual(str(error), "Registry Casework refused the request") + def test_omitted_profile_sends_no_access_profile_query_or_header(self) -> None: description = self.client.description("staff-token") self.assertEqual(description["value"]["projectId"], "fixture") @@ -495,7 +611,18 @@ def test_review_task_context_uses_exact_route_and_source_profile(self) -> None: context["value"]["context"]["projection"]["displayReference"], "Correction 42", ) - self.assertEqual(context["value"]["asks"][0]["answer"], {'text': 'source answer from BReg', 'documents': [], 'answeredAt': '2026-11-27T01:00:00Z'}) + ask = context["value"]["asks"][0] + self.assertEqual(ask["wants"], [{"kind": "answer"}, {"kind": "document"}]) + self.assertEqual(ask["answer"]["text"], "Synthetic answer") + self.assertNotIn("futureAnswerMember", ask["answer"]) + document = ask["answer"]["documents"][0] + self.assertEqual(document["id"], "document-1") + self.assertEqual(document["byteSize"], 42) + self.assertNotIn("futureDocumentMember", document) + self.assertEqual(document["download"], { + "method": "GET", "operation": "read-document", "accessProfile": "reviewer", + "path": "/documents/document-1", + }) observation = _Handler.observations[0] self.assertEqual( observation["route"], f"/tenant/v1/review-tasks/{ITEM_ID}/context" diff --git a/crates/registry-casework-client/src/client.rs b/crates/registry-casework-client/src/client.rs index 087ed6cd46..a9d780829d 100644 --- a/crates/registry-casework-client/src/client.rs +++ b/crates/registry-casework-client/src/client.rs @@ -1,3 +1,4 @@ +use crate::error::ProblemSource; use crate::PeerPolicy; use registry_casework_core::DirectoryTeamUpdateRequest; use std::fmt; @@ -16,9 +17,9 @@ use registry_casework_core::{ ReviewStaffingQuery, ReviewTask, ReviewTaskContext, ReviewTaskContextData, ReviewTaskDraft, ReviewTaskDraftInput, ReviewTaskMarker, ReviewTaskPage, ReviewTaskState, ReviewValidationError, ReviewValidationReason, SupervisoryReviewTaskPage, ACCESS_PROFILE_QUERY_PARAM, - CASEWORK_PROBLEM_TYPE_BASE, DIRECTORY_TARGETS_PATH, IDEMPOTENCY_KEY_HEADER, - MAXIMUM_CASEWORK_IDEMPOTENCY_KEY_BYTES, MAXIMUM_CASEWORK_PROFILE_BYTES, SOURCE_PROFILE_HEADER, - VALIDATION_ALLOWED_HEADER, VALIDATION_PATH_HEADER, VALIDATION_REASON_HEADER, + DIRECTORY_TARGETS_PATH, IDEMPOTENCY_KEY_HEADER, MAXIMUM_CASEWORK_IDEMPOTENCY_KEY_BYTES, + MAXIMUM_CASEWORK_PROFILE_BYTES, SOURCE_PROFILE_HEADER, VALIDATION_ALLOWED_HEADER, + VALIDATION_PATH_HEADER, VALIDATION_REASON_HEADER, }; use registry_platform_httpsec::{response_trace_id, ProblemDocument}; use registry_platform_httputil::client::{ @@ -1862,19 +1863,14 @@ impl CaseworkClient { { return protocol(status, CaseworkProtocolFailure::Problem, trace_id); } - let code = CaseworkProblemCode::parse(&document.code); - let expected_text = code.expected_text(); - if document.type_uri - != format!( - "{CASEWORK_PROBLEM_TYPE_BASE}{}", - code.code().replace('.', "/") - ) - || code - .expected_status() - .is_some_and(|expected| expected != status.as_u16()) - { + let Some(code) = CaseworkProblemCode::checked( + status.as_u16(), + &document.code, + &document.type_uri, + ProblemSource::Casework, + ) else { return protocol(status, CaseworkProtocolFailure::Problem, trace_id); - } + }; if !original_attempt_values.is_empty() { return protocol(status, CaseworkProtocolFailure::Problem, trace_id); } @@ -1903,24 +1899,24 @@ impl CaseworkClient { }, _ => return protocol(status, CaseworkProtocolFailure::Problem, trace_id), }; - Some(ReviewValidationError { + Some(Box::new(ReviewValidationError { path: path.to_owned(), reason, allowed: allowed.into_boxed_slice(), - }) + })) } _ => return protocol(status, CaseworkProtocolFailure::Problem, trace_id), }; if validation.is_none() && !validation_allowed_values.is_empty() { return protocol(status, CaseworkProtocolFailure::Problem, trace_id); } - CaseworkClientError::Problem { - status: status.as_u16(), + CaseworkClientError::validated_problem( + status.as_u16(), code, - detail: expected_text.map(|(_, detail)| detail.to_owned()), - trace_id, + document.type_uri, + document.trace_id.as_str().to_owned(), validation, - } + ) } } diff --git a/crates/registry-casework-client/src/error.rs b/crates/registry-casework-client/src/error.rs index 5716cb0bdf..487b9686f8 100644 --- a/crates/registry-casework-client/src/error.rs +++ b/crates/registry-casework-client/src/error.rs @@ -1,4 +1,6 @@ -use registry_casework_core::{ReviewValidationError, ReviewValidationReason}; +use registry_casework_core::{ + ReviewValidationError, ReviewValidationReason, CASEWORK_PROBLEM_TYPE_BASE, +}; use registry_casework_core::{ ABSENCE_COVER_CYCLE_PROBLEM, ABSENCE_INVALID_PERIOD_PROBLEM, ABSENCE_OVERLAP_PROBLEM, ABSENCE_SELF_COVER_PROBLEM, ACCESS_PROFILE_AMBIGUOUS_PROBLEM, AUTHENTICATION_REFUSED_PROBLEM, @@ -35,7 +37,13 @@ pub enum CaseworkProtocolFailure { Status, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, Copy)] +pub(crate) enum ProblemSource { + Casework, + Review, +} + +#[derive(Clone, PartialEq, Eq)] #[non_exhaustive] pub enum CaseworkProblemCode { AbsenceCoverCycle, @@ -247,6 +255,33 @@ impl CaseworkProblemCode { } } + pub(crate) fn checked( + status: u16, + value: &str, + type_uri: &str, + source: ProblemSource, + ) -> Option { + let code = Self::parse(value); + let expected_status = code.expected_status(); + if !(400..600).contains(&status) + || expected_status.is_some_and(|expected| expected != status) + { + return None; + } + // The shared Review reader validates other providers' identifiers. + // Apply the Casework binding to its own namespace and known codes. + if (matches!(source, ProblemSource::Casework) + || expected_status.is_some() + || type_uri.starts_with(CASEWORK_PROBLEM_TYPE_BASE)) + && (!valid_casework_problem_code(value) + || type_uri.strip_prefix(CASEWORK_PROBLEM_TYPE_BASE) + != Some(value.replace('.', "/").as_str())) + { + return None; + } + Some(code) + } + /// The one status Casework answers this code under, or `None` for a code /// this client does not recognize. #[must_use] @@ -468,6 +503,31 @@ impl CaseworkProblemCode { } } +/// Match the dotted code grammar in the Registry Stack identifier catalogue. +/// The exact derived type URI is bounded by the fixed prefix and this code. +fn valid_casework_problem_code(code: &str) -> bool { + code.len() <= 128 + && code.contains('.') + && code.split('.').all(|segment| { + segment + .as_bytes() + .first() + .is_some_and(u8::is_ascii_lowercase) + && segment.split('-').all(|word| { + !word.is_empty() + && word + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) + }) + }) +} + +impl fmt::Debug for CaseworkProblemCode { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, formatter) + } +} + impl fmt::Display for CaseworkProblemCode { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -477,7 +537,7 @@ impl fmt::Display for CaseworkProblemCode { } } -#[derive(Debug, Error)] +#[derive(Error)] #[non_exhaustive] pub enum CaseworkClientError { #[error( @@ -495,11 +555,12 @@ pub enum CaseworkClientError { Problem { status: u16, code: CaseworkProblemCode, + /// Validated Problem type URI for explicit machine access. + problem_type: Option, /// Curated human detail for a recognized, exactly validated problem. detail: Option, trace_id: Option, - - validation: Option, + validation: Option>, }, #[error("Registry Casework returned an invalid response")] Protocol { @@ -509,6 +570,49 @@ pub enum CaseworkClientError { }, } +impl fmt::Debug for CaseworkClientError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DevelopmentPeer => formatter.write_str("DevelopmentPeer"), + Self::Configuration { reason } => formatter + .debug_struct("Configuration") + .field("reason", reason) + .finish(), + Self::InvalidRequest { reason } => formatter + .debug_struct("InvalidRequest") + .field("reason", reason) + .finish(), + Self::Transport { kind } => formatter + .debug_struct("Transport") + .field("kind", kind) + .finish(), + Self::Problem { + status, + code, + detail, + trace_id, + .. + } => formatter + .debug_struct("Problem") + .field("status", status) + .field("code", code) + .field("detail", detail) + .field("trace_id", trace_id) + .finish_non_exhaustive(), + Self::Protocol { + status, + failure, + trace_id, + } => formatter + .debug_struct("Protocol") + .field("status", status) + .field("failure", failure) + .field("trace_id", trace_id) + .finish(), + } + } +} + impl CaseworkClientError { pub(crate) fn configuration(reason: &'static str) -> Self { Self::Configuration { reason } @@ -518,6 +622,23 @@ impl CaseworkClientError { Self::InvalidRequest { reason } } + pub(crate) fn validated_problem( + status: u16, + code: CaseworkProblemCode, + problem_type: String, + trace_id: String, + validation: Option>, + ) -> Self { + Self::Problem { + status, + detail: code.expected_text().map(|(_, detail)| detail.to_owned()), + code, + problem_type: Some(problem_type), + trace_id: Some(trace_id), + validation, + } + } + /// Classify a mutation failure for exact-key recovery decisions. /// /// `Ambiguous` exactly when [`Self::is_outcome_unknown`] holds, and @@ -612,6 +733,7 @@ impl CaseworkClientError { trace_id, }, ReviewClientError::Problem { status, problem } => { + let problem_type = problem.problem_type().to_owned(); let registry_review_client::ReviewProblem { code, title: _, @@ -619,18 +741,18 @@ impl CaseworkClientError { trace_id, validation, } = *problem; - let code = CaseworkProblemCode::parse(code.as_str()); - let expected_text = code.expected_text(); - if code - .expected_status() - .is_some_and(|expected| expected != status) - { + let Some(code) = CaseworkProblemCode::checked( + status, + code.as_str(), + &problem_type, + ProblemSource::Review, + ) else { return Self::Protocol { status, failure: CaseworkProtocolFailure::Problem, trace_id: Some(trace_id), }; - } + }; let validation = match validation { None => None, Some(validation) => { @@ -685,21 +807,14 @@ impl CaseworkClientError { } } }; - Some(ReviewValidationError { + Some(Box::new(ReviewValidationError { path: validation.path, reason, allowed: Box::default(), - }) + })) } }; - Self::Problem { - status, - code, - detail: expected_text.map(|(_, detail)| detail.to_owned()), - trace_id: Some(trace_id), - - validation, - } + Self::validated_problem(status, code, problem_type, trace_id, validation) } _ => Self::Protocol { status: 0, @@ -719,6 +834,7 @@ mod tests { let refusal = CaseworkClientError::Problem { status: 409, code: CaseworkProblemCode::ReviewSubmissionConflict, + problem_type: None, detail: None, trace_id: None, @@ -744,6 +860,7 @@ mod tests { CaseworkClientError::Problem { status, code, + problem_type: None, detail: None, trace_id: None, diff --git a/crates/registry-casework-client/src/task_assertion_source.rs b/crates/registry-casework-client/src/task_assertion_source.rs index 46f4995bdd..ea7427f0f0 100644 --- a/crates/registry-casework-client/src/task_assertion_source.rs +++ b/crates/registry-casework-client/src/task_assertion_source.rs @@ -356,6 +356,7 @@ mod tests { let error = assertion_error(CaseworkClientError::Problem { status, code: CaseworkProblemCode::Unknown("remote-private-canary".into()), + problem_type: None, detail: Some("remote-private-canary".into()), trace_id: Some("remote-private-canary".into()), validation: None, diff --git a/crates/registry-casework-client/src/wire.rs b/crates/registry-casework-client/src/wire.rs index 403f7418ae..2dac3d19c7 100644 --- a/crates/registry-casework-client/src/wire.rs +++ b/crates/registry-casework-client/src/wire.rs @@ -10,9 +10,106 @@ use std::{collections::BTreeMap, marker::PhantomData}; use registry_casework_core::ReviewPolicyClosure; -use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{ + de::{DeserializeOwned, IntoDeserializer}, + Deserialize, Deserializer, Serialize, Serializer, +}; use serde_json::Value; +// These readers run after duplicate-safe JSON parsing. Require the wire kind +// before Serde can normalize positional objects or externally tagged units. +#[derive(Serialize)] +#[serde(transparent)] +pub(crate) struct ResponseObject(T); + +impl<'de, T: DeserializeOwned> Deserialize<'de> for ResponseObject { + fn deserialize>(deserializer: D) -> Result { + let object = serde_json::Map::deserialize(deserializer)?; + serde_json::from_value(Value::Object(object)) + .map(Self) + .map_err(serde::de::Error::custom) + } +} + +fn deserialize_string_enum<'de, D, T>(deserializer: D) -> Result +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(String::deserialize(deserializer)?.into_deserializer()) +} + +fn deserialize_optional_string_enum<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer)? + .map(|value| T::deserialize(value.into_deserializer())) + .transpose() +} + +// A nullable member can still be required on the wire. An explicit reader +// prevents Serde from interpreting a missing member as None. +fn required_nullable<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::deserialize(deserializer) +} + +fn present_duration_unit<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + u32::deserialize(deserializer).map(Some) +} + +fn document_sha256<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let digest = String::deserialize(deserializer)?; + if digest.len() == 64 + && digest + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + { + Ok(digest) + } else { + Err(serde::de::Error::custom("invalid document digest")) + } +} + +fn download_method<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let method = String::deserialize(deserializer)?; + if method == "GET" { + Ok(method) + } else { + Err(serde::de::Error::custom("invalid download method")) + } +} + +fn download_identifier<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + if !value.trim().is_empty() && value.len() <= 128 && !value.chars().any(char::is_control) { + Ok(value) + } else { + Err(serde::de::Error::custom("invalid download identifier")) + } +} + +fn download_path<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let path = String::deserialize(deserializer)?; + if path.len() <= 8192 + && path.starts_with('/') + && !path.starts_with("//") + && !path.starts_with("/\\") + && !path.chars().any(char::is_control) + { + Ok(path) + } else { + Err(serde::de::Error::custom("invalid download path")) + } +} + pub(crate) trait ClientResponse: Sized { type Wire: serde::de::DeserializeOwned; @@ -58,7 +155,7 @@ macro_rules! response_wire { } impl ClientResponse for $response { - type Wire = Validated<$response, $wire>; + type Wire = Validated<$response, ResponseObject<$wire>>; fn from_wire(wire: Self::Wire) -> Self { wire.into_inner() @@ -183,6 +280,17 @@ struct RoutingRuleWire { queue: String, } +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewStageAsksPolicyWire { + #[serde(default, skip_serializing_if = "Option::is_none")] + answer_within: Option>, + #[serde(default, deserialize_with = "deserialize_string_enum")] + on_due: registry_casework_core::ReviewAskOnDue, + #[serde(default)] + pause_clocks: bool, +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ReviewStagePolicyWire { @@ -196,13 +304,11 @@ struct ReviewStagePolicyWire { required_approvals: u16, #[serde(default, skip_serializing_if = "Option::is_none")] outcomes: Option>, - #[serde(default)] + #[serde(default, deserialize_with = "deserialize_string_enum")] negative_decisions: registry_casework_core::ReviewNegativeDecisionMode, #[serde(default, skip_serializing_if = "Option::is_none")] - asks: Option, - #[serde(default)] + asks: Option>, exclude_initiator: bool, - #[serde(default)] exclude_previous_stage_reviewers: bool, } @@ -238,7 +344,7 @@ struct ReviewPolicyWire { context: ReviewContextPolicyWire, #[serde(default)] routing: Vec, - stages: Vec, + stages: Vec>, #[serde(default)] clocks: Vec, retention: ReviewRetentionPolicyWire, @@ -274,25 +380,37 @@ struct CalendarPolicyWire { #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct SubjectClockAnchorWire { - #[serde(rename = "type")] + #[serde(rename = "type", deserialize_with = "deserialize_string_enum")] kind: registry_casework_core::SubjectClockAnchorType, } #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct StageClockAnchorWire { - #[serde(rename = "type")] + #[serde(rename = "type", deserialize_with = "deserialize_string_enum")] kind: registry_casework_core::StageClockAnchorType, } #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ElapsedDurationWire { - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_duration_unit" + )] minutes: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_duration_unit" + )] hours: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_duration_unit" + )] days: Option, } @@ -345,12 +463,12 @@ struct ClockStepWire { enum ClockPolicyWire { Subject { id: String, - anchor: SubjectClockAnchorWire, - after: ElapsedDurationWire, + anchor: ResponseObject, + after: ResponseObject, }, Stage { id: String, - anchor: StageClockAnchorWire, + anchor: ResponseObject, calendar: String, after: WorkingDaysWire, due_time: String, @@ -367,10 +485,10 @@ response_wire!(DescriptionWire => registry_casework_core::Description { project_id: String, policy_version: String, queues: Vec, - review_policies: Vec, + review_policies: Vec>, context_providers: Vec, - #[serde(default)] calendars: Vec, - #[serde(default)] clocks: Vec, + calendars: Vec>, + clocks: Vec>, }); #[derive(Deserialize, Serialize)] @@ -580,7 +698,7 @@ enum ReviewTaskStateWire { #[derive(Deserialize)] struct HeldStateWire { - holder: IssuerPrincipalWire, + holder: ResponseObject, } impl<'de> Deserialize<'de> for ReviewTaskStateWire { @@ -602,9 +720,10 @@ impl<'de> Deserialize<'de> for ReviewTaskStateWire { let held = object .remove("held") .ok_or_else(|| serde::de::Error::custom("missing held review task state"))?; - let held: HeldStateWire = serde_json::from_value(held).map_err(serde::de::Error::custom)?; + let ResponseObject(held) = serde_json::from_value::>(held) + .map_err(serde::de::Error::custom)?; Ok(Self::Held { - holder: held.holder, + holder: held.holder.0, }) } } @@ -647,9 +766,9 @@ struct ReviewDecisionReceiptWire { } response_wire!(ReviewTaskWire => registry_casework_core::ReviewTask { - subject: SubjectBindingWire, + subject: ResponseObject, requester_reference: String, - deadline_at: Option>, + #[serde(deserialize_with = "required_nullable")] deadline_at: Option>, created_at: chrono::DateTime, #[serde(default)] display_reference: Option, task_id: uuid::Uuid, @@ -663,20 +782,28 @@ response_wire!(ReviewTaskWire => registry_casework_core::ReviewTask { #[serde(default)] staffing_diagnostic: Option, #[serde(default)] decided_by_caller: Option, #[serde(default)] decision_receipt: Option, - #[serde(default)] marker: Option, + #[serde(default, deserialize_with = "deserialize_optional_string_enum")] marker: Option, }); +#[derive(Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "kebab-case")] +enum ReviewAskWantWire { + Answer {}, + Document {}, +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ReviewAskWire { ask_id: uuid::Uuid, request_id: uuid::Uuid, - subject: SubjectBindingWire, + subject: ResponseObject, text: String, - wants: Vec, + wants: Vec>, asked_at: chrono::DateTime, #[serde(default, skip_serializing_if = "Option::is_none")] due_at: Option>, + #[serde(deserialize_with = "deserialize_string_enum")] state: registry_casework_core::ReviewAskState, #[serde(default, skip_serializing_if = "Option::is_none")] answered_at: Option>, @@ -687,33 +814,70 @@ struct ReviewAskWire { #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub(crate) struct ReviewTaskAskedWire { - task: ReviewTaskWire, - ask: ReviewAskWire, + task: ResponseObject, + ask: ResponseObject, } impl ClientResponse for registry_casework_core::ReviewTaskAsked { - type Wire = Validated; + type Wire = Validated>; fn from_wire(wire: Self::Wire) -> Self { wire.into_inner() } } +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewAnswerDownloadWire { + #[serde(deserialize_with = "download_method")] + method: String, + #[serde(deserialize_with = "download_identifier")] + operation: String, + #[serde(deserialize_with = "download_identifier")] + access_profile: String, + #[serde(deserialize_with = "download_path")] + path: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewAnswerDocumentWire { + id: String, + #[serde(deserialize_with = "document_sha256")] + sha256: String, + content_type: String, + byte_size: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + verification_status: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + download: Option>, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReviewContextAnswerWire { + #[serde(default, skip_serializing_if = "Option::is_none")] + text: Option, + documents: Vec>, + answered_at: chrono::DateTime, +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ReviewContextAskWire { ask_id: uuid::Uuid, task_id: uuid::Uuid, text: String, - wants: Vec, + wants: Vec>, asked_at: chrono::DateTime, #[serde(default, skip_serializing_if = "Option::is_none")] due_at: Option>, + #[serde(deserialize_with = "deserialize_string_enum")] state: registry_casework_core::ReviewAskState, #[serde(default, skip_serializing_if = "Option::is_none")] answered_at: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] - answer: Option, + answer: Option>, } #[derive(Deserialize, Serialize)] @@ -937,21 +1101,116 @@ response_wire!(ReviewClockRecomputeResultWire => registry_casework_core::ReviewC tasks: Vec, }); -// The closure digest covers the complete policy and dependency graph. Decode -// it strictly so an unknown governed member is never erased before `verify`. +// Decode the original governed object through the closed core type. Shape +// checks inspect the original JSON without projecting any digest-covered data. +#[derive(Serialize)] +#[serde(transparent)] +pub(crate) struct GovernedClosure(ReviewPolicyClosure); + +// These members can lose their original shape when the closed core supplies +// defaults or omits default values on serialization. +#[derive(Deserialize)] +struct GovernedInboxShape { + #[serde(rename = "defaultPageSize")] + _default_page_size: usize, + #[serde(rename = "maximumCandidateScan")] + _maximum_candidate_scan: usize, + #[serde(rename = "maximumSourceReads")] + _maximum_source_reads: usize, + #[serde(rename = "maximumConcurrentSourceReads")] + _maximum_concurrent_source_reads: usize, + #[serde(rename = "pageDeadlineMilliseconds")] + _page_deadline_milliseconds: u64, +} + +#[derive(Deserialize)] +struct GovernedTemplateShape { + #[serde( + rename = "authorizationMode", + default, + deserialize_with = "deserialize_string_enum" + )] + _authorization_mode: registry_casework_core::TaskAuthorizationMode, +} + +#[derive(Deserialize)] +struct GovernedDependenciesShape { + #[serde(rename = "inbox")] + _inbox: ResponseObject, + #[serde(rename = "contextProvider", deserialize_with = "required_nullable")] + _context_provider: Option>, + #[serde(rename = "clocks")] + _clocks: Vec>, + #[serde(rename = "taskTemplates")] + _task_templates: Vec>, +} + +impl<'de> Deserialize<'de> for GovernedClosure { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + struct ClosureShape { + #[serde(rename = "dependencies")] + _dependencies: ResponseObject, + #[serde(rename = "identity")] + _identity: ResponseObject, + #[serde(rename = "stages")] + _stages: Vec>, + #[serde( + rename = "resubmission", + default, + deserialize_with = "deserialize_string_enum" + )] + _resubmission: registry_casework_core::ReviewResubmissionPolicy, + } + + let value = Value::Object(serde_json::Map::deserialize(deserializer)?); + ClosureShape::deserialize(&value).map_err(serde::de::Error::custom)?; + let closure = ReviewPolicyClosure::deserialize(&value).map_err(serde::de::Error::custom)?; + let named = serde_json::to_value(&closure).map_err(serde::de::Error::custom)?; + if !governed_shapes_match(&value, &named) { + return Err(serde::de::Error::custom( + "invalid governed policy response shape", + )); + } + Ok(Self(closure)) + } +} + +// Compare JSON kinds to the closed core contract across dependency objects +// and enum fields. Optional members omitted by serialization keep the core's +// omission rules. Neither the comparison nor the stage precheck supplies +// values to the digest-bearing closure. +fn governed_shapes_match(received: &Value, named: &Value) -> bool { + match (received, named) { + (Value::Object(received), Value::Object(named)) => received.iter().all(|(key, value)| { + named + .get(key) + .is_none_or(|named| governed_shapes_match(value, named)) + }), + (Value::Array(received), Value::Array(named)) => { + received.len() == named.len() + && received + .iter() + .zip(named) + .all(|(value, named)| governed_shapes_match(value, named)) + } + _ => std::mem::discriminant(received) == std::mem::discriminant(named), + } +} + impl ClientResponse for ReviewPolicyClosure { - type Wire = ReviewPolicyClosure; + type Wire = GovernedClosure; fn from_wire(wire: Self::Wire) -> Self { - wire + wire.0 } } impl ClientResponse for Vec { - type Wire = Vec; + type Wire = Vec; fn from_wire(wire: Self::Wire) -> Self { - wire + wire.into_iter().map(|closure| closure.0).collect() } } @@ -988,19 +1247,19 @@ enum ReviewTaskContextDataWire { pub(crate) struct ReviewTaskContextWire { task_id: uuid::Uuid, request_id: uuid::Uuid, - subject: SubjectBindingWire, + subject: ResponseObject, requester_reference: String, - policy: PolicyBindingWire, - policy_closure: ReviewPolicyClosure, + policy: ResponseObject, + policy_closure: GovernedClosure, #[serde(default)] result_constraints: Option, context: ReviewTaskContextDataWire, #[serde(default, skip_serializing_if = "Vec::is_empty")] - asks: Vec, + asks: Vec>, } impl ClientResponse for registry_casework_core::ReviewTaskContext { - type Wire = Validated; + type Wire = Validated>; fn from_wire(wire: Self::Wire) -> Self { wire.into_inner() @@ -1011,6 +1270,21 @@ impl ClientResponse for registry_casework_core::ReviewTaskContext { mod fix_round_tests { use super::*; + #[test] + fn stage_ask_policy_preserves_known_field_validation() { + type StageAsks = + Validated; + + for value in [ + serde_json::json!({"onDue": null}), + serde_json::json!({"onDue": "future-action"}), + serde_json::json!({"answerWithin": {"hours": 1, "days": 1}}), + serde_json::json!({"answerWithin": {"hours": 0}}), + ] { + assert!(serde_json::from_value::(value).is_err()); + } + } + #[test] fn absent_resubmission_stays_absent_on_the_client_wire() { let policy: ReviewPolicyWire = serde_json::from_value(serde_json::json!({ diff --git a/crates/registry-casework-client/tests/fixtures/ask-response-shapes.json b/crates/registry-casework-client/tests/fixtures/ask-response-shapes.json new file mode 100644 index 0000000000..d8d21cf1ae --- /dev/null +++ b/crates/registry-casework-client/tests/fixtures/ask-response-shapes.json @@ -0,0 +1,574 @@ +[ + { + "name": "context named object", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "ask named object", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "description named object", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "context state object", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":{\"answered\":null},\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask state object", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":{\"open\":null},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "onDue object", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"onDue\":{\"return-to-reviewer\":null},\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "present null duration unit", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1,\"minutes\":null},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "download positional array", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":[\"GET\",\"read-document\",\"reviewer\",\"/documents/document-1\"],\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "closure identity positional array", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":[\"review\",\"1\",\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\"],\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "document digest value", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "download method value", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"POST\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "missing required download path", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "duplicate additive ask member", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"future\":1,\"future\":2,\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "download URL is not origin-relative", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"//other.example/document\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "duration positional array", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":[null,1,null],\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "validation diagnostics", + "route": "description", + "body": "{\"code\":\"request.invalid\",\"detail\":\"Invalid\",\"status\":400,\"title\":\"Invalid\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"type\":\"https://id.registrystack.org/problems/registry-casework/request/invalid\"}", + "accepted": false, + "status": 400, + "headers": { + "registry-casework-validation-path": "$.remote-path-canary", + "registry-casework-validation-reason": "outcome-not-declared", + "registry-casework-validation-allowed": "remote-value-canary" + } + }, + { + "name": "ask additive named want", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"futureMember\":true,\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"futureState\":true,\"held\":{\"futureHeld\":true,\"holder\":{\"futureHolder\":true,\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "ask positional want", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[[\"answer\"]]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask positional want variant payload", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[[\"answer\",{}]]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "context positional want", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[[\"answer\"],{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "context positional want variant payload", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[[\"answer\",{}],{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f7d03032064ae00dc02ea6454216f4f9dcd15369efb3efd4e7e2d466957e3273\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask object waiting marker", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":{\"waiting\":null},\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask positional task subject", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"held\":{\"holder\":{\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":[\"registry\",\"record\",\"record-1\",\"1\",\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"],\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed single policy named dependencies", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "governed policy list named dependencies", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "governed context named dependencies", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "governed single policy object purpose", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":{\"approval\":null},\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed list object purpose", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":{\"approval\":null},\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed context object purpose", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":{\"approval\":null},\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed single policy positional inbox", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":[25,100,25,4,2000],\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed list positional inbox", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":[25,100,25,4,2000],\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed context positional inbox", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":[25,100,25,4,2000],\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed single policy object actsAs", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":{\"staff\":null},\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed list object actsAs", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":{\"staff\":null},\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed context object actsAs", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":{\"staff\":null},\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed single policy positional queue", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[[\"reviews\",\"Reviews\"]],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed list positional queue", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[[\"reviews\",\"Reviews\"]],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "governed context positional queue", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[[\"reviews\",\"Reviews\"]],\"taskTemplates\":[],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:f2f49af35e18df64a7a108294f35cb8f0d0e01574eec606e91150b305f1e250e\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask missing nullable deadline", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"futureMember\":true,\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"futureState\":true,\"held\":{\"futureHeld\":true,\"holder\":{\"futureHolder\":true,\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask deadline wrong shape", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"futureMember\":true,\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":[],\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"futureState\":true,\"held\":{\"futureHeld\":true,\"holder\":{\"futureHolder\":true,\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask positional held state", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"futureMember\":true,\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"futureState\":true,\"held\":[{\"futureHolder\":true,\"issuer\":\"https://issuer.example.test\",\"subject\":\"someone\"}]},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "ask positional holder", + "route": "ask", + "body": "{\"ask\":{\"askId\":\"00000000-0000-0000-0000-00000000000b\",\"askedAt\":\"2026-10-14T00:00:00Z\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"state\":\"open\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"text\":\"Send the signed form.\",\"wants\":[{\"futureMember\":true,\"kind\":\"answer\"}]},\"task\":{\"createdAt\":\"2026-10-14T00:00:00Z\",\"deadlineAt\":null,\"eligibleProfiles\":[\"staff\"],\"marker\":\"waiting\",\"queue\":\"reviews\",\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"revision\":3,\"stageId\":\"review\",\"stageIndex\":0,\"state\":{\"futureState\":true,\"held\":{\"futureHeld\":true,\"holder\":[\"https://issuer.example.test\",\"someone\"]}},\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description missing calendars", + "route": "description", + "body": "{\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description wrong shape calendars", + "route": "description", + "body": "{\"calendars\":{},\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description missing clocks", + "route": "description", + "body": "{\"calendars\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description wrong shape clocks", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":{},\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description missing excludeInitiator", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description wrong shape excludeInitiator", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":[],\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description missing excludePreviousStageReviewers", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "description wrong shape excludePreviousStageReviewers", + "route": "description", + "body": "{\"calendars\":[],\"clocks\":[],\"contextProviders\":[],\"futureMember\":{\"safeToIgnore\":true},\"policyVersion\":\"v1\",\"projectId\":\"fixture\",\"queues\":[],\"reviewPolicies\":[{\"context\":{\"mode\":\"submitted\"},\"displaySchema\":{\"type\":\"object\"},\"id\":\"review\",\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"asks\":{\"answerWithin\":{\"futureDurationMember\":true,\"hours\":1},\"futureAskPolicyMember\":true,\"pauseClocks\":true},\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":[],\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}],\"version\":\"1\"}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy explicit immediate and subject clock", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "policy list explicit immediate and subject clock", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "context explicit immediate and subject clock", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": true, + "status": 200, + "headers": {} + }, + { + "name": "policy missing nullable context provider", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy list missing nullable context provider", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "context missing nullable context provider", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy missing all inbox members", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy list missing all inbox members", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "context missing all inbox members", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy missing inbox defaultPageSize", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy missing inbox maximumCandidateScan", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy missing inbox maximumConcurrentSourceReads", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy missing inbox maximumSourceReads", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy missing inbox pageDeadlineMilliseconds", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy object immediate mode", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":{\"immediate\":null},\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy list object immediate mode", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":{\"immediate\":null},\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "context object immediate mode", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":{\"immediate\":null},\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy null companion clock unit", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1,\"minutes\":null},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy list null companion clock unit", + "route": "policies", + "body": "[{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1,\"minutes\":null},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}]", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "context null companion clock unit", + "route": "context", + "body": "{\"asks\":[{\"answer\":{\"answeredAt\":\"2026-11-27T01:00:00Z\",\"documents\":[{\"byteSize\":42,\"contentType\":\"application/pdf\",\"download\":{\"accessProfile\":\"reviewer\",\"futureDownloadMember\":true,\"method\":\"GET\",\"operation\":\"read-document\",\"path\":\"/documents/document-1\"},\"futureDocumentMember\":true,\"id\":\"document-1\",\"sha256\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"verificationStatus\":\"verified\"}],\"futureAnswerMember\":true,\"text\":\"Synthetic answer\"},\"answeredAt\":\"2026-11-27T01:00:00Z\",\"askId\":\"00000000-0000-0000-0000-000000000007\",\"askedAt\":\"2026-11-27T00:00:00Z\",\"state\":\"answered\",\"taskId\":\"00000000-0000-0000-0000-000000000001\",\"text\":\"Send the signed form.\",\"wants\":[{\"futureWantMember\":true,\"kind\":\"answer\"},{\"futureWantMember\":true,\"kind\":\"document\"}]}],\"context\":{\"mode\":\"submitted\",\"snapshot\":{}},\"policy\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"policyClosure\":{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1,\"minutes\":null},\"anchor\":{\"type\":\"request-accepted\"},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]},\"requestId\":\"00000000-0000-0000-0000-000000000009\",\"requesterReference\":\"record-1\",\"subject\":{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"id\":\"record-1\",\"source\":\"registry\",\"type\":\"record\",\"version\":\"1\"},\"taskId\":\"00000000-0000-0000-0000-000000000001\"}", + "accepted": false, + "status": 200, + "headers": {} + }, + { + "name": "policy object clock anchor enum", + "route": "policy", + "body": "{\"context\":{\"mode\":\"submitted\"},\"dependencies\":{\"accessProfiles\":[{\"actsAs\":\"staff\",\"id\":\"staff\",\"principalClaim\":\"sub\",\"requiredScopes\":[\"casework:staff\"]}],\"calendars\":[],\"clocks\":[{\"after\":{\"hours\":1},\"anchor\":{\"type\":{\"request-accepted\":null}},\"id\":\"elapsed\",\"type\":\"subject\"}],\"contextProvider\":null,\"inbox\":{\"defaultPageSize\":25,\"maximumCandidateScan\":100,\"maximumConcurrentSourceReads\":4,\"maximumSourceReads\":25,\"pageDeadlineMilliseconds\":2000},\"queues\":[{\"id\":\"reviews\",\"label\":\"Reviews\"}],\"taskTemplates\":[{\"agent\":{\"issuer\":\"https://issuer.example/\",\"subject\":\"follow-up\"},\"authorizationMode\":\"immediate\",\"bounds\":{\"permissions\":[{\"collection\":\"records\",\"operations\":[\"read\"]}],\"type\":\"breg\"},\"client\":\"follow-up\",\"eligibleProfiles\":[\"staff\"],\"eligibleTeams\":[],\"id\":\"follow-up\",\"label\":\"Follow up\",\"lifetimeSeconds\":60,\"purpose\":\"Follow up\",\"resource\":\"urn:breg\",\"scopes\":[\"write\"],\"source\":\"registry\",\"subjects\":{},\"version\":\"1\"}],\"teams\":[],\"trustedProducers\":[]},\"displaySchema\":{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"},\"identity\":{\"digest\":\"sha256:87e50efd823716089da56f1044af095d8fc3004f015eefa19f7b3ab1b2d60d86\",\"id\":\"review\",\"version\":\"1\"},\"outcomes\":[{\"id\":\"approved\",\"label\":\"Approve\",\"publicReason\":\"optional\",\"reasonRequired\":false,\"settlement\":\"approved\"}],\"purpose\":\"approval\",\"retention\":{\"accountabilityRetentionDays\":30,\"terminalRetentionDays\":30},\"stages\":[{\"decidingProfiles\":[\"staff\"],\"excludeInitiator\":false,\"excludePreviousStageReviewers\":false,\"id\":\"review\",\"queue\":\"reviews\",\"requiredApprovals\":1}]}", + "accepted": false, + "status": 200, + "headers": {} + } +] diff --git a/crates/registry-casework-client/tests/fixtures/direct-response-additions.json b/crates/registry-casework-client/tests/fixtures/direct-response-additions.json new file mode 100644 index 0000000000..bdeeb59710 --- /dev/null +++ b/crates/registry-casework-client/tests/fixtures/direct-response-additions.json @@ -0,0 +1,81 @@ +{ + "description": { + "projectId": "fixture", + "policyVersion": "v1", + "queues": [], + "reviewPolicies": [ + { + "id": "review", + "version": "1", + "purpose": "approval", + "context": { "mode": "submitted" }, + "stages": [ + { + "id": "review", + "queue": "reviews", + "decidingProfiles": ["staff"], + "requiredApprovals": 1, + "excludeInitiator": false, + "excludePreviousStageReviewers": false, + "asks": { + "answerWithin": { "hours": 1, "futureDurationMember": true }, + "pauseClocks": true, + "futureAskPolicyMember": true + } + } + ], + "retention": { "terminalRetentionDays": 30, "accountabilityRetentionDays": 30 }, + "displaySchema": { "type": "object" } + } + ], + "contextProviders": [], + "calendars": [], + "clocks": [], + "futureMember": { "safeToIgnore": true } + }, + "asks": [ + { + "askId": "00000000-0000-0000-0000-000000000007", + "taskId": "00000000-0000-0000-0000-000000000000", + "text": "Send the signed form.", + "wants": [ + { "kind": "answer", "futureWantMember": true }, + { "kind": "document", "futureWantMember": true } + ], + "state": "answered", + "askedAt": "2026-11-27T00:00:00Z", + "answeredAt": "2026-11-27T01:00:00Z", + "answer": { + "text": "Synthetic answer", + "documents": [ + { + "id": "document-1", + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "contentType": "application/pdf", + "byteSize": 42, + "verificationStatus": "verified", + "download": { + "method": "GET", + "operation": "read-document", + "accessProfile": "reviewer", + "path": "/documents/document-1", + "futureDownloadMember": true + }, + "futureDocumentMember": true + } + ], + "answeredAt": "2026-11-27T01:00:00Z", + "futureAnswerMember": true + } + } + ], + "problem": { + "type": "https://id.registrystack.org/problems/registry-casework/review/future-safe", + "status": 409, + "code": "review.future-safe", + "traceId": "0123456789abcdef0123456789abcdef", + "title": "Synthetic future title", + "detail": "Synthetic future detail", + "futureMember": { "prose": "Synthetic future extension" } + } +} diff --git a/crates/registry-casework-client/tests/fixtures/problem-responses.json b/crates/registry-casework-client/tests/fixtures/problem-responses.json new file mode 100644 index 0000000000..fa920a6417 --- /dev/null +++ b/crates/registry-casework-client/tests/fixtures/problem-responses.json @@ -0,0 +1,101 @@ +[ + { + "name": "future", + "status": 409, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/future-safe\",\"status\":409,\"code\":\"review.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": true, + "delegated": true + }, + { + "name": "future-server-error", + "status": 503, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/future-safe\",\"status\":503,\"code\":\"review.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": true, + "delegated": true + }, + { + "name": "future-wrong-casework-type", + "status": 409, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/unrelated\",\"status\":409,\"code\":\"review.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "body-status-mismatch", + "status": 409, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/future-safe\",\"status\":400,\"code\":\"review.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "generic", + "status": 409, + "headers": {}, + "body": "{\"type\":\"https://provider.example/problems/future-safe\",\"status\":409,\"code\":\"provider.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": true + }, + { + "name": "known-changed-prose", + "status": 400, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/request/invalid\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": true, + "delegated": true + }, + { + "name": "known-wrong-type", + "status": 400, + "headers": {}, + "body": "{\"type\":\"https://provider.example/problems/future-safe\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "known-wrong-status", + "status": 409, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/request/invalid\",\"status\":409,\"code\":\"request.invalid\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "success-status", + "status": 201, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/future-safe\",\"status\":201,\"code\":\"review.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "redirect-status", + "status": 302, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/future-safe\",\"status\":302,\"code\":\"review.future-safe\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "unpaired-validation", + "status": 400, + "headers": { + "registry-review-validation-path": "$.display", + "registry-casework-validation-path": "$.display" + }, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/request/invalid\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"0123456789abcdef0123456789abcdef\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + }, + { + "name": "wrong-trace", + "status": 409, + "headers": {}, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-casework/review/future-safe\",\"status\":409,\"code\":\"review.future-safe\",\"traceId\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Synthetic future title\",\"detail\":\"Synthetic future detail\",\"futureMember\":{\"prose\":\"Synthetic future extension\"}}", + "direct": false, + "delegated": false + } +] diff --git a/crates/registry-casework-client/tests/http_boundary.rs b/crates/registry-casework-client/tests/http_boundary.rs index eee650c0dd..ed369df899 100644 --- a/crates/registry-casework-client/tests/http_boundary.rs +++ b/crates/registry-casework-client/tests/http_boundary.rs @@ -30,6 +30,11 @@ use uuid::Uuid; const TRACEPARENT: &str = "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"; type HistoryObservations = Arc>>; +fn direct_response_additions() -> Value { + serde_json::from_str(include_str!("fixtures/direct-response-additions.json")) + .expect("direct response fixtures") +} + #[tokio::test] async fn separate_human_source_credential_is_explicit_per_call_and_never_retained() { let observations = Arc::new(Mutex::new(Vec::<(String, HeaderMap)>::new())); @@ -81,7 +86,7 @@ async fn separate_human_source_credential_is_explicit_per_call_and_never_retaine #[tokio::test] async fn ordinary_nested_response_members_are_ignored() { - let description = json!({ + let mut description = json!({ "projectId": "client-fixture", "policyVersion": "1", "queues": [{"id": "reviews", "label": "Reviews", "futureQueueMember": true}], @@ -94,11 +99,12 @@ async fn ordinary_nested_response_members_are_ignored() { "stages": [{ "id": "review", "queue": "reviews", "decidingProfiles": ["staff"], "requiredApprovals": 1, "outcomes": ["approved"], + "excludeInitiator": false, "excludePreviousStageReviewers": false, "publicProgressCode": "initial-verification", "futureStageMember": true }, { "id": "confirm", "queue": "reviews", "decidingProfiles": ["staff"], - "requiredApprovals": 1 + "requiredApprovals": 1, "excludeInitiator": false, "excludePreviousStageReviewers": false }], "retention": { "terminalRetentionDays": 30, @@ -128,6 +134,9 @@ async fn ordinary_nested_response_members_are_ignored() { "clocks": [], "futureDescriptionMember": {"safeToIgnore": true} }); + description["reviewPolicies"][0]["stages"][0]["asks"] = direct_response_additions() + ["description"]["reviewPolicies"][0]["stages"][0]["asks"] + .clone(); let directory = json!({ "revision": 3, "teams": [{ @@ -207,6 +216,12 @@ async fn ordinary_nested_response_members_are_ignored() { assert_eq!(returned.value.review_policies[0].id, "registry-correction"); let stages = &returned.value.review_policies[0].stages; assert_eq!(stages[0].outcomes, Some(vec!["approved".to_owned()])); + let asks = stages[0].asks.as_ref().expect("stage ask policy"); + assert_eq!( + asks.answer_within, + Some(registry_casework_core::ElapsedDuration::Hours(1)) + ); + assert!(asks.pause_clocks); assert_eq!( stages[0] .public_progress_code @@ -3395,6 +3410,193 @@ async fn review_validation_headers_preserve_only_path_and_closed_reason() { server.abort(); } +#[tokio::test] +async fn ask_responses_require_their_contract_shapes() { + let fixtures: Vec = + serde_json::from_str(include_str!("fixtures/ask-response-shapes.json")).unwrap(); + let respond = |State(responses): State>>>| async move { + let fixture = responses.lock().unwrap().pop_front().unwrap(); + let status = StatusCode::from_u16(fixture["status"].as_u64().unwrap() as u16).unwrap(); + let media = if status.is_success() { + "application/json" + } else { + "application/problem+json" + }; + let mut headers = HeaderMap::new(); + headers.insert("content-type", media.parse().unwrap()); + headers.insert("traceparent", TRACEPARENT.parse().unwrap()); + for (name, value) in fixture["headers"].as_object().unwrap() { + headers.insert( + axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(), + value.as_str().unwrap().parse().unwrap(), + ); + } + ( + status, + headers, + fixture["body"].as_str().unwrap().to_owned(), + ) + }; + let responses = Arc::new(Mutex::new(VecDeque::from(fixtures.clone()))); + let app = Router::new() + .route("/v1/casework", get(respond)) + .route("/v1/review-policies", get(respond)) + .route("/v1/review-policies/{policy}", get(respond)) + .route("/v1/review-tasks/{task}/context", get(respond)) + .route("/v1/review-tasks/{task}/asks", post(respond)) + .with_state(responses.clone()); + 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 { axum::serve(listener, app).await.unwrap() }); + let client = CaseworkClient::new(CaseworkClientConfig::new_without_peer_policy( + Url::parse(&format!("http://{address}/")).unwrap(), + )) + .unwrap(); + let token = BearerToken::new("one-call-secret").unwrap(); + for fixture in fixtures { + let auth = CaseworkAuth::new(&token, "staff"); + let task = Uuid::from_u128(1); + let route = fixture["route"].as_str().unwrap(); + let name = &fixture["name"]; + let result = match route { + "context" => client.review_task_context(auth, task).await.map(|_| ()), + "ask" => client + .ask_applicant(auth, task, 2, "ask-1", &the_ask()) + .await + .map(|_| ()), + "description" => client.description(auth).await.map(|_| ()), + "policy" => client.review_policy(auth, "review").await.map(|_| ()), + "policies" => client.review_policies(auth).await.map(|_| ()), + _ => panic!("unexpected fixture route {route}"), + }; + if fixture["accepted"] == true { + result.unwrap_or_else(|error| panic!("{name}: {error:?}")); + continue; + } + let error = result.expect_err(name.as_str().unwrap()); + if fixture["status"] == 400 { + let debug = format!("{error:?}"); + let CaseworkClientError::Problem { + validation: Some(validation), + .. + } = error + else { + panic!("{name}: {debug}") + }; + assert_eq!(validation.path, "$.remote-path-canary"); + assert_eq!(validation.allowed.as_ref(), ["remote-value-canary"]); + assert!(!debug.contains("remote-path-canary")); + assert!(!debug.contains("remote-value-canary")); + } else { + assert!( + matches!( + error, + CaseworkClientError::Protocol { + status: 200, + failure: CaseworkProtocolFailure::Body, + .. + } + ), + "{name}: {error:?}" + ); + if route == "ask" { + assert!(error.is_outcome_unknown(), "{name}"); + } + } + } + assert!(responses.lock().unwrap().is_empty()); + server.abort(); +} + +#[tokio::test] +async fn direct_and_review_problem_boundaries_share_raw_http_fixtures() { + let fixtures: Vec = + serde_json::from_str(include_str!("fixtures/problem-responses.json")).unwrap(); + let responses = fixtures + .iter() + .flat_map(|fixture| [fixture.clone(), fixture.clone()]) + .collect::>(); + let respond = |State(responses): State>>>| async move { + let fixture = responses.lock().unwrap().pop_front().unwrap(); + let mut headers = HeaderMap::new(); + headers.insert("content-type", "application/problem+json".parse().unwrap()); + headers.insert("traceparent", TRACEPARENT.parse().unwrap()); + for (name, value) in fixture["headers"].as_object().unwrap() { + headers.insert( + axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(), + value.as_str().unwrap().parse().unwrap(), + ); + } + ( + StatusCode::from_u16(fixture["status"].as_u64().unwrap() as u16).unwrap(), + headers, + fixture["body"].as_str().unwrap().to_owned(), + ) + }; + let app = Router::new() + .route("/v1/casework", get(respond)) + .route("/v1/review-results", get(respond)) + .with_state(Arc::new(Mutex::new(responses))); + 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 { axum::serve(listener, app).await.unwrap() }); + let client = CaseworkClient::new(CaseworkClientConfig::new_without_peer_policy( + Url::parse(&format!("http://{address}/")).unwrap(), + )) + .unwrap(); + let token = BearerToken::new("one-call-secret").unwrap(); + for fixture in fixtures { + let auth = || CaseworkAuth::new(&token, "requester"); + for (route, error) in [ + ("direct", client.description(auth()).await.unwrap_err()), + ( + "delegated", + client + .review_results(auth(), &Default::default()) + .await + .unwrap_err(), + ), + ] { + let name = &fixture["name"]; + let diagnostic = format!("{error} {error:?}"); + assert!(!diagnostic.contains("Synthetic future"), "{route} {name}"); + let status = fixture["status"].as_u64().unwrap() as u16; + if fixture[route] == true { + let body: Value = serde_json::from_str(fixture["body"].as_str().unwrap()).unwrap(); + assert_eq!(error.is_outcome_unknown(), status >= 500, "{route} {name}"); + let CaseworkClientError::Problem { + status: actual_status, + code, + problem_type: Some(problem_type), + trace_id: Some(trace_id), + validation: None, + .. + } = error + else { + panic!("expected structured Problem for {route} {name}: {diagnostic}"); + }; + assert_eq!(actual_status, status); + assert_eq!(code.code(), body["code"].as_str().unwrap()); + assert_eq!(problem_type, body["type"].as_str().unwrap()); + assert_eq!(trace_id, body["traceId"].as_str().unwrap()); + if matches!(code, CaseworkProblemCode::Unknown(_)) { + assert!(!diagnostic.contains(code.code()), "{route} {name}"); + assert!(!diagnostic.contains(&problem_type), "{route} {name}"); + assert!(!format!("{code:?}").contains(code.code()), "{route} {name}"); + } + } else { + assert!( + matches!(error, CaseworkClientError::Protocol { + status: actual_status, .. + } if actual_status == status), + "{route} {name}: {diagnostic}" + ); + } + } + } + server.abort(); +} + #[tokio::test] async fn unknown_future_problem_code_remains_a_safe_typed_problem() { let app = Router::new().route("/v1/casework", get(unknown_problem_response)); @@ -3412,19 +3614,85 @@ async fn unknown_future_problem_code_remains_a_safe_typed_problem() { .expect("client"); let token = BearerToken::new("one-call-secret").expect("fixture token"); let result = client.description(CaseworkAuth::new(&token, "staff")).await; + let error = result.expect_err("problem response"); assert_eq!( - result.as_ref().expect_err("problem response").to_string(), + error.to_string(), "Registry Casework refused the request (HTTP 409, problem unknown)" ); + assert!(!error.is_outcome_unknown()); + assert!(!format!("{error:?}").contains("Synthetic future")); assert!(matches!( - result, - Err(CaseworkClientError::Problem { + error, + CaseworkClientError::Problem { status: 409, code: CaseworkProblemCode::Unknown(code), + problem_type: Some(problem_type), detail: None, + trace_id: Some(trace_id), + validation: None, + } if code == "review.future-safe" + && problem_type == direct_response_additions()["problem"]["type"].as_str().unwrap() + && trace_id == "0123456789abcdef0123456789abcdef" + )); + server.abort(); +} + +#[tokio::test] +async fn future_problem_requires_a_bounded_registered_identifier_shape() { + let app = Router::new().route( + "/v1/casework", + get( + |State(problems): State>>>| async move { + ( + StatusCode::CONFLICT, + [ + ("content-type", "application/problem+json"), + ("traceparent", TRACEPARENT), + ], + problems.lock().unwrap().pop_front().expect("next fixture"), + ) + }, + ), + ); + let mut unmatched_type = direct_response_additions()["problem"].clone(); + unmatched_type["type"] = + json!("https://id.registrystack.org/problems/registry-casework/review/other"); + let bounded_code = format!("review.future.{}", "a".repeat(114)); + let problems = [ + problem_json(&bounded_code, 409), + problem_json("undotted", 409), + problem_json("review.future--code", 409), + problem_json(&format!("review.{}", "a".repeat(122)), 409), + unmatched_type.to_string(), + ]; + let invalid_count = problems.len() - 1; + let app = app.with_state(Arc::new(Mutex::new(VecDeque::from(problems)))); + 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 { axum::serve(listener, app).await.unwrap() }); + let client = CaseworkClient::new(CaseworkClientConfig::new_without_peer_policy( + Url::parse(&format!("http://{address}/")).unwrap(), + )) + .unwrap(); + let token = BearerToken::new("one-call-secret").unwrap(); + + assert!(matches!( + client.description(CaseworkAuth::new(&token, "staff")).await, + Err(CaseworkClientError::Problem { + code: CaseworkProblemCode::Unknown(code), .. - }) if code == "review.future-safe" + }) if code == bounded_code )); + for _ in 0..invalid_count { + assert!(matches!( + client.description(CaseworkAuth::new(&token, "staff")).await, + Err(CaseworkClientError::Protocol { + status: 409, + failure: CaseworkProtocolFailure::Problem, + .. + }) + )); + } server.abort(); } @@ -3636,7 +3904,7 @@ async fn unknown_problem_response() -> impl IntoResponse { ("content-type", "application/problem+json"), ("traceparent", TRACEPARENT), ], - problem_json("review.future-safe", 409), + direct_response_additions()["problem"].to_string(), ) } @@ -3697,6 +3965,7 @@ fn enrich_tasks(value: &mut Value) { ); object.insert("requesterReference".into(), json!("record-1")); object.insert("createdAt".into(), json!("2026-10-14T00:00:00Z")); + object.entry("deadlineAt").or_insert(Value::Null); object.insert("futureTaskMember".into(), json!({"safeToIgnore": true})); if let Some(Value::Object(state)) = object.get_mut("state") { if let Some(Value::Object(held)) = state.get_mut("held") { @@ -3758,7 +4027,7 @@ fn asked_body(task_id: Uuid, revision: i64, marker: Option<&str>, ask_state: &st "digest":ContentDigest::for_bytes(b"record-1") }, "text": "Send the signed form.", - "wants": [{"kind": "answer"}], + "wants": [{"kind": "answer", "futureWantMember": true}], "askedAt": "2026-10-14T00:00:00.000000Z", "state": ask_state, "futureAskMember": true, @@ -3902,21 +4171,49 @@ async fn review_task_context_carries_the_asks_and_tasks_the_marker() { }), json!({"mode": "submitted", "snapshot": {"summary": "Frozen review"}}), ); - body["asks"] = json!([{ - "askId": Uuid::from_u128(11), - "taskId": Uuid::nil(), - "text": "Send the signed form.", - "wants": [{"kind": "document"}], - "askedAt": "2026-10-14T00:00:00Z", - "state": "answered", - "answeredAt": "2026-10-14T01:00:00Z", - }]); - let context = serve_context(body).await.expect("context with asks").value; + body["asks"] = direct_response_additions()["asks"].clone(); + let context = serve_context(body.clone()) + .await + .expect("context with asks") + .value; assert_eq!(context.asks.len(), 1); assert_eq!( context.asks[0].state, registry_casework_client::ReviewAskState::Answered ); + assert_eq!( + context.asks[0].wants, + vec![ + registry_casework_client::ReviewAskWant::Answer {}, + registry_casework_client::ReviewAskWant::Document {}, + ] + ); + let answer = context.asks[0].answer.as_ref().expect("source answer"); + assert_eq!(answer.text.as_deref(), Some("Synthetic answer")); + let document = &answer.documents[0]; + assert_eq!(document.id, "document-1"); + assert_eq!(document.byte_size, 42); + assert_eq!( + document.download.as_ref().expect("download").path, + "/documents/document-1" + ); + + for (pointer, invalid_value) in [ + ("/asks/0/wants/0/kind", json!("future-want")), + ("/asks/0/answer/documents/0/byteSize", json!("42")), + ("/asks/0/answer/documents/0/download/path", Value::Null), + ] { + let mut invalid = body.clone(); + *invalid.pointer_mut(pointer).expect("known fixture field") = invalid_value; + assert!(matches!( + serve_context_rejection(invalid).await, + CaseworkClientError::Protocol { + status: 200, + failure: CaseworkProtocolFailure::Body, + .. + } + )); + } } #[tokio::test] diff --git a/crates/registry-casework/src/config.rs b/crates/registry-casework/src/config.rs index 28c15649f8..cdcce6e542 100644 --- a/crates/registry-casework/src/config.rs +++ b/crates/registry-casework/src/config.rs @@ -4830,7 +4830,7 @@ impl RuntimeConfigError { Self::DatabaseTransport(DatabaseTransportError::TestOnlyPlaintext) => { "database.testOnlyPlaintext" } - Self::DatabaseTransport(_) => "database.transport", + Self::DatabaseTransport(error) => error.database_field(), Self::DevelopmentOnly(_) => "authentication.oidc.issuers", Self::InvalidAuditDestination(error) => audit_field(error), Self::InvalidContextProviders => "contextProviders", diff --git a/crates/registry-casework/src/config/issuers.rs b/crates/registry-casework/src/config/issuers.rs index 47e9766849..d8cb4a93f7 100644 --- a/crates/registry-casework/src/config/issuers.rs +++ b/crates/registry-casework/src/config/issuers.rs @@ -26,7 +26,7 @@ pub const ISSUERS_POINTER: &str = "/authentication/oidc/issuers"; pub static UNRESTRICTED_CLIENTS: DevelopmentSetting = DevelopmentSetting { code: "casework.posture.unrestricted-clients", key: "allowedClients", - summary: "this issuer entry admits a token from every client the issuer signs for", + summary: "This issuer entry admits a token from every client the issuer signs for", production: "List the OAuth clients whose access tokens this issuer entry admits.", }; diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 97817bac20..7ccb572efd 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -10,7 +10,6 @@ use registry_platform_config::{ DatabaseTransport, DatabaseTransportError, DevelopmentWitness, SecretResolver, }; use serde_json::{json, Value}; -use std::str::FromStr; use std::time::Duration; use thiserror::Error; use tokio_postgres::Config as PgConfig; @@ -203,7 +202,7 @@ impl PostgresStore { config, secrets, witness, - "database.runtimeUrlRef", + registry_platform_config::DatabaseMember::RuntimeUrl, &config.runtime_url_ref, ) } @@ -216,7 +215,7 @@ impl PostgresStore { config, secrets, witness, - "database.migrationUrlRef", + registry_platform_config::DatabaseMember::MigrationUrl, &config.migration_url_ref, ) } @@ -224,11 +223,15 @@ impl PostgresStore { config: &DatabaseConfig, secrets: &SecretResolver, witness: Option<&DevelopmentWitness>, - field: &'static str, + member: registry_platform_config::DatabaseMember, reference: &str, ) -> Result { let protected = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure(field, reference, &error)) + StoreError::SecretConfiguration(describe_secret_failure( + &format!("database.{member}"), + reference, + &error, + )) })?; let url = std::str::from_utf8(protected.expose_secret()) .map_err(|_| StoreError::Configuration)?; @@ -236,6 +239,7 @@ impl PostgresStore { config, url, witness, + member, ®istry_platform_config::resolve_database_host, )?; let manager_config = ManagerConfig { @@ -715,20 +719,8 @@ fn tls_connector( &error, )) })?; - let mut roots = rustls::RootCertStore::empty(); - use rustls::pki_types::pem::PemObject as _; - let mut count = 0usize; - for certificate in - rustls::pki_types::CertificateDer::pem_slice_iter(certificate.expose_secret()) - { - roots - .add(certificate.map_err(|_| StoreError::Configuration)?) - .map_err(|_| StoreError::Configuration)?; - count += 1; - } - if count == 0 { - return Err(StoreError::Configuration); - } + let roots = registry_platform_postgres::pem_root_store(certificate.expose_secret()) + .map_err(|_| StoreError::Configuration)?; let client = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); @@ -969,9 +961,11 @@ fn driver_config( config: &DatabaseConfig, url: &str, witness: Option<&DevelopmentWitness>, + member: registry_platform_config::DatabaseMember, resolve: ®istry_platform_config::HostResolver, ) -> Result<(PgConfig, DatabaseTransport), StoreError> { - let mut postgres = PgConfig::from_str(url).map_err(|_| StoreError::Configuration)?; + let mut postgres = registry_platform_postgres::parse_runtime_url(url, config, witness) + .map_err(|error| error.at_url(member))?; if postgres.get_user().is_none() || postgres.get_dbname().is_none() { return Err(StoreError::Configuration); } @@ -998,6 +992,30 @@ mod driver_config_tests { use super::*; + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config = registry_platform_config::DatabaseConfig { + runtime_url_ref: "secret:env/DB_RUNTIME".to_owned(), + migration_url_ref: "secret:env/DB_MIGRATION".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: None, + }; + let (postgres, tls) = driver_config( + &config, + "postgresql://app@db.example/registry?sslmode=verify-full", + None, + registry_platform_config::DatabaseMember::RuntimeUrl, + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert_eq!(tls, DatabaseTransport::VerifiedTls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping @@ -1020,6 +1038,7 @@ mod driver_config_tests { &config, "postgresql://app@localhost:5433/casework", None, + registry_platform_config::DatabaseMember::RuntimeUrl, &fixed, ) .unwrap(); diff --git a/crates/registry-casework/tests/refusal_golden.rs b/crates/registry-casework/tests/refusal_golden.rs index 1cf50e8f74..4b293e37f2 100644 --- a/crates/registry-casework/tests/refusal_golden.rs +++ b/crates/registry-casework/tests/refusal_golden.rs @@ -625,6 +625,20 @@ fn assert_one_value_free_line(case: &Case, logs: &CapturedDiagnosticLogs, tokens "{}", case.name ); + let expected_remedy = match case.name { + "wrong-audience" => Some("aud claim"), + "expired" => Some("exp claim"), + _ => None, + }; + if let Some(claim) = expected_remedy { + assert!( + fields["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(claim)), + "{}: the operator diagnostic names the token claim", + case.name + ); + } if case.check == "scope" { // A scope refusal names what the operator declared, never the scopes // the token held. diff --git a/crates/registry-caseworkctl/src/lib.rs b/crates/registry-caseworkctl/src/lib.rs index 7e6f4f03f3..abdd29197a 100644 --- a/crates/registry-caseworkctl/src/lib.rs +++ b/crates/registry-caseworkctl/src/lib.rs @@ -644,7 +644,7 @@ fn classify_failure(kind: CommandKind, error: &anyhow::Error) -> (u8, Value) { json!({ "severity": "error", "code": transport.code(), - "path": "runtime.yaml:/database/transport", + "path": format!("runtime.yaml:{}", transport.database_pointer()), "message": transport.to_string(), "suggestedAction": transport.suggested_action(), }), diff --git a/crates/registry-caseworkctl/src/provision.rs b/crates/registry-caseworkctl/src/provision.rs index d73cef84b7..e17922f866 100644 --- a/crates/registry-caseworkctl/src/provision.rs +++ b/crates/registry-caseworkctl/src/provision.rs @@ -6,19 +6,16 @@ use std::path::Path; use std::process::ExitCode; -use registry_casework::{secret_resolver, RuntimeConfig}; -use registry_platform_config::{describe_secret_failure, DeclaredPosture, SecretResolver}; +use registry_casework::RuntimeConfig; +use registry_platform_config::{DatabaseMember, DeclaredPosture, SecretError, SecretResolver}; use registry_platform_provision::cli::OutputFormat; use registry_platform_provision::{ - provision_transport, run_provision, ProductDatabase, ProvisionArgs, ProvisionInput, - SchemaLayout, + provision_transport, read_ca_bundle, run_provision, secret_refusal, secret_refusal_code, + url_not_text_refusal, ProductDatabase, ProvisionArgs, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; -const SECRET_ACTION: &str = - "Provision a runtime-readable secret through the configured provider and retry provision."; - /// Runs the command with this tool's global `--format`. pub(crate) fn run(args: ProvisionArgs, json: bool, declared: DeclaredPosture) -> ExitCode { let format = if json { @@ -51,44 +48,33 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result Result, Box> { - let secret = secrets - .resolve(reference) - .map_err(|error| secret_diagnostic(field, pointer, reference, &error))?; - let text = std::str::from_utf8(secret.expose_secret()).map_err(|_| { - Box::new(Diagnostic::error( - "casework.runtime.secret-unavailable", - format!("runtime.yaml:{pointer}"), - format!("{field}: the secret value must be non-empty text"), - SECRET_ACTION, - )) - })?; +) -> Result, Vec> { + let refused = |error: &SecretError| vec![secret_refusal("database", member, error)]; + let secret = member + .read(secrets, reference) + .map_err(|error| refused(&error))?; + let text = std::str::from_utf8(secret.expose_secret()) + .map_err(|_| vec![url_not_text_refusal("database", member)])?; Ok(Zeroizing::new(text.to_owned())) } - -fn secret_diagnostic( - field: &str, - pointer: &str, - reference: &str, - error: ®istry_platform_config::SecretError, -) -> Box { - Box::new(Diagnostic::error( - "casework.runtime.secret-unavailable", - format!("runtime.yaml:{pointer}"), - describe_secret_failure(field, reference, error), - error.suggested_action(), - )) -} diff --git a/crates/registry-caseworkctl/tests/provision.rs b/crates/registry-caseworkctl/tests/provision.rs index bf5e7cbed9..f7260b417b 100644 --- a/crates/registry-caseworkctl/tests/provision.rs +++ b/crates/registry-caseworkctl/tests/provision.rs @@ -269,7 +269,7 @@ fn a_missing_runtime_url_secret_is_refused_without_printing_a_password() { fs::remove_file(deployment.root.join("secrets/runtime-url")).unwrap(); assert_loader_refusal( &refused_print(&deployment.runtime), - "casework.runtime.secret-unavailable", + "platform.provision.secret-unavailable", "/database/runtimeUrlRef", ); } @@ -287,7 +287,7 @@ fn a_missing_migration_url_secret_is_refused_without_printing_a_password() { fs::remove_file(deployment.root.join("secrets/migration-url")).unwrap(); assert_loader_refusal( &refused_print(&deployment.runtime), - "casework.runtime.secret-unavailable", + "platform.provision.secret-unavailable", "/database/migrationUrlRef", ); } @@ -306,13 +306,13 @@ fn a_runtime_url_secret_that_is_not_text_is_refused() { fs::write(&file, [0xff, 0xfe, 0xfd]).unwrap(); assert_loader_refusal( &refused_print(&deployment.runtime), - "casework.runtime.secret-unavailable", + "platform.provision.secret-value-invalid", "/database/runtimeUrlRef", ); } #[test] -fn a_ca_bundle_that_is_not_text_is_refused_with_its_reason() { +fn a_ca_bundle_without_a_certificate_is_refused_with_its_reason() { let (migration, runtime) = offline_urls(); let ca = tempfile::NamedTempFile::new().unwrap(); fs::write(ca.path(), "replaced below").unwrap(); @@ -329,10 +329,14 @@ fn a_ca_bundle_that_is_not_text_is_refused_with_its_reason() { let refused = refused_print(&deployment.runtime); assert_loader_refusal( &refused, - "casework.runtime.secret-unavailable", + "platform.provision.ca-bundle-no-certificate", "/database/caBundleRef", ); - assert!(refused.2.contains("not UTF-8 text"), "{}", refused.2); + assert!( + refused.2.contains("holds no PEM certificate"), + "{}", + refused.2 + ); } #[test] @@ -350,7 +354,7 @@ fn a_missing_ca_bundle_secret_is_refused() { fs::remove_file(deployment.root.join("secrets/ca")).unwrap(); assert_loader_refusal( &refused_print(&deployment.runtime), - "casework.runtime.secret-unavailable", + "platform.provision.secret-unavailable", "/database/caBundleRef", ); } diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index c90af04500..80fd344c88 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -27449,7 +27449,7 @@ "name": "serve", "invocation": "registry-render serve", "about": "Serve the HTTP rendering API (see the runtime YAML)", - "long_about": "Serve the HTTP rendering API (see the runtime YAML). Configure OIDC authentication with authentication.oidc, or shared API key authentication with authentication.apiKeyRef for unsigned rendering. Sealing requires OIDC.", + "long_about": "Serve the HTTP rendering API (see the runtime YAML). Configure OIDC authentication with authentication.oidc, or shared API key authentication with authentication.apiKeyRef for unsigned rendering in explicit development posture on a loopback listener. Sealing requires OIDC.", "usage": "registry-render serve [OPTIONS] --runtime-config ", "arguments": [], "options": [ @@ -30302,6 +30302,60 @@ "constraints": [], "subcommands": [] }, + { + "name": "export-preview", + "invocation": "rstack dev export-preview", + "about": "Build a project's service preview and export the bundle a host serves outside rstack dev", + "long_about": "Build a project's service preview and export the bundle a host serves outside rstack dev. Writes exactly the preview manifest, each compiled function and every file of the manifest's static output into a new directory, and prints the bundle digest a deployment pins with the declaration digest of the checked service.yaml. Starts no service.", + "usage": "rstack dev export-preview [OPTIONS] --output ", + "arguments": [ + { + "display": "", + "description": "Project directory containing dev.yaml with preview and its service.yaml", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--output ", + "description": "New directory for the bundle. An existing path is refused", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Report encoding. Defaults to human even when stdout is piped. Only forwarded evidence test and evidence fixtures run commands accept junit", + "always_required": false, + "repeatable": true, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help (see a summary with '-h')", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, { "name": "status", "invocation": "rstack dev status", diff --git a/crates/registry-cli-report/tests/envelope.rs b/crates/registry-cli-report/tests/envelope.rs index 99a2ec8954..43309bcd01 100644 --- a/crates/registry-cli-report/tests/envelope.rs +++ b/crates/registry-cli-report/tests/envelope.rs @@ -175,7 +175,7 @@ fn explicit_line(pointer: &str, line: Option) -> ExplicitSettingLine { pointer: Some(pointer.to_owned()), line, column: line.map(|_| 7), - summary: "admits access tokens typed JWT. ID tokens stay refused".to_owned(), + summary: "This setting admits access tokens typed JWT. ID tokens stay refused".to_owned(), } } @@ -205,12 +205,12 @@ fn explicit_settings_follow_the_posture_as_their_own_list_and_never_as_a_diagnos "pointer": "/authentication/oidc/issuers/staff/accessTokenType", "line": 12, "column": 7, - "summary": "admits access tokens typed JWT. ID tokens stay refused" + "summary": "This setting admits access tokens typed JWT. ID tokens stay refused" }, { "code": "platform.posture.jwt-access-token", "pointer": "/authentication/oidc/issuers/partners/accessTokenType", - "summary": "admits access tokens typed JWT. ID tokens stay refused" + "summary": "This setting admits access tokens typed JWT. ID tokens stay refused" } ]) ); @@ -246,11 +246,11 @@ fn an_explicit_setting_line_names_its_file_and_leaves_out_an_unknown_pointer() { "pointer": "/oidc/issuers/staff/accessTokenType", "line": 4, "column": 7, - "summary": "admits access tokens typed JWT. ID tokens stay refused" + "summary": "This setting admits access tokens typed JWT. ID tokens stay refused" }, { "code": "platform.posture.jwt-access-token", - "summary": "admits access tokens typed JWT. ID tokens stay refused" + "summary": "This setting admits access tokens typed JWT. ID tokens stay refused" } ]) ); diff --git a/crates/registry-coordinator/src/deployment.rs b/crates/registry-coordinator/src/deployment.rs index bac4b4f091..5ea68f56ed 100644 --- a/crates/registry-coordinator/src/deployment.rs +++ b/crates/registry-coordinator/src/deployment.rs @@ -582,7 +582,14 @@ async fn open_named( &runtime.database, url, runtime.development.as_ref(), - &|error| runtime.database_transport_error(error), + &|error| { + let member = if migration { + registry_platform_config::DatabaseMember::MigrationUrl + } else { + registry_platform_config::DatabaseMember::RuntimeUrl + }; + runtime.database_transport_error(error.at_url(member)) + }, ®istry_platform_config::resolve_database_host, )?; let tls = if verified_tls { @@ -609,9 +616,8 @@ fn driver_config( transport_error: &dyn Fn(registry_platform_config::DatabaseTransportError) -> CoordinatorError, resolve: ®istry_platform_config::HostResolver, ) -> Result<(tokio_postgres::Config, bool)> { - let postgres: tokio_postgres::Config = url - .parse() - .map_err(|_| fail("supply a valid PostgreSQL connection URL"))?; + let postgres = registry_platform_postgres::parse_runtime_url(url, database, development) + .map_err(transport_error)?; database .check(cfg!(feature = "postgres-test")) .map_err(transport_error)?; @@ -625,10 +631,10 @@ fn driver_config( if postgres.get_ssl_mode() != tokio_postgres::config::SslMode::Require { return Err(CoordinatorError::new( "database-tls-required", - "verified TLS requires sslmode=require in the database URL", + "verified TLS requires sslmode=require or sslmode=verify-full in the database URL", ) .at("runtime.yaml", "database.runtimeUrlRef") - .suggest("Add sslmode=require for a TLS database, or set database.transport: loopback-plaintext for PostgreSQL on this host.")); + .suggest("Add sslmode=verify-full for a TLS database, or set database.transport: loopback-plaintext for PostgreSQL on this host.")); } Ok((postgres, true)) } @@ -641,16 +647,19 @@ fn tls( let value = secrets .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(); - for cert in rustls::pki_types::CertificateDer::pem_slice_iter(value.expose_secret()) { - roots - .add(cert.map_err(|_| fail("supply valid PEM certificates"))?) - .map_err(|_| fail("supply valid PEM certificates"))?; - } - if roots.is_empty() { - return Err(fail("supply at least one trusted database root")); - } + let roots = + registry_platform_postgres::pem_root_store(value.expose_secret()).map_err(|error| { + match error { + registry_platform_postgres::PemRootsError::NoCertificate => { + fail("supply at least one trusted database root") + } + registry_platform_postgres::PemRootsError::TooLarge + | registry_platform_postgres::PemRootsError::InvalidPem + | registry_platform_postgres::PemRootsError::UnusableCertificate => { + fail("supply valid PEM certificates") + } + } + })?; Ok(tokio_postgres_rustls::MakeRustlsConnect::new( rustls::ClientConfig::builder() .with_root_certificates(roots) @@ -1143,6 +1152,30 @@ mod tests { use crate::definition::Definition; use std::collections::BTreeMap; + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config = registry_platform_config::DatabaseConfig { + runtime_url_ref: "secret:env/DB_RUNTIME".to_owned(), + migration_url_ref: "secret:env/DB_MIGRATION".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: None, + }; + let (postgres, tls) = super::driver_config( + &config, + "postgresql://app@db.example/registry?sslmode=verify-full", + None, + &|error| panic!("the TLS URL is refused: {error}"), + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert!(tls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_store_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping diff --git a/crates/registry-coordinator/src/provision.rs b/crates/registry-coordinator/src/provision.rs index 43124f7285..09ff60f1b6 100644 --- a/crates/registry-coordinator/src/provision.rs +++ b/crates/registry-coordinator/src/provision.rs @@ -11,11 +11,16 @@ use std::path::Path; use std::process::ExitCode; -use registry_platform_config::{DeclaredPosture, PostureReport, SecretResolver}; +use registry_platform_config::{ + DatabaseMember, DeclaredPosture, PostureReport, SecretError, SecretResolver, +}; use registry_platform_provision::cli::{ provision_transport, run_provision, OutputFormat, ProvisionArgs, ProvisionInput, }; -use registry_platform_provision::{ProductDatabase, SchemaLayout}; +use registry_platform_provision::{ + read_ca_bundle, secret_refusal, secret_refusal_code, url_not_text_refusal, ProductDatabase, + SchemaLayout, +}; use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; @@ -68,50 +73,40 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Some( - 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, - }; + let ca_pem = database + .ca_bundle_ref + .as_deref() + .map(|reference| { + read_ca_bundle(&resolver, "database", reference).map_err(|refused| vec![*refused]) + }) + .transpose()?; Ok(ProvisionInput { product: ProductDatabase { product: "coordinator", @@ -133,15 +128,27 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result<(), Box> { - let user = runtime_url - .trim() - .parse::() - .ok() - .and_then(|config| config.get_user().map(str::to_owned)); +/// would provision a role neither of them uses. The platform parser reports +/// invalid URLs. A parsed connection string without a user gets the role +/// mismatch code and a message that names only the configured role. +fn require_runtime_role( + runtime_url: &str, + expected: &str, + transport: registry_platform_config::DatabaseTransport, +) -> Result<(), Box> { + let config = registry_platform_postgres::parse_database_url( + runtime_url.trim(), + transport == registry_platform_config::DatabaseTransport::VerifiedTls, + ) + .map_err(|error| { + Box::new(Diagnostic::error( + error.code(), + "/database/runtimeUrlRef", + error.to_string(), + error.suggested_action(), + )) + })?; + let user = config.get_user().map(str::to_owned); match user.as_deref() { Some(user) if user == expected => Ok(()), Some(_) => Err(Box::new(Diagnostic::error( @@ -165,27 +172,15 @@ fn require_runtime_role(runtime_url: &str, expected: &str) -> Result<(), Box Result, Box> { - let secret = resolver.resolve(reference).map_err(|error| { - refusal( - pointer, - ®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.", - ) - })?; +) -> Result, Vec> { + let refused = |error: &SecretError| vec![secret_refusal("database", member, error)]; + let secret = member + .read(resolver, reference) + .map_err(|error| refused(&error))?; + let text = std::str::from_utf8(secret.expose_secret()) + .map_err(|_| vec![url_not_text_refusal("database", member)])?; Ok(Zeroizing::new(text.to_owned())) } diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index d633c8616f..43469a56f0 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -799,10 +799,10 @@ impl RuntimeConfig { &self, error: registry_platform_config::DatabaseTransportError, ) -> CoordinatorError { - let field = if self.database.test_only_plaintext { + let field = if self.database.test_only_plaintext && error.url_member().is_none() { "database.testOnlyPlaintext" } else { - "database.transport" + error.database_field() }; CoordinatorError::new(error.code(), error.to_string()) .at("runtime.yaml", field) diff --git a/crates/registry-coordinator/src/store.rs b/crates/registry-coordinator/src/store.rs index 3fd86ced67..1762bb1229 100644 --- a/crates/registry-coordinator/src/store.rs +++ b/crates/registry-coordinator/src/store.rs @@ -3534,7 +3534,13 @@ fn open_driver_config( tls: bool, resolve: ®istry_platform_config::HostResolver, ) -> Result { - let config: tokio_postgres::Config = database_url.parse().map_err(unavailable)?; + // A caller-supplied connector may implement a custom verifier, so this + // low-level constructor cannot promise verify-full. The deployment path + // builds its own hostname-verifying connector. + let config = + registry_platform_postgres::parse_database_url(database_url, false).map_err(|error| { + CoordinatorError::new(error.code(), error.to_string()).suggest(error.suggested_action()) + })?; let local = !config.get_hosts().is_empty() && config.get_hosts().iter().all(|host| match host { // The spelling is checked here; the shared check below diff --git a/crates/registry-coordinator/tests/caller_contract.rs b/crates/registry-coordinator/tests/caller_contract.rs index ab1e632305..299310a5db 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. This setting admits access tokens typed JWT. ID tokens stay refused." )), "{stdout}"); } diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index b4f4c2bc6f..4bf873a6b4 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -879,7 +879,7 @@ async fn split_activation_and_real_router_enforce_owned_progress_and_operator_re .expect("TLS is required"); assert_eq!(error.code, "database-tls-required"); assert_eq!(error.field.as_deref(), Some("database.runtimeUrlRef")); - assert_eq!(error.suggested_action.as_deref(), Some("Add sslmode=require for a TLS database, or set database.transport: loopback-plaintext for PostgreSQL on this host.")); + assert_eq!(error.suggested_action.as_deref(), Some("Add sslmode=verify-full for a TLS database, or set database.transport: loopback-plaintext for PostgreSQL on this host.")); let mut remote_url = runtime_url.clone(); remote_url.set_host(Some("10.0.0.5")).unwrap(); diff --git a/crates/registry-coordinator/tests/provision_cli.rs b/crates/registry-coordinator/tests/provision_cli.rs index a19b55ff2a..933488913b 100644 --- a/crates/registry-coordinator/tests/provision_cli.rs +++ b/crates/registry-coordinator/tests/provision_cli.rs @@ -21,7 +21,11 @@ fn runtime_file(directory: &Path) -> std::path::PathBuf { fs::create_dir(&secrets).unwrap(); fs::set_permissions(&secrets, fs::Permissions::from_mode(0o700)).unwrap(); let root_pem = secrets.join("postgres-root.pem"); - fs::write(&root_pem, "unused in print mode").unwrap(); + fs::write( + &root_pem, + registry_platform_provision::test_support::ca_bundle_pem(), + ) + .unwrap(); fs::set_permissions(&root_pem, fs::Permissions::from_mode(0o600)).unwrap(); let path = root.join("runtime.yaml"); fs::write( @@ -265,12 +269,20 @@ fn a_runtime_url_user_that_is_not_the_deployment_runtime_role_is_refused_before_ } #[test] -fn a_runtime_url_that_names_no_user_is_refused_as_missing_its_user() { +fn invalid_runtime_urls_and_runtime_urls_without_a_user_have_distinct_refusals() { let directory = tempfile::tempdir().unwrap(); let runtime = runtime_file(directory.path()); - for url in [ - "postgres://db.example.org:5432/coordinator", - "not a postgresql url", + for (url, code, message) in [ + ( + "postgres://db.example.org:5432/coordinator", + "coordinator.runtime-config.runtime-role-mismatch", + "the runtime database URL names no user", + ), + ( + "not a postgresql url", + "platform.database.invalid-url", + "the PostgreSQL connection URL is invalid", + ), ] { let output = provision_with( &runtime, @@ -278,19 +290,20 @@ fn a_runtime_url_that_names_no_user_is_refused_as_missing_its_user() { Some(database_url("coordinator_migration", MIGRATION_PASSWORD)), Some(url.to_owned()), ); - assert_refused( - &output, - "coordinator.runtime-config.runtime-role-mismatch", - "/database/runtimeUrlRef", - ); + let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); assert!( - stderr.contains("names no user"), - "the refusal says the URL has no user: {stderr}" + !stdout.contains(url) && !stderr.contains(url), + "the refusal leaked the configured input for {code}" + ); + assert_refused(&output, code, "/database/runtimeUrlRef"); + assert!( + stderr.contains(message), + "the refusal for {code} omits the expected message" ); assert!( !stderr.contains("does not log in as"), - "a missing user is not reported as another user: {stderr}" + "the refusal for {code} describes a different runtime user" ); } } @@ -370,7 +383,7 @@ fn an_unreadable_runtime_url_secret_is_refused_without_a_password() { ); assert_refused( &output, - "coordinator.runtime-config.refused", + "platform.provision.secret-unavailable", "/database/runtimeUrlRef", ); assert_unavailable_reason_and_fix(&output); @@ -388,14 +401,14 @@ fn an_unreadable_migration_url_secret_is_refused_without_a_password() { ); assert_refused( &output, - "coordinator.runtime-config.refused", + "platform.provision.secret-unavailable", "/database/migrationUrlRef", ); assert_unavailable_reason_and_fix(&output); } #[test] -fn a_certificate_authority_file_that_is_not_text_is_refused() { +fn a_certificate_authority_file_without_a_certificate_is_refused() { let directory = tempfile::tempdir().unwrap(); let runtime = runtime_file(directory.path()); let root_pem = directory.path().join("secrets/postgres-root.pem"); @@ -404,11 +417,11 @@ fn a_certificate_authority_file_that_is_not_text_is_refused() { let output = provision(&runtime, &["--print-sql"]); assert_refused( &output, - "coordinator.runtime-config.refused", + "platform.provision.ca-bundle-no-certificate", "/database/caBundleRef", ); let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("not UTF-8 text"), "{stderr}"); + assert!(stderr.contains("holds no PEM certificate"), "{stderr}"); } #[test] @@ -419,7 +432,7 @@ fn a_missing_certificate_authority_file_is_refused() { let output = provision(&runtime, &["--print-sql"]); assert_refused( &output, - "coordinator.runtime-config.refused", + "platform.provision.secret-unavailable", "/database/caBundleRef", ); } diff --git a/crates/registry-coordinator/tests/refusal_golden.rs b/crates/registry-coordinator/tests/refusal_golden.rs index 90fa9dc289..5673abc791 100644 --- a/crates/registry-coordinator/tests/refusal_golden.rs +++ b/crates/registry-coordinator/tests/refusal_golden.rs @@ -270,7 +270,39 @@ async fn production_caller_refusals_match_the_golden() { ("action-without-policy", good.expose(), forbidden), ] { let credential = format!("Bearer {token}"); - answers.insert(name.into(), answer(&app, Some(&credential), status).await); + use tracing::instrument::WithSubscriber as _; + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let response = answer(&app, Some(&credential), status) + .with_subscriber(logs.subscriber()) + .await; + if let Some((check, guidance)) = match name { + "wrong-audience" => Some(("token-audience", "aud claim")), + "expired" => Some(("token-time", "exp claim")), + "missing-scope" => Some(("scope", "coordinator:start")), + _ => None, + } { + let text = logs.text(); + assert!( + text.lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .any(|line| { + let fields = &line["fields"]; + let actionable = if check == "scope" { + fields["scope_claim"] == "scope" && fields["required_scope"] == guidance + } else { + fields["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(guidance)) + }; + fields["decision"] == "refused" + && fields["failed_check"] == check + && fields["trace_id"] == "0af7651916cd43dd8448eb211c80319c" + && actionable + }), + "{name}: diagnostic lacked {guidance}" + ); + } + answers.insert(name.into(), response); } let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/refusal_answers.json"); diff --git a/crates/registry-discovery-client-node/__test__/surface.test.js b/crates/registry-discovery-client-node/__test__/surface.test.js index eeed8d5903..a3f4d6047b 100644 --- a/crates/registry-discovery-client-node/__test__/surface.test.js +++ b/crates/registry-discovery-client-node/__test__/surface.test.js @@ -4,6 +4,7 @@ const assert = require('node:assert/strict'); const crypto = require('node:crypto'); const http = require('node:http'); const test = require('node:test'); +const { inspect } = require('node:util'); const { AcceptedServiceSelection, DiscoveryClient, @@ -215,13 +216,13 @@ test('search, resolve, and inert exact selection accept a development peer unles assert.equal(JSON.parse(JSON.stringify(selection)).recordId, 'record-a'); }); -test('a Discovery problem names its kind in kebab-case', async () => { +test('a Discovery problem names its kind in kebab-case and its code', async () => { const problems = [ - ['not-found', 404, 'Not found'], - ['invalid-request', 400, 'Invalid request'], - ['result-bound-exceeded', 422, 'Result bound exceeded'], + ['not-found', 404, 'Not found', 'request.not-found'], + ['invalid-request', 400, 'Invalid request', 'request.invalid'], + ['result-bound-exceeded', 422, 'Result bound exceeded', 'request.result-bound-exceeded'], ]; - for (const [name, status, title] of problems) { + for (const [name, status, title, code] of problems) { const server = http.createServer((_request, response) => { response.statusCode = status; response.setHeader('content-type', 'application/problem+json'); @@ -238,36 +239,79 @@ test('a Discovery problem names its kind in kebab-case', async () => { (error) => error instanceof DiscoveryClientError && error.kind === 'problem' && error.status === status - && error.problem === name, + && error.problem === name + && error.code === code + && error.problemType === undefined, ); await new Promise((resolve) => server.close(resolve)); } }); -test('an unrecognized problem uses only HTTP status semantics', async () => { - const server = http.createServer((_request, response) => { - response.statusCode = 409; - response.setHeader('content-type', 'application/problem+json'); - response.end(JSON.stringify({ - type: 'https://id.registrystack.org/problems/registry-discovery/future-conflict', - title: 'Future conflict', - status: 409, - code: 'future-conflict', - futureRecovery: { retry: false }, - })); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - const client = new DiscoveryClient(`http://127.0.0.1:${server.address().port}/`); - await assert.rejects( - client.searchEvidenceServices({ evidenceTypeId: 'urn:example:evidence-type' }), - (error) => error instanceof DiscoveryClientError - && error.kind === 'problem' - && error.status === 409 - && error.problem === undefined - && !error.message.includes('future-conflict') - && !error.message.includes('Future conflict'), - ); - await new Promise((resolve) => server.close(resolve)); +test('shared raw HTTP responses preserve the reader contract', async (t) => { + const fixtures = require('../../registry-discovery-client/tests/fixtures/http-responses.json'); + for (const fixture of fixtures) { + await t.test(fixture.name, async (t) => { + const server = http.createServer((_request, response) => { + response.statusCode = fixture.status; + response.setHeader('content-type', fixture.mediaType); + if (fixture.traceparents?.length) response.setHeader('traceparent', fixture.traceparents); + response.end(fixture.body); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + const client = new DiscoveryClient(`http://127.0.0.1:${server.address().port}/`); + const result = fixture.resolve + ? client.resolveEvidenceTypes({ requirementId: 'urn:example:requirement' }) + : client.searchEvidenceServices({ evidenceTypeId: 'urn:example:evidence-type' }); + if (fixture.kind === 'success') { + const found = await result; + assert.equal(found.items[0].recordId, 'record-a'); + assert.equal(Object.hasOwn(found, 'futureSearchMetadata'), false); + assert.equal(Object.hasOwn(found.items[0], 'futureServiceMetadata'), false); + } else { + await assert.rejects(result, (error) => { + assert.ok(error instanceof DiscoveryClientError); + assert.equal(error.kind, fixture.kind); + if (fixture.kind === 'problem') { + assert.equal(error.status, fixture.status); + assert.equal(error.problem, fixture.problem); + assert.equal(error.problemType, fixture.problemType); + assert.equal(error.code, fixture.code); + assert.equal(error.traceId, fixture.traceId); + assert.doesNotMatch(error.message, /service-(text|detail)-canary/u); + assert.doesNotMatch(JSON.stringify(error), /futureRecovery/u); + if (fixture.problemType) { + for (const rendered of [String(error), error.stack, inspect(error), JSON.stringify(error)]) { + assert.equal(rendered.includes(fixture.problemType), false); + assert.equal(rendered.includes(fixture.code), false); + } + } + } + return true; + }); + } + }); + } +}); + +test('persisted selection rejects positional and extended capability objects before acceptance', () => { + const valid = require('../../../products/discovery/fixtures/compatibility/pre-retirement-evidence-selection.json'); + const positional = [ + valid.recordId, valid.bindingId, valid.serviceId, valid.serviceKind, valid.endpointUrl, + valid.publisherId, null, null, null, null, valid.jurisdictions, valid.conformsTo, + valid.evidenceTypeIds, valid.semanticClassIds, valid.operationFamilyIds, + valid.matchedCapability, null, valid.originId, valid.originUrl, valid.originContentDigest, + valid.originFetchedAt, valid.catalogRevision, null, + ]; + for (const invalid of [ + positional, + { ...valid, matchedCapability: { ...valid.matchedCapability, unexpected: true } }, + { ...valid, matchedCapability: ['evidence-type', valid.matchedCapability.id] }, + ]) { + assert.throws(() => acceptSelection(invalid, () => assert.fail('invoked acceptance')), + (error) => error.kind === 'query'); + } + assert.deepEqual(validateSelectionStructure(valid), valid); }); test('adopter acceptance is explicit and precedes credentials or native traffic', () => { diff --git a/crates/registry-discovery-client-node/client.d.ts b/crates/registry-discovery-client-node/client.d.ts index e4fd04d0bc..a0c8e3fbef 100644 --- a/crates/registry-discovery-client-node/client.d.ts +++ b/crates/registry-discovery-client-node/client.d.ts @@ -128,6 +128,12 @@ export class DiscoveryClientError extends Error { readonly kind: DiscoveryClientErrorKind; readonly status?: number; readonly problem?: string; + /** The Discovery problem type of a problem this client does not recognise. */ + readonly problemType?: string; + /** A known problem's code, or the code an unrecognised problem supplied, when it supplied one. */ + readonly code?: string; + /** The validated trace identifier of an unrecognized Problem, when available. */ + readonly traceId?: string; readonly transportKind?: string; } diff --git a/crates/registry-discovery-client-node/client.js b/crates/registry-discovery-client-node/client.js index 8c06f7ecea..e299b23b43 100644 --- a/crates/registry-discovery-client-node/client.js +++ b/crates/registry-discovery-client-node/client.js @@ -15,8 +15,19 @@ class DiscoveryClientError extends Error { super(envelope.message); this.name = 'DiscoveryClientError'; this.kind = envelope.kind; - for (const field of ['status', 'problem', 'transportKind']) { - if (envelope[field] !== undefined && envelope[field] !== null) this[field] = envelope[field]; + for (const field of ['status', 'problem', 'problemType', 'code', 'traceId', 'transportKind']) { + const value = envelope[field]; + if (value === undefined || value === null) continue; + if (field === 'problemType' || (field === 'code' && envelope.problemType !== undefined)) { + Object.defineProperty(this, field, { + value, + configurable: true, + enumerable: false, + writable: true, + }); + } else { + this[field] = value; + } } } } diff --git a/crates/registry-discovery-client-node/src/lib.rs b/crates/registry-discovery-client-node/src/lib.rs index cbb4fe7e9d..1f8451580b 100644 --- a/crates/registry-discovery-client-node/src/lib.rs +++ b/crates/registry-discovery-client-node/src/lib.rs @@ -76,11 +76,20 @@ fn error(source: DiscoveryClientError) -> Error { "kind": "problem", "status": status, "problem": problem_name(problem), + "code": problem.code(), "message": "Discovery refused the request" }), - DiscoveryClientError::UnrecognizedProblem { status } => json!({ + DiscoveryClientError::UnrecognizedProblem { + status, + problem_type, + code, + trace_id, + } => json!({ "kind": "problem", "status": status, + "problemType": problem_type, + "code": code, + "traceId": trace_id, "message": "Discovery refused or failed the request with an unrecognized problem type" }), DiscoveryClientError::DevelopmentPeer => json!({ diff --git a/crates/registry-discovery-client-py/python/registry_discovery_client/__init__.pyi b/crates/registry-discovery-client-py/python/registry_discovery_client/__init__.pyi index e6f01b83c0..26cc785ba5 100644 --- a/crates/registry-discovery-client-py/python/registry_discovery_client/__init__.pyi +++ b/crates/registry-discovery-client-py/python/registry_discovery_client/__init__.pyi @@ -168,6 +168,9 @@ class DiscoveryClientError(Exception): status: int | None problem: str | None transport_kind: str | None + problem_type: str | None + code: str | None + trace_id: str | None class DiscoveryClient: def __init__( diff --git a/crates/registry-discovery-client-py/src/lib.rs b/crates/registry-discovery-client-py/src/lib.rs index 4a3a82e72f..6ae7ceaa72 100644 --- a/crates/registry-discovery-client-py/src/lib.rs +++ b/crates/registry-discovery-client-py/src/lib.rs @@ -71,13 +71,25 @@ fn client_error(py: Python<'_>, error: DiscoveryClientError) -> PyErr { instance .setattr("kind", kind(&error)) .expect("fresh exception"); - let (status, problem, transport_kind) = match error { - DiscoveryClientError::Problem { status, problem } => { - (Some(status), Some(problem_name(problem)), None) - } - DiscoveryClientError::UnrecognizedProblem { status } => (Some(status), None, None), - DiscoveryClientError::Transport { kind } => (None, None, Some(kind.kind())), - _ => (None, None, None), + instance + .setattr("trace_id", error.trace_id()) + .expect("fresh exception"); + let (status, problem, transport_kind, problem_type, code) = match error { + DiscoveryClientError::Problem { status, problem } => ( + Some(status), + Some(problem_name(problem)), + None, + None, + Some(problem.code().to_owned()), + ), + DiscoveryClientError::UnrecognizedProblem { + status, + problem_type, + code, + .. + } => (Some(status), None, None, Some(problem_type), code), + DiscoveryClientError::Transport { kind } => (None, None, Some(kind.kind()), None, None), + _ => (None, None, None, None, None), }; instance.setattr("status", status).expect("fresh exception"); instance @@ -86,6 +98,10 @@ fn client_error(py: Python<'_>, error: DiscoveryClientError) -> PyErr { instance .setattr("transport_kind", transport_kind) .expect("fresh exception"); + instance + .setattr("problem_type", problem_type) + .expect("fresh exception"); + instance.setattr("code", code).expect("fresh exception"); result } diff --git a/crates/registry-discovery-client-py/tests/python/test_client.py b/crates/registry-discovery-client-py/tests/python/test_client.py index 0986ae8ec3..e6227fc496 100644 --- a/crates/registry-discovery-client-py/tests/python/test_client.py +++ b/crates/registry-discovery-client-py/tests/python/test_client.py @@ -6,6 +6,7 @@ import json import threading import unittest +from pathlib import Path from bootstrap import ensure_built @@ -208,33 +209,16 @@ def log_message(self, format: str, *args: object) -> None: pass -class UnknownProblemHandler(http.server.BaseHTTPRequestHandler): - def do_GET(self) -> None: - body = json.dumps({ - "type": ( - "https://id.registrystack.org/problems/registry-discovery/" - "future-conflict" - ), - "title": "Future conflict", - "status": 409, - "code": "future-conflict", - "futureRecovery": {"retry": False}, - }).encode() - self.send_response(409) - self.send_header("Content-Type", "application/problem+json") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def log_message(self, format: str, *args: object) -> None: - pass - - PROBLEMS = { "not-found": (404, "Not found"), "invalid-request": (400, "Invalid request"), "result-bound-exceeded": (422, "Result bound exceeded"), } +CODES = { + "not-found": "request.not-found", + "invalid-request": "request.invalid", + "result-bound-exceeded": "request.result-bound-exceeded", +} class DiscoveryClientTests(unittest.TestCase): @@ -254,6 +238,8 @@ def test_a_problem_names_its_kind_in_kebab_case(self) -> None: self.assertEqual(caught.exception.kind, "problem") self.assertEqual(caught.exception.status, status) self.assertEqual(caught.exception.problem, name) + self.assertEqual(caught.exception.code, CODES[name]) + self.assertIsNone(caught.exception.problem_type) finally: server.shutdown() server.server_close() @@ -328,28 +314,87 @@ def test_search_resolve_and_inert_selection(self) -> None: self.assertEqual(json.loads(json.dumps(selection))["recordId"], "record-a") - def test_an_unrecognized_problem_uses_only_http_status_semantics(self) -> None: - server = http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), - UnknownProblemHandler, + def test_persisted_selection_refuses_positional_and_extended_capability_objects(self) -> None: + fixture = ( + Path(__file__).resolve().parents[4] + / "products/discovery/fixtures/compatibility/pre-retirement-evidence-selection.json" ) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - client = DiscoveryClient(f"http://127.0.0.1:{server.server_port}/") + valid = json.loads(fixture.read_text()) + fields = ( + "recordId bindingId serviceId serviceKind endpointUrl publisherId operatorId " + "registryAuthorityId legalIssuerId technicalProviderId jurisdictions conformsTo " + "evidenceTypeIds semanticClassIds operationFamilyIds matchedCapability evidenceResolution " + "originId originUrl originContentDigest originFetchedAt catalogRevision mappingRevision" + ) + for invalid in ( + [valid.get(field) for field in fields.split()], + {**valid, "matchedCapability": {**valid["matchedCapability"], "unexpected": True}}, + {**valid, "matchedCapability": ["evidence-type", valid["matchedCapability"]["id"]]}, + ): with self.assertRaises(DiscoveryClientError) as caught: - client.search_evidence_services({ - "evidenceTypeId": "urn:example:evidence-type", - }) - self.assertEqual(caught.exception.kind, "problem") - self.assertEqual(caught.exception.status, 409) - self.assertIsNone(caught.exception.problem) - self.assertNotIn("future-conflict", str(caught.exception)) - self.assertNotIn("Future conflict", str(caught.exception)) - finally: - server.shutdown() - server.server_close() - thread.join() + accept_selection(invalid, lambda _: self.fail("invoked acceptance")) + self.assertEqual(caught.exception.kind, "query") + self.assertEqual(validate_selection_structure(valid), valid) + + def test_shared_raw_http_responses(self) -> None: + fixtures = ( + Path(__file__).resolve().parents[3] + / "registry-discovery-client/tests/fixtures/http-responses.json" + ) + for case in json.loads(fixtures.read_text()): + with self.subTest(case=case["name"]): + class FixtureHandler(Handler): + def do_GET(self) -> None: + self.respond() + + def do_POST(self) -> None: + self.respond() + + def respond(self) -> None: + body = case["body"].encode() + self.send_response(case["status"]) + self.send_header("Content-Type", case["mediaType"]) + self.send_header("Content-Length", str(len(body))) + for header in case.get("traceparents", []): + self.send_header("traceparent", header) + self.end_headers() + self.wfile.write(body) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), FixtureHandler) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + client = DiscoveryClient(f"http://127.0.0.1:{server.server_port}/") + filters = {"evidenceTypeId": "urn:example:evidence-type"} + if case["kind"] == "success": + result = client.search_evidence_services(filters) + self.assertEqual(result["items"][0]["recordId"], "record-a") + self.assertNotIn("futureSearchMetadata", result) + self.assertNotIn("futureServiceMetadata", result["items"][0]) + else: + with self.assertRaises(DiscoveryClientError) as caught: + if case.get("resolve"): + client.resolve_evidence_types({"requirementId": "urn:example:requirement"}) + else: + client.search_evidence_services(filters) + error = caught.exception + self.assertEqual(error.kind, case["kind"]) + if case["kind"] == "problem": + self.assertEqual(error.status, case["status"]) + self.assertEqual(error.problem, case.get("problem")) + self.assertEqual(error.problem_type, case.get("problemType")) + self.assertEqual(error.code, case["code"]) + self.assertEqual(error.trace_id, case.get("traceId")) + self.assertNotIn("service-text-canary", str(error)) + self.assertNotIn("service-detail-canary", str(error)) + self.assertNotIn("futureRecovery", vars(error)) + if case.get("problemType"): + for diagnostic in (str(error), repr(error)): + self.assertNotIn(case["problemType"], diagnostic) + self.assertNotIn(case["code"], diagnostic) + finally: + server.shutdown() + thread.join() def test_exact_local_acceptance_precedes_credentials_and_native_io(self) -> None: selection = evidence_selection() diff --git a/crates/registry-discovery-client-py/tests/python/test_drift.py b/crates/registry-discovery-client-py/tests/python/test_drift.py index 1d01400ba2..ccb1736771 100644 --- a/crates/registry-discovery-client-py/tests/python/test_drift.py +++ b/crates/registry-discovery-client-py/tests/python/test_drift.py @@ -35,7 +35,15 @@ "validate_selection_structure", } RUNTIME_NAMES = RUNTIME_CLASS_NAMES | RUNTIME_FUNCTION_NAMES -ERROR_ATTRIBUTES = {"kind", "status", "problem", "transport_kind"} +ERROR_ATTRIBUTES = { + "kind", + "status", + "problem", + "transport_kind", + "problem_type", + "code", + "trace_id", +} EXPECTED_PACKAGE_FILES = {"__init__.py", "__init__.pyi", "py.typed"} DIGEST = "sha256:" + "1" * 64 diff --git a/crates/registry-discovery-client/Cargo.toml b/crates/registry-discovery-client/Cargo.toml index a1730eb994..5880ab1995 100644 --- a/crates/registry-discovery-client/Cargo.toml +++ b/crates/registry-discovery-client/Cargo.toml @@ -15,6 +15,7 @@ workspace = true registry-discovery = { workspace = true, default-features = false } registry-discovery-profile.workspace = true registry-platform-canonical-json.workspace = true +registry-platform-httpsec.workspace = true registry-platform-httputil.workspace = true reqwest.workspace = true serde.workspace = true diff --git a/crates/registry-discovery-client/src/client.rs b/crates/registry-discovery-client/src/client.rs index 0a1c159883..996b8e5643 100644 --- a/crates/registry-discovery-client/src/client.rs +++ b/crates/registry-discovery-client/src/client.rs @@ -12,6 +12,7 @@ use registry_discovery::{ MAXIMUM_RESULT_RECORDS, }; use registry_platform_canonical_json::parse_json_strict; +use registry_platform_httpsec::{response_trace_id, TraceId}; use registry_platform_httputil::client::{ build_client, read_failure_kind, send_failure_kind, OutboundOptions, ServiceBaseUrl, }; @@ -22,7 +23,7 @@ use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; -use crate::wire::{EvidenceTypeResolveWire, ServiceSearchWire}; +use crate::wire::{EvidenceTypeResolveWire, Named, ServiceSearchWire}; use crate::{DiscoveryClientError, DiscoveryProblem}; const JSON: &str = "application/json"; @@ -277,6 +278,11 @@ impl DiscoveryClient { return Err(DiscoveryClientError::Protocol); } let content_type = response_content_type(response.headers()); + let response_trace = if status.is_success() { + None + } else { + response_trace_id(response.headers()).ok() + }; let maximum = if status.is_success() { self.maximum_response_bytes } else { @@ -300,7 +306,7 @@ impl DiscoveryClient { { return Err(DiscoveryClientError::Protocol); } - Err(problem_from_response(status, &bytes)?) + Err(problem_from_response(status, &bytes, response_trace)?) } } } @@ -382,15 +388,18 @@ fn quoted_media_parameter(value: &str) -> bool { fn strict_decode(bytes: &[u8]) -> Result { let value = parse_json_strict(bytes).map_err(|_| DiscoveryClientError::Protocol)?; - serde_json::from_value(value).map_err(|_| DiscoveryClientError::Protocol) + serde_json::from_value::>(value) + .map(|Named(decoded)| decoded) + .map_err(|_| DiscoveryClientError::Protocol) } #[derive(Deserialize)] struct ProblemBody { #[serde(rename = "type")] type_uri: String, - title: String, status: u16, + #[serde(rename = "title")] + _title: String, #[serde(flatten)] additional: serde_json::Map, } @@ -398,63 +407,93 @@ struct ProblemBody { fn problem_from_response( status: StatusCode, bytes: &[u8], + response_trace: Option, ) -> Result { let body: ProblemBody = strict_decode(bytes)?; if body.status != status.as_u16() { return Err(DiscoveryClientError::Protocol); } - let (problem, expected_code) = match (body.type_uri.as_str(), body.title.as_str()) { - ( - "https://id.registrystack.org/problems/registry-discovery/invalid-request", - "Invalid request", - ) if status == StatusCode::BAD_REQUEST => { - (DiscoveryProblem::InvalidRequest, "request.invalid") + // Retain a trace only when the header and body agree. Correlation is + // optional in the native client, including for legacy Problem documents. + let trace_id = response_trace.filter(|trace| { + body.additional + .get("traceId") + .and_then(serde_json::Value::as_str) + == Some(trace.as_str()) + }); + // Classification reads the type, status and code only; `title` and + // `detail` are prose a compatible server may reword. + let problem = match body.type_uri.as_str() { + "https://id.registrystack.org/problems/registry-discovery/invalid-request" + if status == StatusCode::BAD_REQUEST => + { + DiscoveryProblem::InvalidRequest } - ("https://id.registrystack.org/problems/registry-discovery/not-found", "Not found") + "https://id.registrystack.org/problems/registry-discovery/not-found" if status == StatusCode::NOT_FOUND => { - (DiscoveryProblem::NotFound, "request.not-found") + DiscoveryProblem::NotFound + } + "https://id.registrystack.org/problems/registry-discovery/result-bound-exceeded" + if status == StatusCode::UNPROCESSABLE_ENTITY => + { + DiscoveryProblem::ResultBoundExceeded } - ( - "https://id.registrystack.org/problems/registry-discovery/result-bound-exceeded", - "Result bound exceeded", - ) if status == StatusCode::UNPROCESSABLE_ENTITY => ( - DiscoveryProblem::ResultBoundExceeded, - "request.result-bound-exceeded", - ), - ("https://id.registrystack.org/problems/registry-discovery/unavailable", "Unavailable") + "https://id.registrystack.org/problems/registry-discovery/unavailable" if status == StatusCode::SERVICE_UNAVAILABLE => { - (DiscoveryProblem::Unavailable, "service.unavailable") + DiscoveryProblem::Unavailable } _ if known_problem_type(&body.type_uri) => return Err(DiscoveryClientError::Protocol), _ if valid_unrecognized_problem(&body, status) => { + let code = match body.additional.get("code") { + None => None, + Some(serde_json::Value::String(code)) if valid_supplied_code(code) => { + Some(code.clone()) + } + Some(_) => return Err(DiscoveryClientError::Protocol), + }; return Ok(DiscoveryClientError::UnrecognizedProblem { status: status.as_u16(), + problem_type: body.type_uri, + code, + trace_id, }); } _ => return Err(DiscoveryClientError::Protocol), }; - validate_supplied_code(&body, expected_code)?; + match body.additional.get("code") { + // Legacy documents carry no `code`. + None => {} + Some(serde_json::Value::String(code)) if code == problem.code() => {} + // A later release may add a more specific code under a known type: keep + // the type and code rather than claim a protocol failure. A code that + // names another known problem contradicts the type. + Some(serde_json::Value::String(code)) + if valid_supplied_code(code) + && !KNOWN_PROBLEMS.iter().any(|known| known.code() == code) => + { + return Ok(DiscoveryClientError::UnrecognizedProblem { + status: status.as_u16(), + problem_type: body.type_uri, + code: Some(code.clone()), + trace_id, + }); + } + Some(_) => return Err(DiscoveryClientError::Protocol), + } Ok(DiscoveryClientError::Problem { status: status.as_u16(), problem, }) } -/// Legacy documents carry no `code`. When a known problem supplies one it must -/// be that problem's code; every other supplied member stays opaque and bounded -/// by the whole problem-body limit. -fn validate_supplied_code( - body: &ProblemBody, - expected_code: &str, -) -> Result<(), DiscoveryClientError> { - match body.additional.get("code") { - None => Ok(()), - Some(value) if value.as_str() == Some(expected_code) => Ok(()), - Some(_) => Err(DiscoveryClientError::Protocol), - } -} +const KNOWN_PROBLEMS: [DiscoveryProblem; 4] = [ + DiscoveryProblem::InvalidRequest, + DiscoveryProblem::NotFound, + DiscoveryProblem::ResultBoundExceeded, + DiscoveryProblem::Unavailable, +]; fn known_problem_type(type_uri: &str) -> bool { matches!( @@ -473,13 +512,16 @@ fn valid_unrecognized_problem(body: &ProblemBody, status: StatusCode) -> bool { }; (status.is_client_error() || status.is_server_error()) && valid_problem_code(code) - && !body.title.is_empty() - && body.title.chars().count() <= 128 - && !body.title.chars().any(char::is_control) && body.type_uri.chars().count() <= 256 && url::Url::parse(&body.type_uri).is_ok_and(|uri| uri.as_str() == body.type_uri) } +/// A supplied code is dot-separated lowercase kebab segments, the shape of +/// both the current `family.reason` codes and the older type-suffix codes. +fn valid_supplied_code(code: &str) -> bool { + code.len() <= 128 && code.split('.').all(valid_problem_code) +} + fn valid_problem_code(code: &str) -> bool { !code.is_empty() && code.len() <= 128 @@ -913,7 +955,24 @@ mod tests { body: serde_json::Value, traceparents: &[&str], ) -> DiscoveryClientError { - let bytes = serde_json::to_vec(&body).unwrap(); + exchange_response( + StatusCode::BAD_REQUEST, + PROBLEM_JSON, + serde_json::to_vec(&body).unwrap(), + traceparents, + false, + ) + .await + .expect_err("fixture responds with a problem") + } + + async fn exchange_response( + status: StatusCode, + media_type: &'static str, + bytes: Vec, + traceparents: &[&str], + resolve: bool, + ) -> Result { let parents = traceparents .iter() .map(|value| reqwest::header::HeaderValue::from_str(value).unwrap()) @@ -924,8 +983,7 @@ mod tests { let bytes = bytes.clone(); let parents = parents.clone(); async move { - let mut response = - response_with_media_type(StatusCode::BAD_REQUEST, PROBLEM_JSON, bytes); + let mut response = response_with_media_type(status, media_type, bytes); for parent in parents { response.headers_mut().append("traceparent", parent); } @@ -940,9 +998,117 @@ mod tests { url::Url::parse(&format!("http://{address}")).unwrap(), )) .unwrap(); - let result = client.search_services(ServiceFilters::default()).await; + let result = if resolve { + client + .resolve_evidence_types(EvidenceTypeResolveRequest { + requirement_id: "urn:example:requirement".into(), + jurisdiction: None, + }) + .await + .map(|response| serde_json::to_value(response).unwrap()) + } else { + client + .search_services(ServiceFilters::default()) + .await + .map(|response| serde_json::to_value(response).unwrap()) + }; server.abort(); - result.expect_err("fixture responds with a problem") + result + } + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct HttpResponseFixture { + name: String, + status: u16, + media_type: String, + body: String, + #[serde(default)] + traceparents: Vec, + kind: String, + #[serde(default)] + resolve: bool, + problem: Option, + problem_type: Option, + code: Option, + trace_id: Option, + } + + #[tokio::test] + async fn shared_raw_http_responses_preserve_the_reader_contract() { + let cases: Vec = + serde_json::from_str(include_str!("../tests/fixtures/http-responses.json")).unwrap(); + for case in cases { + let parents: Vec<_> = case.traceparents.iter().map(String::as_str).collect(); + let media_type = match case.media_type.as_str() { + JSON => JSON, + PROBLEM_JSON => PROBLEM_JSON, + _ => panic!("unexpected fixture media type"), + }; + let result = exchange_response( + StatusCode::from_u16(case.status).unwrap(), + media_type, + case.body.into_bytes(), + &parents, + case.resolve, + ) + .await; + if case.kind == "success" { + let response = result.expect(&case.name); + assert_eq!(response["items"][0]["recordId"], "record-a"); + assert!(response.get("futureSearchMetadata").is_none()); + assert!(response["items"][0].get("futureServiceMetadata").is_none()); + continue; + } + let error = result.expect_err(&case.name); + if case.kind == "protocol" { + assert_eq!(error, DiscoveryClientError::Protocol, "{}", case.name); + } else if case.problem.is_some() { + let DiscoveryClientError::Problem { status, problem } = &error else { + panic!("{}: {error}", case.name); + }; + assert_eq!(*status, case.status, "{}", case.name); + assert_eq!(Some(problem.code()), case.code.as_deref(), "{}", case.name); + } else { + let DiscoveryClientError::UnrecognizedProblem { + status, + problem_type, + code, + .. + } = &error + else { + panic!("{}: {error}", case.name); + }; + assert_eq!(*status, case.status, "{}", case.name); + assert_eq!( + Some(problem_type), + case.problem_type.as_ref(), + "{}", + case.name + ); + assert_eq!(code, &case.code, "{}", case.name); + assert_eq!( + DiscoveryClientError::trace_id(&error), + case.trace_id.as_deref(), + "{}", + case.name + ); + assert!( + !format!("{error:?} {error}").contains(problem_type), + "{}", + case.name + ); + if let Some(code) = code { + assert!( + !format!("{error:?} {error}").contains(code), + "{}", + case.name + ); + } + } + assert!(!format!("{error:?} {error}").contains("service-text-canary")); + assert!(!format!("{error:?} {error}").contains("service-detail-canary")); + } } #[tokio::test] @@ -977,8 +1143,12 @@ mod tests { } #[tokio::test] - async fn a_supplied_code_must_match_the_known_problem() { - for value in [json!("service.unavailable"), json!(null)] { + async fn a_known_problem_cannot_carry_another_known_problems_code_or_a_malformed_one() { + for value in [ + json!("service.unavailable"), + json!(null), + json!("Not A Code"), + ] { let mut body = legacy_problem(); body["code"] = value; assert!(matches!( @@ -988,6 +1158,54 @@ mod tests { } } + /// A 1.x server may add a more specific code under an existing type. The + /// client keeps that type and code instead of reporting a protocol failure. + #[tokio::test] + async fn a_known_problem_type_with_a_new_code_keeps_its_type_and_code() { + let mut body = legacy_problem(); + body["code"] = json!("request.query-too-long"); + assert_eq!( + exchange_problem(body, &[]).await, + DiscoveryClientError::UnrecognizedProblem { + status: 400, + problem_type: + "https://id.registrystack.org/problems/registry-discovery/invalid-request" + .into(), + code: Some("request.query-too-long".into()), + trace_id: None, + } + ); + } + + #[tokio::test] + async fn a_known_problem_type_at_another_status_is_a_protocol_failure() { + let body = json!({ + "type": "https://id.registrystack.org/problems/registry-discovery/not-found", + "status": 400, + "title": "Reworded not found", + "code": "request.not-found", + }); + assert_eq!( + exchange_problem(body, &[]).await, + DiscoveryClientError::Protocol + ); + } + + #[test] + fn each_known_problem_names_its_code() { + for (problem, code) in [ + (DiscoveryProblem::InvalidRequest, "request.invalid"), + (DiscoveryProblem::NotFound, "request.not-found"), + ( + DiscoveryProblem::ResultBoundExceeded, + "request.result-bound-exceeded", + ), + (DiscoveryProblem::Unavailable, "service.unavailable"), + ] { + assert_eq!(problem.code(), code); + } + } + #[tokio::test] async fn real_client_resolves_and_searches_in_one_exact_exchange_each() { let (client, _) = client(Mode::Valid, 1024 * 1024).await; @@ -1149,11 +1367,25 @@ mod tests { } #[tokio::test] - async fn problem_title_must_match_the_closed_problem_contract() { + async fn problem_title_and_detail_never_change_the_known_problem() { let (client, _) = client(Mode::WrongProblemTitle, 1024 * 1024).await; assert_eq!( client.search_services(ServiceFilters::default()).await, - Err(DiscoveryClientError::Protocol) + Err(DiscoveryClientError::Problem { + status: 400, + problem: DiscoveryProblem::InvalidRequest, + }) + ); + let mut reworded = legacy_problem(); + reworded["title"] = json!("Reworded title"); + reworded["detail"] = json!("Reworded guidance from a compatible server."); + reworded["code"] = json!("request.invalid"); + assert_eq!( + exchange_problem(reworded, &[]).await, + DiscoveryClientError::Problem { + status: 400, + problem: DiscoveryProblem::InvalidRequest, + } ); } @@ -1190,7 +1422,7 @@ mod tests { } #[tokio::test] - async fn unrecognized_problem_types_fall_back_to_http_status_without_service_values() { + async fn an_unrecognized_problem_keeps_its_type_and_code_and_drops_service_text() { let (client, _) = client(Mode::UnknownProblem, 1024 * 1024).await; let error = client .search_services(ServiceFilters::default()) @@ -1198,14 +1430,48 @@ mod tests { .expect_err("an unrecognized problem remains an HTTP error"); assert_eq!( error, - DiscoveryClientError::UnrecognizedProblem { status: 409 } + DiscoveryClientError::UnrecognizedProblem { + status: 409, + problem_type: + "https://id.registrystack.org/problems/registry-discovery/future-conflict" + .into(), + code: Some("future-conflict".into()), + trace_id: None, + } ); let rendered = format!("{error:?} {error}"); - assert!(!rendered.contains("future-conflict")); assert!(!rendered.contains("Future conflict")); assert!(!rendered.contains("futureRecovery")); } + #[tokio::test] + async fn an_unrecognized_problem_decodes_whatever_its_title_and_without_a_code() { + let body = json!({ + "type": "https://id.registrystack.org/problems/registry-discovery/future-limit", + "title": "x".repeat(400), + "status": 400, + "detail": "Guidance from a newer server.", + }); + assert_eq!( + exchange_problem(body.clone(), &[]).await, + DiscoveryClientError::UnrecognizedProblem { + status: 400, + problem_type: + "https://id.registrystack.org/problems/registry-discovery/future-limit".into(), + code: None, + trace_id: None, + } + ); + for code in [json!("Not A Code"), json!(7), json!("")] { + let mut refused = body.clone(); + refused["code"] = code; + assert_eq!( + exchange_problem(refused, &[]).await, + DiscoveryClientError::Protocol + ); + } + } + #[tokio::test] async fn unknown_known_field_meaning_is_refused() { let (client, _) = client(Mode::UnknownServiceKind, 1024 * 1024).await; diff --git a/crates/registry-discovery-client/src/error.rs b/crates/registry-discovery-client/src/error.rs index 548e0caff2..e6f7ebacc8 100644 --- a/crates/registry-discovery-client/src/error.rs +++ b/crates/registry-discovery-client/src/error.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 //! Closed, value-free Registry Discovery client failures. +use std::fmt; + +use registry_platform_httpsec::TraceId; use registry_platform_httputil::TransportKind; use thiserror::Error; @@ -13,6 +16,18 @@ pub enum DiscoveryProblem { Unavailable, } +impl DiscoveryProblem { + /// The problem code Discovery registers for this problem. + pub const fn code(self) -> &'static str { + match self { + Self::InvalidRequest => "request.invalid", + Self::NotFound => "request.not-found", + Self::ResultBoundExceeded => "request.result-bound-exceeded", + Self::Unavailable => "service.unavailable", + } + } +} + impl std::fmt::Display for DiscoveryProblem { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str(match self { @@ -24,7 +39,7 @@ impl std::fmt::Display for DiscoveryProblem { } } -#[derive(Debug, Error, Clone, PartialEq, Eq)] +#[derive(Error, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum DiscoveryClientError { #[error( @@ -57,15 +72,65 @@ pub enum DiscoveryClientError { status: u16, problem: DiscoveryProblem, }, - /// A valid Problem whose type is newer than this client. Only its HTTP - /// status carries semantics; service-authored text and extensions are discarded. + /// A valid Problem whose type, or whose code under a known type, is newer + /// than this client. It keeps the Discovery problem type and, when the + /// server supplied one, its bounded code. A trace identifier survives when + /// the Problem and response header agree. Prose and other extensions are discarded. #[error("Discovery refused or failed the request: status {status}, unrecognized problem type")] - UnrecognizedProblem { status: u16 }, + UnrecognizedProblem { + status: u16, + problem_type: String, + code: Option, + trace_id: Option, + }, #[error("the Discovery response did not satisfy its closed wire contract")] Protocol, } +impl fmt::Debug for DiscoveryClientError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DevelopmentPeer => formatter.write_str("DevelopmentPeer"), + Self::Configuration => formatter.write_str("Configuration"), + Self::Query => formatter.write_str("Query"), + Self::NoMatchingService => formatter.write_str("NoMatchingService"), + Self::AmbiguousSelection => formatter.write_str("AmbiguousSelection"), + Self::NoMatchingAlternative => formatter.write_str("NoMatchingAlternative"), + Self::AmbiguousAlternative => formatter.write_str("AmbiguousAlternative"), + Self::CapabilityMismatch => formatter.write_str("CapabilityMismatch"), + Self::LocalAcceptanceRefused => formatter.write_str("LocalAcceptanceRefused"), + Self::SelectionChanged => formatter.write_str("SelectionChanged"), + Self::Transport { kind } => formatter + .debug_struct("Transport") + .field("kind", kind) + .finish(), + Self::Problem { status, problem } => formatter + .debug_struct("Problem") + .field("status", status) + .field("problem", problem) + .finish(), + Self::UnrecognizedProblem { + status, trace_id, .. + } => formatter + .debug_struct("UnrecognizedProblem") + .field("status", status) + .field("trace_id", trace_id) + .finish_non_exhaustive(), + Self::Protocol => formatter.write_str("Protocol"), + } + } +} + impl DiscoveryClientError { + /// Returns the validated trace identifier for an unrecognized Problem, if present. + #[must_use] + pub fn trace_id(&self) -> Option<&str> { + match self { + Self::UnrecognizedProblem { trace_id, .. } => trace_id.as_ref().map(TraceId::as_str), + _ => None, + } + } + pub(crate) const fn transport(kind: TransportKind) -> Self { Self::Transport { kind } } @@ -95,7 +160,13 @@ mod tests { status: 503, problem: DiscoveryProblem::Unavailable, }, - DiscoveryClientError::UnrecognizedProblem { status: 409 }, + DiscoveryClientError::UnrecognizedProblem { + status: 409, + problem_type: "https://id.registrystack.org/problems/registry-discovery/future" + .into(), + code: Some("future".into()), + trace_id: None, + }, ]; for error in errors { let rendered = format!("{error:?} {error}"); diff --git a/crates/registry-discovery-client/src/selection.rs b/crates/registry-discovery-client/src/selection.rs index cc2c43a5ff..f555012228 100644 --- a/crates/registry-discovery-client/src/selection.rs +++ b/crates/registry-discovery-client/src/selection.rs @@ -11,31 +11,78 @@ use url::Url; use crate::{ client::{validate_resolve_response_shape, validate_search_response_shape}, + wire::Named, DiscoveryClientError, EvidenceServiceQuery, }; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[serde(tag = "kind", content = "id", rename_all = "kebab-case")] pub enum MatchedCapability { EvidenceType(String), } -/// Complete, inert provenance for one resolved Evidence Type AND-list. -/// -/// This is discovery metadata, not a request or a trust decision. Keeping the -/// whole list prevents a saved selection from turning one required set of -/// Evidence Types into a single, lossy type identifier. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct EvidenceResolutionContext { - pub requirement_id: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub jurisdiction: Option, - pub mapping_revision: String, - pub evidence_type_list_id: String, - pub evidence_type_ids: Vec, - pub mapping_id: String, - pub mapping_authority_id: String, +impl<'de> Deserialize<'de> for MatchedCapability { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Fields { + kind: String, + id: String, + } + + let Named(Fields { kind, id }) = Named::deserialize(deserializer)?; + match kind.as_str() { + "evidence-type" => Ok(Self::EvidenceType(id)), + _ => Err(serde::de::Error::custom("unknown matched capability kind")), + } + } +} + +// Declare saved selection fields once and deserialize through a private map-only proxy. +macro_rules! named_selection_struct { + ($(#[$metadata:meta])* $model:ident, $remote:literal { $($fields:tt)* }) => { + $(#[$metadata])* + #[derive(Clone, Debug, Serialize, PartialEq, Eq)] + #[serde(rename_all = "camelCase")] + pub struct $model { + $($fields)* + } + + impl<'de> Deserialize<'de> for $model { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(remote = $remote, deny_unknown_fields, rename_all = "camelCase")] + struct Fields { + $($fields)* + } + + #[derive(Deserialize)] + #[serde(transparent)] + struct Object(#[serde(with = "Fields")] $model); + + let Named(Object(value)) = Named::deserialize(deserializer)?; + Ok(value) + } + } + }; +} + +named_selection_struct! { + /// Complete, inert provenance for one resolved Evidence Type AND-list. + /// + /// This is discovery metadata, not a request or a trust decision. Keeping the + /// whole list prevents a saved selection from turning one required set of + /// Evidence Types into a single, lossy type identifier. + EvidenceResolutionContext, "EvidenceResolutionContext" { + pub requirement_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jurisdiction: Option, + pub mapping_revision: String, + pub evidence_type_list_id: String, + pub evidence_type_ids: Vec, + pub mapping_id: String, + pub mapping_authority_id: String, + } } impl EvidenceResolutionContext { @@ -142,39 +189,39 @@ pub struct SelectionRequest { pub mapping_revision: Option, } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct ServiceSelection { - pub record_id: String, - pub binding_id: String, - pub service_id: String, - pub service_kind: ServiceKind, - pub endpoint_url: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub publisher_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub operator_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub registry_authority_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub legal_issuer_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub technical_provider_id: Option, - pub jurisdictions: Vec, - pub conforms_to: Vec, - pub evidence_type_ids: Vec, - pub semantic_class_ids: Vec, - pub operation_family_ids: Vec, - pub matched_capability: MatchedCapability, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub evidence_resolution: Option, - pub origin_id: String, - pub origin_url: String, - pub origin_content_digest: String, - pub origin_fetched_at: String, - pub catalog_revision: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mapping_revision: Option, +named_selection_struct! { + ServiceSelection, "ServiceSelection" { + pub record_id: String, + pub binding_id: String, + pub service_id: String, + pub service_kind: ServiceKind, + pub endpoint_url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub publisher_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operator_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub registry_authority_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub legal_issuer_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub technical_provider_id: Option, + pub jurisdictions: Vec, + pub conforms_to: Vec, + pub evidence_type_ids: Vec, + pub semantic_class_ids: Vec, + pub operation_family_ids: Vec, + pub matched_capability: MatchedCapability, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub evidence_resolution: Option, + pub origin_id: String, + pub origin_url: String, + pub origin_content_digest: String, + pub origin_fetched_at: String, + pub catalog_revision: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mapping_revision: Option, + } } impl ServiceSelection { @@ -1062,6 +1109,75 @@ mod tests { assert_eq!(serde_json::to_vec(&selection).unwrap(), fixture); } + #[test] + fn persisted_selection_refuses_positional_objects_and_unknown_capability_members() { + let fixture = include_bytes!( + "../../../products/discovery/fixtures/compatibility/pre-retirement-evidence-selection.json" + ); + let selection: serde_json::Value = serde_json::from_slice(fixture).unwrap(); + let fields = [ + "recordId", + "bindingId", + "serviceId", + "serviceKind", + "endpointUrl", + "publisherId", + "operatorId", + "registryAuthorityId", + "legalIssuerId", + "technicalProviderId", + "jurisdictions", + "conformsTo", + "evidenceTypeIds", + "semanticClassIds", + "operationFamilyIds", + "matchedCapability", + "evidenceResolution", + "originId", + "originUrl", + "originContentDigest", + "originFetchedAt", + "catalogRevision", + "mappingRevision", + ]; + let positional = fields + .iter() + .map(|field| selection[*field].clone()) + .collect(); + let mut positional_resolution = selection.clone(); + positional_resolution["evidenceResolution"] = serde_json::json!([ + "urn:requirement", + null, + format!("sha256:{}", "1".repeat(64)), + "urn:list", + ["urn:evidence"], + "urn:mapping", + "urn:authority" + ]); + let mut positional_capability = selection.clone(); + positional_capability["matchedCapability"] = + serde_json::json!(["evidence-type", "urn:evidence"]); + let mut unknown_capability = selection; + unknown_capability["matchedCapability"]["unexpected"] = serde_json::json!(true); + let accepted: Vec<_> = [ + ("selection", serde_json::Value::Array(positional)), + ("resolution", positional_resolution), + ("capability", positional_capability), + ("unknown capability member", unknown_capability), + ] + .into_iter() + .filter_map(|(name, value)| { + serde_json::from_value::(value) + .is_ok() + .then_some(name) + }) + .collect(); + assert!( + accepted.is_empty(), + "accepted invalid objects: {accepted:?}" + ); + } + #[test] fn persisted_relay_selection_is_refused_by_the_current_wire_type() { let fixture = include_bytes!( diff --git a/crates/registry-discovery-client/src/wire.rs b/crates/registry-discovery-client/src/wire.rs index 76f6374d3e..b44e60647a 100644 --- a/crates/registry-discovery-client/src/wire.rs +++ b/crates/registry-discovery-client/src/wire.rs @@ -5,7 +5,35 @@ use registry_discovery::{ EvidenceTypeResolveResponse, ResolvedAlternative, ServiceKind, ServiceRecord, ServiceSearchResponse, }; -use serde::Deserialize; +use std::{fmt, marker::PhantomData}; + +use serde::{ + de::{value::MapAccessDeserializer, MapAccess, Visitor}, + Deserialize, Deserializer, +}; + +/// Deserialize a named JSON object without accepting positional struct input. +pub(crate) struct Named(pub(crate) T); + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Named { + fn deserialize>(deserializer: D) -> Result { + struct NamedVisitor(PhantomData); + + impl<'de, T: Deserialize<'de>> Visitor<'de> for NamedVisitor { + type Value = Named; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("a named object") + } + + fn visit_map>(self, map: A) -> Result { + T::deserialize(MapAccessDeserializer::new(map)).map(Named) + } + } + + deserializer.deserialize_map(NamedVisitor(PhantomData)) + } +} /// These wire models deliberately omit `deny_unknown_fields`: response objects /// may gain additive members in a compatible server release. Known members @@ -18,7 +46,7 @@ pub(crate) struct EvidenceTypeResolveWire { #[serde(default)] jurisdiction: Option, mapping_revision: String, - alternatives: Vec, + alternatives: Vec>, } #[derive(Deserialize)] @@ -39,7 +67,7 @@ impl From for EvidenceTypeResolveResponse { alternatives: value .alternatives .into_iter() - .map(ResolvedAlternative::from) + .map(|Named(alternative)| alternative.into()) .collect(), } } @@ -60,7 +88,7 @@ impl From for ResolvedAlternative { #[serde(rename_all = "camelCase")] pub(crate) struct ServiceSearchWire { catalog_revision: String, - items: Vec, + items: Vec>, } #[derive(Deserialize)] @@ -98,7 +126,11 @@ impl From for ServiceSearchResponse { fn from(value: ServiceSearchWire) -> Self { Self { catalog_revision: value.catalog_revision, - items: value.items.into_iter().map(ServiceRecord::from).collect(), + items: value + .items + .into_iter() + .map(|Named(service)| service.into()) + .collect(), } } } diff --git a/crates/registry-discovery-client/tests/compatibility_metadata.rs b/crates/registry-discovery-client/tests/compatibility_metadata.rs index 2798521706..577736e353 100644 --- a/crates/registry-discovery-client/tests/compatibility_metadata.rs +++ b/crates/registry-discovery-client/tests/compatibility_metadata.rs @@ -3,8 +3,8 @@ use registry_platform_canonical_json::parse_json_strict; use serde_json::json; -const ADDITIVE_RESPONSE_PROOF: &str = - "registry-discovery-client::client::tests::real_client_ignores_additive_response_members_at_every_response_level"; +const RESPONSE_COMPATIBILITY_PROOF: &str = + "registry-discovery-client::client::tests::shared_raw_http_responses_preserve_the_reader_contract"; #[test] fn unified_sdk_metadata_names_the_tested_discovery_patch_line_and_proof() { @@ -27,8 +27,8 @@ fn unified_sdk_metadata_names_the_tested_discovery_patch_line_and_proof() { "compatibleServerPatchLine": "0.51.x", "responseCompatibility": { "additiveObjectMembers": "ignored-after-duplicate-key-rejection", - "unknownProblemCodes": "http-status-only", - "proof": ADDITIVE_RESPONSE_PROOF + "unknownProblemCodes": "retained-with-problem-type-when-valid", + "proof": RESPONSE_COMPATIBILITY_PROOF } } } diff --git a/crates/registry-discovery-client/tests/fixtures/http-responses.json b/crates/registry-discovery-client/tests/fixtures/http-responses.json new file mode 100644 index 0000000000..a3ed8c4cdd --- /dev/null +++ b/crates/registry-discovery-client/tests/fixtures/http-responses.json @@ -0,0 +1,215 @@ +[ + { + "name": "additive-search", + "status": 200, + "mediaType": "application/json", + "body": "{\"catalogRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"items\":[{\"recordId\":\"record-a\",\"serviceId\":\"urn:example:service:a\",\"serviceKind\":\"evidence\",\"title\":\"Evidence service\",\"description\":\"Issues minimum-disclosure evidence\",\"endpointUrl\":\"https://provider.example/evidence\",\"publisherId\":\"urn:example:publisher\",\"legalIssuerId\":\"urn:example:legal-issuer\",\"technicalProviderId\":\"urn:example:technical-provider\",\"jurisdictions\":[\"urn:example:jurisdiction\"],\"conformsTo\":[\"urn:example:profile\"],\"evidenceTypeIds\":[\"urn:example:evidence-type\"],\"semanticClassIds\":[],\"operationFamilyIds\":[],\"originId\":\"origin-a\",\"originUrl\":\"https://provider.example/catalog.jsonld\",\"originContentDigest\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"originFetchedAt\":\"2026-08-15T00:00:00Z\",\"bindingId\":\"urn:registrystack:discovery:binding:sha256:3a316636cd4b722c008a02dcf61633c7be64aa85bc9d3c20d932a0a2e8e06129\",\"futureServiceMetadata\":{\"label\":\"ignored\"}}],\"futureSearchMetadata\":{\"label\":\"ignored\"}}", + "kind": "success" + }, + { + "name": "future", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/future-conflict\",\"status\":409,\"code\":\"future-conflict\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ], + "kind": "problem", + "problemType": "https://id.registrystack.org/problems/registry-discovery/future-conflict", + "code": "future-conflict", + "traceId": "11111111111111111111111111111111" + }, + { + "name": "missing-trace", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/future-conflict\",\"status\":409,\"code\":\"future-conflict\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "traceparents": [], + "kind": "problem", + "problemType": "https://id.registrystack.org/problems/registry-discovery/future-conflict", + "code": "future-conflict" + }, + { + "name": "malformed-trace", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/future-conflict\",\"status\":409,\"code\":\"future-conflict\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "traceparents": [ + "invalid" + ], + "kind": "problem", + "problemType": "https://id.registrystack.org/problems/registry-discovery/future-conflict", + "code": "future-conflict" + }, + { + "name": "duplicate-trace", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/future-conflict\",\"status\":409,\"code\":\"future-conflict\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01", + "00-11111111111111111111111111111111-2222222222222222-01" + ], + "kind": "problem", + "problemType": "https://id.registrystack.org/problems/registry-discovery/future-conflict", + "code": "future-conflict" + }, + { + "name": "mismatched-trace", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/future-conflict\",\"status\":409,\"code\":\"future-conflict\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "traceparents": [ + "00-33333333333333333333333333333333-2222222222222222-01" + ], + "kind": "problem", + "problemType": "https://id.registrystack.org/problems/registry-discovery/future-conflict", + "code": "future-conflict" + }, + { + "name": "refined", + "status": 400, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/invalid-request\",\"status\":400,\"code\":\"request.query-too-long\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ], + "kind": "problem", + "problemType": "https://id.registrystack.org/problems/registry-discovery/invalid-request", + "code": "request.query-too-long", + "traceId": "11111111111111111111111111111111" + }, + { + "name": "contradictory-code", + "status": 400, + "mediaType": "application/problem+json", + "body": "{\"type\": \"https://id.registrystack.org/problems/registry-discovery/invalid-request\", \"status\": 400, \"code\": \"service.unavailable\", \"traceId\": \"11111111111111111111111111111111\", \"title\": \"service-text-canary\", \"detail\": \"service-detail-canary\", \"futureRecovery\": {\"retry\": false}}", + "kind": "protocol" + }, + { + "name": "duplicate-problem-member", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\": \"https://id.registrystack.org/problems/registry-discovery/future-conflict\", \"status\": 409, \"code\": \"future-conflict\", \"traceId\": \"11111111111111111111111111111111\", \"title\": \"service-text-canary\", \"detail\": \"service-detail-canary\", \"futureRecovery\": {\"retry\": false},\"code\":\"future-conflict\"}", + "kind": "protocol", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ] + }, + { + "name": "wrong-required-shape", + "status": 200, + "mediaType": "application/json", + "body": "{\"catalogRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"items\":{}}", + "kind": "protocol" + }, + { + "name": "duplicate-search-member", + "status": 200, + "mediaType": "application/json", + "body": "{\"catalogRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"items\":[],\"items\":[]}", + "kind": "protocol" + }, + { + "name": "reworded-title", + "status": 400, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/invalid-request\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "kind": "problem", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ], + "problem": "invalid-request", + "code": "request.invalid" + }, + { + "name": "missing-title", + "status": 400, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/invalid-request\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"11111111111111111111111111111111\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "kind": "protocol", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ] + }, + { + "name": "mistyped-title", + "status": 400, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/invalid-request\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"11111111111111111111111111111111\",\"title\":7,\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "kind": "protocol", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ] + }, + { + "name": "status-mismatch", + "status": 409, + "mediaType": "application/problem+json", + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-discovery/invalid-request\",\"status\":400,\"code\":\"request.invalid\",\"traceId\":\"11111111111111111111111111111111\",\"title\":\"service-text-canary\",\"detail\":\"service-detail-canary\",\"futureRecovery\":{\"retry\":false}}", + "kind": "protocol", + "traceparents": [ + "00-11111111111111111111111111111111-2222222222222222-01" + ] + }, + { + "name": "missing-search-items", + "status": 200, + "mediaType": "application/json", + "body": "{\"catalogRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\"}", + "kind": "protocol" + }, + { + "name": "positional-search", + "status": 200, + "mediaType": "application/json", + "body": "[\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",[]]", + "kind": "protocol" + }, + { + "name": "positional-service", + "status": 200, + "mediaType": "application/json", + "body": "{\"catalogRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"items\":[[\"record-a\",\"urn:registrystack:discovery:binding:sha256:3a316636cd4b722c008a02dcf61633c7be64aa85bc9d3c20d932a0a2e8e06129\",\"urn:example:service:a\",\"evidence\",\"Evidence service\",\"Issues minimum-disclosure evidence\",\"https://provider.example/evidence\",\"urn:example:publisher\",null,null,\"urn:example:legal-issuer\",\"urn:example:technical-provider\",[\"urn:example:jurisdiction\"],[\"urn:example:profile\"],[\"urn:example:evidence-type\"],[],[],\"origin-a\",\"https://provider.example/catalog.jsonld\",\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"2026-08-15T00:00:00Z\"]]}", + "kind": "protocol" + }, + { + "name": "missing-service-id", + "status": 200, + "mediaType": "application/json", + "body": "{\"catalogRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"items\":[{\"recordId\":\"record-a\",\"serviceKind\":\"evidence\",\"title\":\"Evidence service\",\"description\":\"Issues minimum-disclosure evidence\",\"endpointUrl\":\"https://provider.example/evidence\",\"publisherId\":\"urn:example:publisher\",\"legalIssuerId\":\"urn:example:legal-issuer\",\"technicalProviderId\":\"urn:example:technical-provider\",\"jurisdictions\":[\"urn:example:jurisdiction\"],\"conformsTo\":[\"urn:example:profile\"],\"evidenceTypeIds\":[\"urn:example:evidence-type\"],\"semanticClassIds\":[],\"operationFamilyIds\":[],\"originId\":\"origin-a\",\"originUrl\":\"https://provider.example/catalog.jsonld\",\"originContentDigest\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"originFetchedAt\":\"2026-08-15T00:00:00Z\",\"bindingId\":\"urn:registrystack:discovery:binding:sha256:3a316636cd4b722c008a02dcf61633c7be64aa85bc9d3c20d932a0a2e8e06129\",\"futureServiceMetadata\":{\"label\":\"ignored\"}}]}", + "kind": "protocol" + }, + { + "name": "positional-resolution", + "status": 200, + "mediaType": "application/json", + "body": "[\"urn:example:requirement\",null,\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",[]]", + "kind": "protocol", + "resolve": true + }, + { + "name": "positional-alternative", + "status": 200, + "mediaType": "application/json", + "body": "{\"requirementId\":\"urn:example:requirement\",\"mappingRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"alternatives\":[[\"urn:example:list\",[\"urn:example:evidence-type\"],\"urn:example:mapping\",\"urn:example:authority\"]]}", + "kind": "protocol", + "resolve": true + }, + { + "name": "missing-resolve-alternatives", + "status": 200, + "mediaType": "application/json", + "body": "{\"requirementId\":\"urn:example:requirement\",\"mappingRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\"}", + "kind": "protocol", + "resolve": true + }, + { + "name": "duplicate-alternative-member", + "status": 200, + "mediaType": "application/json", + "body": "{\"requirementId\": \"urn:example:requirement\", \"mappingRevision\": \"sha256:1111111111111111111111111111111111111111111111111111111111111111\", \"alternatives\": [{\"evidenceTypeListId\":\"urn:list\",\"evidenceTypeListId\":\"urn:list\",\"evidenceTypeIds\":[\"urn:evidence\"],\"mappingId\":\"urn:mapping\",\"mappingAuthorityId\":\"urn:authority\"}]}", + "kind": "protocol", + "resolve": true + } +] diff --git a/crates/registry-discovery/src/model.rs b/crates/registry-discovery/src/model.rs index 6ff13d7562..cb7788aaa1 100644 --- a/crates/registry-discovery/src/model.rs +++ b/crates/registry-discovery/src/model.rs @@ -262,7 +262,7 @@ pub static LOOPBACK_CATALOG_URL: registry_platform_config::DevelopmentSetting = registry_platform_config::DevelopmentSetting { code: "discovery.posture.loopback-catalog-url", key: "catalogUrl", - summary: "the index advertises an address on the reader's own machine", + summary: "The index advertises an address on the reader's own machine", production: "Publish HTTPS URLs on non-loopback hosts.", }; diff --git a/crates/registry-discoveryctl/src/lib.rs b/crates/registry-discoveryctl/src/lib.rs index af5710aaca..4041ed0c0b 100644 --- a/crates/registry-discoveryctl/src/lib.rs +++ b/crates/registry-discoveryctl/src/lib.rs @@ -1143,7 +1143,7 @@ mod tests { let warning = |pointer: &str| { format!( "warning[discovery.posture.loopback-catalog-url] {} {pointer}\n \ - the index advertises an address on the reader's own machine; production refuses it\n \ + The index advertises an address on the reader's own machine; production refuses it\n \ next: Publish HTTPS URLs on non-loopback hosts.\n", index.display() ) diff --git a/crates/registry-documents/src/auth.rs b/crates/registry-documents/src/auth.rs index 0261db61c6..212eeb60b5 100644 --- a/crates/registry-documents/src/auth.rs +++ b/crates/registry-documents/src/auth.rs @@ -796,6 +796,45 @@ pub(crate) mod tests { ); } + #[tokio::test] + async fn a_wrong_audience_or_expired_token_logs_the_claim_to_change() { + let mut other_audience = citizen_claims(); + other_audience["aud"] = json!("urn:example:another-service"); + let refused = authenticator() + .authenticate_declaring(&token(other_audience)) + .await + .expect_err("a token for another audience is refused"); + assert_eq!( + refused.error, + AuthenticationError::Refused(FailedCheck::TokenAudience) + ); + assert!( + refused + .remedy + .is_some_and(|remedy| remedy.contains("aud") && remedy.contains("audience")), + "{:?}", + refused.remedy + ); + + let mut expired = citizen_claims(); + let issued = chrono::Utc::now().timestamp() - 3_600; + expired["iat"] = json!(issued); + expired["exp"] = json!(issued + 300); + let refused = authenticator() + .authenticate_declaring(&token(expired)) + .await + .expect_err("an expired token is refused"); + assert_eq!( + refused.error, + AuthenticationError::Refused(FailedCheck::TokenTime) + ); + assert!( + refused.remedy.is_some_and(|remedy| remedy.contains("exp")), + "{:?}", + refused.remedy + ); + } + #[tokio::test] async fn a_jwt_typed_token_is_admitted_when_the_issuer_states_it() { let stating = authenticator_with(verifier_typed(AccessTokenType::Jwt), DeclaredKinds::None); diff --git a/crates/registry-documents/src/store.rs b/crates/registry-documents/src/store.rs index 338df54c31..a6391e94ad 100644 --- a/crates/registry-documents/src/store.rs +++ b/crates/registry-documents/src/store.rs @@ -7,7 +7,6 @@ //! activation transaction, and [`PostgresStore::ready`] refuses a database //! whose applied versions are not exactly the ones this release carries. -use std::str::FromStr; use std::time::Duration; use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; @@ -119,7 +118,7 @@ impl PostgresStore { Self::connect_reference( config, secrets, - "database.runtimeUrlRef", + registry_platform_config::DatabaseMember::RuntimeUrl, &config.runtime_url_ref, posture, witness, @@ -142,7 +141,7 @@ impl PostgresStore { Self::connect_reference( config, secrets, - "database.migrationUrlRef", + registry_platform_config::DatabaseMember::MigrationUrl, &config.migration_url_ref, posture, witness, @@ -152,13 +151,17 @@ impl PostgresStore { fn connect_reference( config: &DatabaseConfig, secrets: &SecretResolver, - field: &'static str, + member: registry_platform_config::DatabaseMember, reference: &str, posture: Posture, witness: Option<&DevelopmentWitness>, ) -> Result { let protected = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure(field, reference, &error)) + StoreError::SecretConfiguration(describe_secret_failure( + &format!("database.{member}"), + reference, + &error, + )) })?; let url = std::str::from_utf8(protected.expose_secret()) .map_err(|_| StoreError::Configuration)?; @@ -166,6 +169,7 @@ impl PostgresStore { config, url, witness, + member, ®istry_platform_config::resolve_database_host, )?; let manager_config = ManagerConfig { @@ -394,20 +398,8 @@ fn tls_connector( &error, )) })?; - let mut roots = rustls::RootCertStore::empty(); - use rustls::pki_types::pem::PemObject as _; - let mut count = 0usize; - for certificate in - rustls::pki_types::CertificateDer::pem_slice_iter(certificate.expose_secret()) - { - roots - .add(certificate.map_err(|_| StoreError::Configuration)?) - .map_err(|_| StoreError::Configuration)?; - count += 1; - } - if count == 0 { - return Err(StoreError::Configuration); - } + let roots = registry_platform_postgres::pem_root_store(certificate.expose_secret()) + .map_err(|_| StoreError::Configuration)?; let client = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); @@ -516,9 +508,11 @@ fn driver_config( config: &DatabaseConfig, url: &str, witness: Option<&DevelopmentWitness>, + member: registry_platform_config::DatabaseMember, resolve: ®istry_platform_config::HostResolver, ) -> Result<(PgConfig, bool), StoreError> { - let postgres = PgConfig::from_str(url).map_err(|_| StoreError::Configuration)?; + let postgres = registry_platform_postgres::parse_runtime_url(url, config, witness) + .map_err(|error| error.at_url(member))?; if postgres.get_user().is_none() || postgres.get_dbname().is_none() { return Err(StoreError::Configuration); } @@ -540,6 +534,30 @@ mod driver_config_tests { use super::*; + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config = registry_platform_config::DatabaseConfig { + runtime_url_ref: "secret:env/DB_RUNTIME".to_owned(), + migration_url_ref: "secret:env/DB_MIGRATION".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: None, + }; + let (postgres, tls) = driver_config( + &config, + "postgresql://app@db.example/registry?sslmode=verify-full", + None, + registry_platform_config::DatabaseMember::RuntimeUrl, + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert!(tls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping @@ -562,6 +580,7 @@ mod driver_config_tests { &config, "postgresql://app@localhost:5433/documents", None, + registry_platform_config::DatabaseMember::RuntimeUrl, &fixed, ) .unwrap(); diff --git a/crates/registry-documents/tests/refusal_golden.rs b/crates/registry-documents/tests/refusal_golden.rs index 00cc017a0a..b7dc6bf3e8 100644 --- a/crates/registry-documents/tests/refusal_golden.rs +++ b/crates/registry-documents/tests/refusal_golden.rs @@ -670,6 +670,20 @@ async fn every_refusal_is_counted_and_logged_under_the_check_it_failed() { "{}", fixture.name ); + let expected_remedy = match fixture.name { + "foreign-audience" => Some("aud claim"), + "expired" => Some("exp claim"), + _ => None, + }; + if let Some(claim) = expected_remedy { + assert!( + fields["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(claim)), + "{}: the operator diagnostic names the token claim", + fixture.name + ); + } *logged.entry(fixture.check.as_str()).or_default() += 1; } } diff --git a/crates/registry-documentsctl/src/operate.rs b/crates/registry-documentsctl/src/operate.rs index d3221d7eac..099f99516b 100644 --- a/crates/registry-documentsctl/src/operate.rs +++ b/crates/registry-documentsctl/src/operate.rs @@ -359,7 +359,7 @@ pub(crate) fn failure(path: &Path, declared: DeclaredPosture, error: RuntimeErro } => { let diagnostic = Diagnostic::error( error.code(), - "/database/transport", + error.database_pointer(), error.to_string(), error.suggested_action(), ); diff --git a/crates/registry-documentsctl/src/provision.rs b/crates/registry-documentsctl/src/provision.rs index c95751348d..3b8d953d42 100644 --- a/crates/registry-documentsctl/src/provision.rs +++ b/crates/registry-documentsctl/src/provision.rs @@ -8,9 +8,10 @@ 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, DatabaseMember, PostureReport}; +use registry_platform_config::{DatabaseMember, PostureReport, SecretError}; use registry_platform_provision::{ - provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, + provision_transport, read_ca_bundle, secret_refusal, secret_refusal_code, url_not_text_refusal, + ProductDatabase, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; @@ -33,6 +34,17 @@ fn refused(code: &str, path: &str, message: String, action: &str) -> Box Vec { + diagnostic.artifact = Some(DOCUMENTS_RUNTIME_KIND.to_owned()); + vec![diagnostic] +} + +/// The shared refusal of a database member's secret or public document. +fn secret_refused(member: DatabaseMember, error: &SecretError) -> Vec { + in_runtime_file(secret_refusal("database", member, error)) +} + /// Reads the runtime file exactly as `apply` does and resolves the two /// database URLs and the CA behind `database.caBundleRef`. pub(crate) fn load( @@ -62,37 +74,27 @@ pub(crate) fn load( ), } })?; - let secrets = config.secret_resolver().map_err(|error| { - refuse( - "config.refused", - "/secretProviders", - error.to_string(), - "Correct secretProviders in the runtime file, then run provision again.", - ) - })?; - let resolve = |member: DatabaseMember, reference: &str| { - let read = member.read(&secrets, reference); - read.map_err(|error| { + let secrets = config + .secret_providers + .resolver(config.development.as_ref()) + .map_err(|error| { refuse( - "config.refused", - &format!("/database/{member}"), - describe_secret_failure(&format!("database.{member}"), reference, &error), + secret_refusal_code(&error), + "/secretProviders", + error.to_string(), error.suggested_action(), ) - }) + })?; + let resolve = |member: DatabaseMember, reference: &str| { + member + .read(&secrets, reference) + .map_err(|error| secret_refused(member, &error)) }; 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( - "config.refused", - &format!("/database/{member}"), - format!("database.{member} is not UTF-8 text"), - "Put a PostgreSQL URL in the secret, then run provision again.", - ) - }) + .map_err(|_| in_runtime_file(url_not_text_refusal("database", member))) }; let migration_url = url( DatabaseMember::MigrationUrl, @@ -103,9 +105,11 @@ pub(crate) fn load( .database .ca_bundle_ref .as_deref() - .map(|reference| resolve(DatabaseMember::CaBundle, reference)) - .transpose()? - .map(|secret| secret.expose_secret().to_vec()); + .map(|reference| { + read_ca_bundle(&secrets, "database", reference) + .map_err(|refused| in_runtime_file(*refused)) + }) + .transpose()?; Ok(ProvisionInput { product: product(), migration_url, diff --git a/crates/registry-documentsctl/tests/provision_cli.rs b/crates/registry-documentsctl/tests/provision_cli.rs index 8fd0345eef..d7997f3dd3 100644 --- a/crates/registry-documentsctl/tests/provision_cli.rs +++ b/crates/registry-documentsctl/tests/provision_cli.rs @@ -359,7 +359,10 @@ fn a_missing_database_secret_is_refused_at_its_member() { let runtime = write_runtime(directory.path()); std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); let diagnostic = loader_refusal(&runtime); - assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["code"], "platform.provision.secret-unavailable", + "{diagnostic}" + ); assert_eq!( diagnostic["path"], "/database/runtimeUrlRef", "{diagnostic}" @@ -373,7 +376,10 @@ fn a_database_secret_that_is_not_text_is_refused_at_its_member() { let secret = directory.path().join("secrets/migration-database-url"); std::fs::write(&secret, [0xff, 0xfe, 0xfd]).unwrap(); let diagnostic = loader_refusal(&runtime); - assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["code"], "platform.provision.secret-value-invalid", + "{diagnostic}" + ); assert_eq!( diagnostic["path"], "/database/migrationUrlRef", "{diagnostic}" @@ -392,8 +398,142 @@ fn a_missing_ca_bundle_secret_is_refused_at_its_member() { ); std::fs::write(&runtime, text).unwrap(); let diagnostic = loader_refusal(&runtime); - assert_eq!(diagnostic["code"], "config.refused", "{diagnostic}"); + assert_eq!( + diagnostic["code"], "platform.provision.secret-unavailable", + "{diagnostic}" + ); + assert_eq!(diagnostic["path"], "/database/caBundleRef", "{diagnostic}"); +} + +/// Name `secrets/database-ca` as the runtime file's `database.caBundleRef`. +fn add_ca_bundle(runtime: &str) { + let text = std::fs::read_to_string(runtime).unwrap().replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/database-ca\n", + ); + std::fs::write(runtime, text).unwrap(); +} + +#[test] +fn a_refused_secret_or_public_document_names_its_fix_once() { + const CERTIFICATE: &[u8] = b"-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + const PRIVATE_KEY: &[u8] = b"-----BEGIN PRIVATE KEY-----\nMII\n-----END PRIVATE KEY-----\n"; + enum Refused { + /// A migration URL secret that others can read. + ReadableUrl, + /// A CA bundle with these bytes and this mode. + CaBundle(&'static [u8], u32), + } + let cases = [ + ( + "Remove access for others", + "platform.provision.secret-file-unsafe", + Refused::ReadableUrl, + ), + ( + "Remove write access for others", + "platform.provision.public-document-unsafe", + Refused::CaBundle(CERTIFICATE, 0o646), + ), + ( + "keep the private key in its own secret file", + "platform.provision.public-document-private-key", + Refused::CaBundle(PRIVATE_KEY, 0o644), + ), + ( + "Put the database server's root certificates in the bundle", + "platform.provision.ca-bundle-no-certificate", + Refused::CaBundle(&[0xff, 0xfe, 0xfd], 0o644), + ), + ]; + for (fix, code, refused) in cases { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let (path, mode) = match refused { + Refused::CaBundle(bytes, mode) => { + add_ca_bundle(&runtime); + let path = directory.path().join("secrets/database-ca"); + std::fs::write(&path, bytes).unwrap(); + (path, mode) + } + Refused::ReadableUrl => ( + directory.path().join("secrets/migration-database-url"), + 0o644, + ), + }; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.status.code(), Some(1), "{text}"); + assert_eq!(text.matches(fix).count(), 1, "{fix}: {text}"); + + let report: serde_json::Value = { + let output = ctl(&[ + "--format", + "json", + "provision", + "--runtime-config", + &runtime, + "--print-sql", + ]); + serde_json::from_slice(&output.stdout).unwrap() + }; + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], code, "{diagnostic}"); + let message = diagnostic["message"].as_str().unwrap(); + let action = diagnostic["suggestedAction"].as_str().unwrap(); + assert!(action.contains(fix), "{diagnostic}"); + assert!(!message.contains(action), "{diagnostic}"); + } +} + +#[test] +fn an_empty_database_secret_is_refused_at_its_member() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + std::fs::write(directory.path().join("secrets/runtime-database-url"), "").unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!( + diagnostic["code"], "platform.provision.secret-value-invalid", + "{diagnostic}" + ); + assert_eq!( + diagnostic["path"], "/database/runtimeUrlRef", + "{diagnostic}" + ); +} + +#[test] +fn print_mode_reads_the_ca_bundle_as_apply_and_the_runtime_do() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + add_ca_bundle(&runtime); + let bundle = directory.path().join("secrets/database-ca"); + std::fs::write(&bundle, "a bundle that names a root but holds none\n").unwrap(); + std::fs::set_permissions(&bundle, std::fs::Permissions::from_mode(0o644)).unwrap(); + let diagnostic = loader_refusal(&runtime); + assert_eq!( + diagnostic["code"], "platform.provision.ca-bundle-no-certificate", + "{diagnostic}" + ); assert_eq!(diagnostic["path"], "/database/caBundleRef", "{diagnostic}"); + + std::fs::write( + &bundle, + registry_platform_provision::test_support::ca_bundle_pem(), + ) + .unwrap(); + let output = ctl(&["provision", "--runtime-config", &runtime, "--print-sql"]); + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); } #[test] diff --git a/crates/registry-evidence-client-node/README.md b/crates/registry-evidence-client-node/README.md index 9930b26e01..46782c6dc8 100644 --- a/crates/registry-evidence-client-node/README.md +++ b/crates/registry-evidence-client-node/README.md @@ -142,10 +142,14 @@ the other verification mode's kind is refused. ### Error mapping A mapped failure surfaces to a caller as an `EvidenceClientError`, exported -from the package root. Its `kind` is always present; `status`, `code`, -`traceId`, `retryAfterSeconds`, `transportKind`, and `tokenKind` are present -when the underlying failure carries them. `message` is human prose, not JSON: -read it, do not parse it. `kind` is one of: `configuration`, `nonce`, `token`, +from the package root. Its `kind` is always present. `status`, `code`, +`problemType`, `traceId`, `retryAfterSeconds`, `transportKind`, and +`tokenKind` appear when supplied by the underlying failure. A structurally +valid future Problem keeps its identifiers as structured properties and +uses the existing HTTP status category. Read the non-enumerable Problem +`code` and `problemType` properties directly on the error. +Read `message` as human prose and branch on `kind`. The kinds are +`configuration`, `nonce`, `token`, `transport`, `denied`, `not-available`, `invalid-request`, `unavailable`, `protocol`, `development-peer`, `verification`. diff --git a/crates/registry-evidence-client-node/__test__/drift.test.js b/crates/registry-evidence-client-node/__test__/drift.test.js index 0794884cfd..536d99c65f 100644 --- a/crates/registry-evidence-client-node/__test__/drift.test.js +++ b/crates/registry-evidence-client-node/__test__/drift.test.js @@ -278,6 +278,7 @@ test('client.d.ts declares no EvidenceClientError field client.js never sets', ( 'kind', 'status', 'code', + 'problemType', 'traceId', 'retryAfterSeconds', 'transportKind', diff --git a/crates/registry-evidence-client-node/__test__/errors.test.js b/crates/registry-evidence-client-node/__test__/errors.test.js index ccb57b17fe..5ef17d9602 100644 --- a/crates/registry-evidence-client-node/__test__/errors.test.js +++ b/crates/registry-evidence-client-node/__test__/errors.test.js @@ -2,8 +2,11 @@ const assert = require('node:assert/strict'); const { test } = require('node:test'); +const { inspect } = require('node:util'); -const { EvidenceClient, EvidenceClientError } = require('..'); +const responseFixtures = require('../../../products/platform/fixtures/client-response-tolerance/evidence.json'); + +const { EvidenceClient, EvidenceClientError, SdJwtVcBatchResponse } = require('..'); const { startStubServer } = require('./helpers/stub-server'); const { generateSigningKey, signEvidence, requestSpec, evidenceFor } = require('./helpers/live-signing'); @@ -183,29 +186,134 @@ test('503 with an unavailable code maps to an unavailable failure without Retry- }); }); -test('an unknown valid problem code falls back by HTTP status and preserves the code', async () => { - const stub = await startStubServer({ - 'POST /v1/evidence': (req, res) => { - res.writeHead(409, { - 'content-type': 'application/problem+json', - traceparent: TRACEPARENT, +test('shared problems retain validated identifiers through status fallback', async (t) => { + for (const fixture of responseFixtures.problems) { + await t.test(fixture.name, async () => { + const stub = await startStubServer({ + 'POST /v1/evidence': (_req, res) => { + res.writeHead(fixture.status, { + 'content-type': 'application/problem+json', + 'retry-after': '2', + }); + res.end(fixture.body); + }, + }); + await assertMappedFailure(stub, (error) => { + assert.equal(error.kind, fixture.kind); + assert.equal(error.status, fixture.status); + assert.equal(error.code, fixture.code); + assert.equal(error.problemType, fixture.problemType); + assert.equal(error.traceId, TRACE_ID); + assert.equal(error.retryAfterSeconds, fixture.status === 429 ? 2 : undefined); + const diagnostics = [String(error), inspect(error), JSON.stringify(error)].join(' '); + assert.ok(!diagnostics.includes('Example problem')); + if (fixture.problemType) assert.ok(!diagnostics.includes(fixture.problemType)); + if (fixture.code?.includes('future-')) assert.ok(!diagnostics.includes(fixture.code)); }); - res.end(JSON.stringify({ - type: 'https://id.registrystack.org/problems/registry-evidence/request/future-conflict', - title: 'Future request conflict', - status: 409, - detail: 'The request conflicts with future service state.', - code: 'request.future-conflict', - traceId: TRACE_ID, - })); + assert.equal(stub.requests.length, 1); + }); + } +}); + +test('shared ordinary responses accept additions and require unique, complete JSON', async () => { + let definitions; + let batch; + const stub = await startStubServer({ + 'GET /v1/evidence-definitions': (_req, res) => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(definitions); + }, + 'POST /v1/evidence/batch': (_req, res) => { + res.writeHead(200, { 'content-type': 'application/vnd.registrystack.evidence.request-batch+json' }); + res.end(batch); }, }); - await assertMappedFailure(stub, (mapped) => { - assert.equal(mapped.kind, 'invalid-request'); - assert.equal(mapped.status, 409); - assert.equal(mapped.code, 'request.future-conflict'); - assert.equal(mapped.traceId, TRACE_ID); + const isProtocol = (error) => error instanceof EvidenceClientError + && error.kind === 'protocol' && error.status === 200; + try { + const { client } = await clientAndPrepared(stub); + const { responseFormat: _format, subjects, subjectExpectations, ...common } = requestSpec(); + const item = { subjects, subjectExpectations }; + const prepareBatch = () => client.prepareBatch({ ...common, items: [item, item] }); + for (const name of ['additive', 'duplicate', 'missingRequired']) { + definitions = responseFixtures.definitions[name]; + batch = responseFixtures.requestBatch[name]; + const holderBatch = Buffer.from(responseFixtures.holderBatch[name]); + if (name === 'additive') { + const document = await client.discover(); + assert.equal(document.schema, 'registry.evidence-definitions/v1'); + assert.deepEqual(document.definitions, []); + assert.equal(document.futureMember, undefined); + const verified = await client.requestAndVerifyBatch(prepareBatch()); + assert.deepEqual(verified.items, [{ status: 'notAvailable' }, { status: 'notAvailable' }]); + assert.deepEqual(new SdJwtVcBatchResponse(holderBatch).credentials, + ['credential-for-key-0', 'credential-for-key-1']); + } else { + await assert.rejects(client.discover(), isProtocol); + await assert.rejects(client.requestAndVerifyBatch(prepareBatch()), isProtocol); + assert.throws(() => new SdJwtVcBatchResponse(holderBatch), isProtocol); + } + } + } finally { + await stub.close(); + } +}); + +test('shared discovery defaults omitted binding mode and channel', async () => { + const stub = await startStubServer({ + 'GET /v1/evidence-definitions': (_req, res) => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(responseFixtures.definitionsWithoutModes); + }, }); + try { + const { client } = await clientAndPrepared(stub); + const { definitions } = await client.discover(); + assert.equal(definitions.length, 1); + assert.equal(definitions[0].subjectBindingMode, undefined); + assert.equal(definitions[0].channel, undefined); + } finally { + await stub.close(); + } +}); + +test('shared ordinary responses refuse wrong JSON types', async (t) => { + const routes = { + definitions: ['GET /v1/evidence-definitions', 'application/json'], + requestBatch: ['POST /v1/evidence/batch', 'application/vnd.registrystack.evidence.request-batch+json'], + jwks: ['GET /.well-known/evidence/jwks.json', 'application/jwk-set+json'], + }; + const isProtocol = (error) => error instanceof EvidenceClientError + && error.kind === 'protocol' && error.status === 200; + for (const { target, name, body } of responseFixtures.wrongShapes) { + await t.test(name, async () => { + if (target === 'holderBatch') { + assert.throws(() => new SdJwtVcBatchResponse(Buffer.from(body)), isProtocol); + return; + } + const [route, mediaType] = routes[target]; + const stub = await startStubServer({ + [route]: (_req, res) => { + res.writeHead(200, { 'content-type': mediaType }); + res.end(body); + }, + }); + try { + const { client } = await clientAndPrepared(stub); + const { responseFormat: _format, subjects, subjectExpectations, ...common } = requestSpec(); + const item = { subjects, subjectExpectations }; + const invoke = { + definitions: () => client.discover(), + requestBatch: () => client.requestAndVerifyBatch( + client.prepareBatch({ ...common, items: [item, item] })), + jwks: () => client.fetchJwks(), + }; + await assert.rejects(invoke[target](), isProtocol); + } finally { + await stub.close(); + } + }); + } }); test('a 200 response under the wrong media type is refused as a protocol failure', async () => { diff --git a/crates/registry-evidence-client-node/client.d.ts b/crates/registry-evidence-client-node/client.d.ts index ac494defca..67fe3a317e 100644 --- a/crates/registry-evidence-client-node/client.d.ts +++ b/crates/registry-evidence-client-node/client.d.ts @@ -389,10 +389,11 @@ export interface EvidenceRequestBatchSpec { * * `kind` is always present. The rest are present only when the underlying * failure carries them: - * - `status`: `denied`, `invalid-request`, `unavailable`, `protocol`, and any `token` failure whose `tokenKind` - * is `protocol` - * - `code`: `denied`, `invalid-request`, `unavailable`, `protocol` (optional), `verification`, and any `token` - * failure whose `tokenKind` is `refused` + * - `status`: `denied`, `invalid-request`, `unavailable`, `protocol`, a + * `not-available` status fallback, or a `token` failure with `tokenKind` of `protocol` + * - `code`: a Problem code, a verifier failure kind, or a token refusal code + * - `problemType`: the validated type URI for a classified Problem, including + * future Problems that use status fallback * - `traceId`: `denied`, `not-available`, `invalid-request`, `unavailable`, `protocol` (all optional) * - `retryAfterSeconds`: `denied`, `protocol` (both optional) * - `transportKind`: `transport`, and any `token` failure whose `tokenKind` @@ -403,6 +404,7 @@ export declare class EvidenceClientError extends Error { readonly kind: string readonly status?: number readonly code?: string + readonly problemType?: string readonly traceId?: string readonly retryAfterSeconds?: number readonly transportKind?: string diff --git a/crates/registry-evidence-client-node/client.js b/crates/registry-evidence-client-node/client.js index b9c36634bf..799ce4ab1e 100644 --- a/crates/registry-evidence-client-node/client.js +++ b/crates/registry-evidence-client-node/client.js @@ -14,18 +14,27 @@ const native = require('./index'); * `map_client_error`), as properties on a thrown `Error` rather than as JSON * text a caller has to `JSON.parse` out of `.message`. * - * `kind` is always present; `status`, `code`, `traceId`, - * `retryAfterSeconds`, `transportKind`, and `tokenKind` are present only when - * the underlying failure carries them. + * `kind` is always present. `status`, `code`, `problemType`, `traceId`, + * `retryAfterSeconds`, `transportKind`, and `tokenKind` appear when supplied + * by the underlying failure. */ class EvidenceClientError extends Error { constructor(envelope) { super(envelope.message); this.name = 'EvidenceClientError'; this.kind = envelope.kind; + if (envelope.problemType !== undefined) { + // Problem identifiers remain accessible without including them in + // default inspection or serialization of the error. + Object.defineProperties(this, { + code: { value: envelope.code }, + problemType: { value: envelope.problemType }, + }); + } else if (envelope.code !== undefined) { + this.code = envelope.code; + } for (const field of [ 'status', - 'code', 'traceId', 'retryAfterSeconds', 'transportKind', diff --git a/crates/registry-evidence-client-node/src/convert.rs b/crates/registry-evidence-client-node/src/convert.rs index fde32bf6aa..3284c793f4 100644 --- a/crates/registry-evidence-client-node/src/convert.rs +++ b/crates/registry-evidence-client-node/src/convert.rs @@ -1113,25 +1113,28 @@ pub fn map_config_error(error: &ConfigError) -> Value { } } -/// Map any [`EvidenceClientError`] to the stable JSON envelope described in -/// the crate's `AGENTS.md`-linked design: `kind` and `message` always, plus -/// whichever of `status`, `code`, `traceId`, `retryAfterSeconds`, -/// `transportKind`, and `tokenKind` the variant carries. `code` is -/// deliberately overloaded: a `Denied`/`Protocol` wire code, a -/// `Token::Refused` OAuth code, and a `Verification` failure's own kind string -/// all travel in the same member, since a caller branches on `kind` first and -/// `code` only refines it. `tokenKind` is `Token`'s own analogous second -/// discriminant: every `TokenError` carries one, from [`TokenError::kind`], -/// alongside whichever further sub-fields (`transportKind`, `code`, `status`) -/// that specific variant also carries. -/// -/// Never included: response bytes, a credential, a header value, a selector -/// value, or a subject binding. Every message here is `Display` text over -/// fixed, non-secret reasons; none of the kinds can carry one of those. +/// Map a client error to the public facade's fields. The Rust client supplies +/// the status, Problem identifiers, trace and retry hint. The token and +/// verification kinds use `code` for their own narrower error vocabulary. +/// The message comes from the Rust error's redacted `Display` rendering. pub fn map_client_error(error: &EvidenceClientError) -> Value { let mut fields = Map::new(); fields.insert("kind".to_owned(), Value::String(error.kind().to_owned())); fields.insert("message".to_owned(), Value::String(error.to_string())); + for (name, value) in [ + ("status", error.status().map(Value::from)), + ("code", error.problem_code().map(Value::from)), + ("problemType", error.problem_type().map(Value::from)), + ("traceId", error.trace_id().map(Value::from)), + ( + "retryAfterSeconds", + error.retry_after_seconds().map(Value::from), + ), + ] { + if let Some(value) = value { + fields.insert(name.to_owned(), value); + } + } match error { // Deliberately no `nonceKind` field: `NonceError::NotCanonical` is @@ -1146,47 +1149,6 @@ pub fn map_client_error(error: &EvidenceClientError) -> Value { Value::String(kind.kind().to_owned()), ); } - EvidenceClientError::Denied { - status, - code, - trace_id, - retry_after_seconds, - } => { - fields.insert("status".to_owned(), Value::from(*status)); - fields.insert("code".to_owned(), Value::String(code.clone())); - insert_trace_id(&mut fields, trace_id); - insert_retry_after(&mut fields, *retry_after_seconds); - } - EvidenceClientError::NotAvailable { trace_id } => { - insert_trace_id(&mut fields, trace_id); - } - EvidenceClientError::InvalidRequest { - status, - code, - trace_id, - } - | EvidenceClientError::Unavailable { - status, - code, - trace_id, - } => { - fields.insert("status".to_owned(), Value::from(*status)); - fields.insert("code".to_owned(), Value::String(code.clone())); - insert_trace_id(&mut fields, trace_id); - } - EvidenceClientError::Protocol { - status, - code, - trace_id, - retry_after_seconds, - } => { - fields.insert("status".to_owned(), Value::from(*status)); - if let Some(code) = code { - fields.insert("code".to_owned(), Value::String(code.clone())); - } - insert_trace_id(&mut fields, trace_id); - insert_retry_after(&mut fields, *retry_after_seconds); - } EvidenceClientError::Verification(verification_error) => { fields.insert( "code".to_owned(), @@ -1226,18 +1188,6 @@ fn insert_token_fields(fields: &mut Map, error: &TokenError) { } } -fn insert_trace_id(fields: &mut Map, trace_id: &Option) { - if let Some(trace_id) = trace_id { - fields.insert("traceId".to_owned(), Value::String(trace_id.clone())); - } -} - -fn insert_retry_after(fields: &mut Map, retry_after_seconds: Option) { - if let Some(seconds) = retry_after_seconds { - fields.insert("retryAfterSeconds".to_owned(), Value::from(seconds)); - } -} - #[cfg(test)] mod tests { use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; diff --git a/crates/registry-evidence-client-py/README.md b/crates/registry-evidence-client-py/README.md index e794bcee80..cc802baacf 100644 --- a/crates/registry-evidence-client-py/README.md +++ b/crates/registry-evidence-client-py/README.md @@ -152,11 +152,11 @@ from the package root, with one subclass per stable kind: `ConfigurationError`, `NonceError`, `TokenError`, `TransportError`, `DeniedError`, `NotAvailableError`, `InvalidRequestError`, `UnavailableError`, `ProtocolError`, `VerificationError`. Every -instance carries `kind`; `status`, `code`, `trace_id`, -`retry_after_seconds`, `transport_kind` (on a `TransportError`, and on a -`TokenError` whose `token_kind` is `"transport"`), and `token_kind` (only on a -`TokenError`) are set as attributes only when the underlying failure carries -them. `str(error)` is human prose, not JSON: read it, do not parse it. +instance carries `kind`. `status`, `code`, `problem_type`, `trace_id`, +`retry_after_seconds`, `transport_kind`, and `token_kind` are filled in from +the underlying failure. A structurally valid future Problem keeps its +identifiers as structured attributes and uses the existing HTTP status +category. Read `str(error)` as human prose and branch on `kind`. HTTP 401, 403, and 429 map to `denied`; 422 maps to `not-available`; other contract-valid 4xx responses map to `invalid-request`; and contract-valid 5xx diff --git a/crates/registry-evidence-client-py/python/registry_evidence_client/__init__.pyi b/crates/registry-evidence-client-py/python/registry_evidence_client/__init__.pyi index d75eea25ad..960887b616 100644 --- a/crates/registry-evidence-client-py/python/registry_evidence_client/__init__.pyi +++ b/crates/registry-evidence-client-py/python/registry_evidence_client/__init__.pyi @@ -227,9 +227,9 @@ class EvidenceClientError(Exception): "transport", "denied", "not-available", "invalid-request", "unavailable", "protocol", or "verification". Branch on `kind`, never on the rendered message, which this crate does - not freeze. `status`, `code`, `trace_id`, `retry_after_seconds`, - `transport_kind`, and `token_kind` are present only when the underlying - failure carries them; every other case leaves them `None`. + not freeze. `status`, `code`, `problem_type`, `trace_id`, + `retry_after_seconds`, `transport_kind`, and `token_kind` are set from + the underlying failure. Unavailable attributes are `None`. No attribute here ever carries response bytes, a credential, a header value, a selector value, or a subject binding. @@ -243,6 +243,7 @@ class EvidenceClientError(Exception): kind: str status: Optional[int] code: Optional[str] + problem_type: Optional[str] trace_id: Optional[str] retry_after_seconds: Optional[int] transport_kind: Optional[str] @@ -279,8 +280,8 @@ class DeniedError(EvidenceClientError): ... class NotAvailableError(EvidenceClientError): - """The deployment answered that no evidence is available for this - request.""" + """The deployment returned HTTP 422. Status fallback for unrecognized + problems also carries `status`, `code`, and `problem_type`.""" ... diff --git a/crates/registry-evidence-client-py/src/convert.rs b/crates/registry-evidence-client-py/src/convert.rs index 5109c038ce..84ec5e40ca 100644 --- a/crates/registry-evidence-client-py/src/convert.rs +++ b/crates/registry-evidence-client-py/src/convert.rs @@ -1080,19 +1080,15 @@ pub fn evidence_to_json(evidence: &Evidence) -> Result { /// One mapped failure, ready to become a Python exception. /// -/// Unlike the Node binding, which serializes this shape into one JSON string -/// and uses it as the thrown error's `message` (so a caller can -/// `JSON.parse(error.message)`), the Python exception classes carry `kind`, -/// `status`, `code`, `trace_id`, `retry_after_seconds`, `transport_kind`, and -/// `token_kind` as separate attributes, and `message` is always `Display` -/// text over the source failure, never a JSON envelope. `src/lib.rs` reads -/// this struct's fields directly when constructing the exception instance. +/// `src/lib.rs` attaches these fields directly to the Python exception. +/// Its message is the source failure's `Display` text. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MappedError { pub kind: &'static str, pub message: String, pub status: Option, pub code: Option, + pub problem_type: Option, pub trace_id: Option, pub retry_after_seconds: Option, pub transport_kind: Option<&'static str>, @@ -1106,6 +1102,7 @@ impl MappedError { message, status: None, code: None, + problem_type: None, trace_id: None, retry_after_seconds: None, transport_kind: None, @@ -1131,28 +1128,17 @@ pub fn map_config_error(error: &ConfigError) -> MappedError { } } -/// Map any [`EvidenceClientError`] to a [`MappedError`]. -/// -/// `code` is deliberately overloaded: a `Denied`/`Protocol` wire code, a -/// `Token::Refused` OAuth code, and a `Verification` failure's own kind -/// string all travel in the same field, since a caller branches on `kind` -/// first and `code` only refines it. `token_kind` is `Token`'s own analogous -/// second discriminant: every `TokenError` carries one, from -/// [`TokenError::kind`], alongside whichever further sub-fields -/// (`transport_kind`, `code`, `status`) that specific variant also carries. -/// -/// `code` and `trace_id` are already bounded by the wrapped crate before -/// either ever reaches an `EvidenceClientError` variant -/// (`evidence_client_sdk::problem` validates the exact code and trace ID -/// contracts): this function passes them through -/// unchanged rather than re-bounding them. -/// -/// Never included: response bytes, a credential, a header value, a selector -/// value, or a subject binding. Every message here is `Display` text over -/// fixed, non-secret reasons; none of the error kinds can carry one of those. +/// Map a client error to the Python exception's attributes. The Rust client +/// supplies the status, Problem identifiers, trace and retry hint. The token +/// and verification kinds use `code` for their own narrower vocabulary. +/// The message comes from the Rust error's redacted `Display` rendering. pub fn map_client_error(error: &EvidenceClientError) -> MappedError { let mut mapped = MappedError::bare(error.kind(), error.to_string()); + mapped.status = error.status(); + mapped.code = error.problem_code().map(str::to_owned); + mapped.problem_type = error.problem_type(); mapped.trace_id = error.trace_id().map(str::to_owned); + mapped.retry_after_seconds = error.retry_after_seconds(); match error { // Deliberately no `nonce_kind` field: `NonceError::NotCanonical` is @@ -1164,32 +1150,6 @@ pub fn map_client_error(error: &EvidenceClientError) -> MappedError { EvidenceClientError::Transport { kind } => { mapped.transport_kind = Some(kind.kind()); } - EvidenceClientError::Denied { - status, - code, - retry_after_seconds, - .. - } => { - mapped.status = Some(*status); - mapped.code = Some(code.clone()); - mapped.retry_after_seconds = *retry_after_seconds; - } - EvidenceClientError::NotAvailable { .. } => {} - EvidenceClientError::InvalidRequest { status, code, .. } - | EvidenceClientError::Unavailable { status, code, .. } => { - mapped.status = Some(*status); - mapped.code = Some(code.clone()); - } - EvidenceClientError::Protocol { - status, - code, - retry_after_seconds, - .. - } => { - mapped.status = Some(*status); - mapped.code = code.clone(); - mapped.retry_after_seconds = *retry_after_seconds; - } EvidenceClientError::Verification(verification_error) => { mapped.code = Some(verification_error.kind().to_owned()); } diff --git a/crates/registry-evidence-client-py/src/lib.rs b/crates/registry-evidence-client-py/src/lib.rs index 2baee1c9b0..da9ea43692 100644 --- a/crates/registry-evidence-client-py/src/lib.rs +++ b/crates/registry-evidence-client-py/src/lib.rs @@ -126,7 +126,8 @@ pyo3::create_exception!( registry_evidence_client, NotAvailableError, EvidenceClientError, - "The deployment answered that no evidence is available for this request." + "The deployment returned HTTP 422. Status fallback for unrecognized \ + problems also carries status, code, and problem_type." ); pyo3::create_exception!( @@ -196,6 +197,7 @@ fn to_py_err(py: Python<'_>, mapped: &MappedError) -> PyErr { set_attr!("kind", mapped.kind); set_attr!("status", mapped.status); set_attr!("code", mapped.code.as_deref()); + set_attr!("problem_type", mapped.problem_type.as_deref()); set_attr!("trace_id", mapped.trace_id.as_deref()); set_attr!("retry_after_seconds", mapped.retry_after_seconds); set_attr!("transport_kind", mapped.transport_kind); @@ -1007,6 +1009,7 @@ impl EvidenceClient { message: "the client profile could not be loaded".to_owned(), status: None, code: None, + problem_type: None, trace_id: None, retry_after_seconds: None, transport_kind: None, @@ -1067,6 +1070,7 @@ impl EvidenceClient { message: "the client profile could not be loaded".to_owned(), status: None, code: None, + problem_type: None, trace_id: None, retry_after_seconds: None, transport_kind: None, diff --git a/crates/registry-evidence-client-py/tests/python/test_drift.py b/crates/registry-evidence-client-py/tests/python/test_drift.py index e445e7f850..548777e324 100644 --- a/crates/registry-evidence-client-py/tests/python/test_drift.py +++ b/crates/registry-evidence-client-py/tests/python/test_drift.py @@ -45,6 +45,7 @@ "kind", "status", "code", + "problem_type", "trace_id", "retry_after_seconds", "transport_kind", diff --git a/crates/registry-evidence-client-py/tests/python/test_errors.py b/crates/registry-evidence-client-py/tests/python/test_errors.py index ca7726a80e..4bdad50f83 100644 --- a/crates/registry-evidence-client-py/tests/python/test_errors.py +++ b/crates/registry-evidence-client-py/tests/python/test_errors.py @@ -31,6 +31,10 @@ PROBLEM_MEDIA_TYPE = "application/problem+json" EVIDENCE_JWS_MEDIA_TYPE = "application/jose+json" TRACE_ID = fixtures.TRACE_ID +RESPONSE_FIXTURES = json.loads( + (_TESTS_DIR.parents[3] / "products/platform/fixtures/client-response-tolerance/evidence.json") + .read_text(encoding="utf-8") +) class ErrorMappingTest(unittest.TestCase): @@ -134,29 +138,107 @@ def test_503_with_an_unavailable_code_maps_to_unavailable(self): self.assertEqual(error.trace_id, TRACE_ID) self.assertIsNone(error.retry_after_seconds) - def test_unknown_valid_code_falls_back_by_status_and_preserves_code(self): - self.server.routes["POST /v1/evidence"] = StubRoute( - status=409, - headers={"Content-Type": PROBLEM_MEDIA_TYPE}, - body=json.dumps({ - "type": ( - "https://id.registrystack.org/problems/registry-evidence/" - "request/future-conflict" - ), - "title": "Future request conflict", - "status": 409, - "detail": "The request conflicts with future service state.", - "code": "request.future-conflict", - "traceId": TRACE_ID, - }).encode("utf-8"), + def test_shared_problems_retain_validated_identifiers_through_status_fallback(self): + for fixture in RESPONSE_FIXTURES["problems"]: + with self.subTest(fixture=fixture["name"]): + self.server.routes["POST /v1/evidence"] = StubRoute( + status=fixture["status"], + headers={"Content-Type": PROBLEM_MEDIA_TYPE, "Retry-After": "2"}, + body=fixture["body"].encode("utf-8"), + ) + calls = len(self.server.requests) + with self.assertRaises(revc.EvidenceClientError) as raised: + self._send(self._client()) + error = raised.exception + self.assertEqual(error.kind, fixture["kind"]) + self.assertEqual(error.status, fixture["status"]) + self.assertEqual(error.code, fixture.get("code")) + self.assertEqual(error.problem_type, fixture.get("problemType")) + self.assertEqual(error.trace_id, TRACE_ID) + self.assertEqual(error.retry_after_seconds, 2 if fixture["status"] == 429 else None) + diagnostics = str(error) + repr(error) + self.assertNotIn("Example problem", diagnostics) + if error.problem_type: + self.assertNotIn(error.problem_type, diagnostics) + if "future-" in (error.code or ""): + self.assertNotIn(error.code, diagnostics) + self.assertEqual(len(self.server.requests), calls + 1) + + def test_shared_ordinary_responses_accept_additions_and_require_unique_complete_json(self): + client = self._client() + for name in ("additive", "duplicate", "missingRequired"): + with self.subTest(fixture=name): + self.server.routes["GET /v1/evidence-definitions"] = StubRoute( + status=200, + headers={"Content-Type": "application/json"}, + body=RESPONSE_FIXTURES["definitions"][name].encode("utf-8"), + ) + self.server.routes["POST /v1/evidence/batch"] = StubRoute( + status=200, + headers={"Content-Type": "application/vnd.registrystack.evidence.request-batch+json"}, + body=RESPONSE_FIXTURES["requestBatch"][name].encode("utf-8"), + ) + prepared = client.prepare_batch(fixtures.request_batch_spec()) + holder_batch = RESPONSE_FIXTURES["holderBatch"][name].encode("utf-8") + if name == "additive": + document = client.discover() + self.assertEqual(document["schema"], "registry.evidence-definitions/v1") + self.assertEqual(document["definitions"], []) + self.assertNotIn("futureMember", document) + batch = client.request_and_verify_batch(prepared) + self.assertEqual(batch.items, [{"status": "not_available"}] * 2) + parsed = revc.SdJwtVcBatchResponse.parse(holder_batch) + self.assertEqual(list(parsed.credentials), ["credential-for-key-0", "credential-for-key-1"]) + else: + for invoke in ( + client.discover, + lambda: client.request_and_verify_batch(prepared), + lambda: revc.SdJwtVcBatchResponse.parse(holder_batch), + ): + with self.assertRaises(revc.ProtocolError) as raised: + invoke() + self.assertEqual(raised.exception.status, 200) + + def test_shared_discovery_defaults_omitted_binding_mode_and_channel(self): + self.server.routes["GET /v1/evidence-definitions"] = StubRoute( + status=200, + headers={"Content-Type": "application/json"}, + body=RESPONSE_FIXTURES["definitionsWithoutModes"].encode("utf-8"), ) - with self.assertRaises(revc.InvalidRequestError) as raised: - self._send(self._client()) - error = raised.exception - self.assertEqual(error.kind, "invalid-request") - self.assertEqual(error.status, 409) - self.assertEqual(error.code, "request.future-conflict") - self.assertEqual(error.trace_id, TRACE_ID) + definition, = self._client().discover()["definitions"] + self.assertNotIn("subjectBindingMode", definition) + self.assertNotIn("channel", definition) + + def test_shared_ordinary_responses_refuse_wrong_json_types(self): + client = self._client() + routes = { + "definitions": ("GET /v1/evidence-definitions", "application/json"), + "requestBatch": ( + "POST /v1/evidence/batch", + "application/vnd.registrystack.evidence.request-batch+json", + ), + "jwks": ("GET /.well-known/evidence/jwks.json", "application/jwk-set+json"), + } + for fixture in RESPONSE_FIXTURES["wrongShapes"]: + with self.subTest(fixture=fixture["name"]): + target = fixture["target"] + body = fixture["body"].encode("utf-8") + if target != "holderBatch": + route, media_type = routes[target] + self.server.routes[route] = StubRoute( + status=200, headers={"Content-Type": media_type}, body=body, + ) + invoke = { + "definitions": client.discover, + "requestBatch": lambda: client.request_and_verify_batch( + client.prepare_batch(fixtures.request_batch_spec()) + ), + "jwks": client.fetch_jwks, + "holderBatch": lambda: revc.SdJwtVcBatchResponse.parse(body), + } + with self.assertRaises(revc.ProtocolError) as raised: + invoke[target]() + self.assertEqual(raised.exception.status, 200) def test_a_success_with_the_wrong_media_type_maps_to_protocol(self): self.server.routes["POST /v1/evidence"] = StubRoute( diff --git a/crates/registry-evidence-client/src/batch.rs b/crates/registry-evidence-client/src/batch.rs index 1faba2bbd7..4b94f2b552 100644 --- a/crates/registry-evidence-client/src/batch.rs +++ b/crates/registry-evidence-client/src/batch.rs @@ -21,7 +21,9 @@ use registry_evidence_verifier::redacted_debug; use serde::Deserialize; -use crate::{error::EvidenceClientError, prepare::MAXIMUM_HOLDER_KEYS}; +use crate::{ + error::EvidenceClientError, prepare::MAXIMUM_HOLDER_KEYS, wire::decode_response_object, +}; /// The exact media type that selects a batch issuance envelope. No other /// negotiation reaches this format, and no other format reaches this type. @@ -64,10 +66,10 @@ impl SdJwtVcBatchResponse { /// /// This is a wire-shape check and nothing more. It refuses a body past the /// contract's byte ceiling, a document that is not this envelope version, - /// one carrying a member this version does not declare, and a member list - /// that is empty, past the contract's ceiling, or carrying an empty - /// credential. It makes no judgement whatsoever about the credentials - /// themselves. + /// duplicate members, and a credential list that is missing, empty, past + /// the contract's ceiling, or contains an empty credential. It ignores + /// additive envelope members. Credentials still require individual + /// verification. /// /// Every refusal is the same /// [`EvidenceClientError::Protocol`](crate::EvidenceClientError::Protocol), @@ -79,10 +81,8 @@ impl SdJwtVcBatchResponse { if body.len() > MAX_SD_JWT_VC_BATCH_RESPONSE_BYTES { return Err(refusal()); } - let value = - registry_platform_canonical_json::parse_json_strict(body).map_err(|_| refusal())?; let document: SdJwtVcBatchEnvelopeDocument = - serde_json::from_value(value).map_err(|_| refusal())?; + decode_response_object(body).map_err(|_| refusal())?; if document.schema != SD_JWT_VC_BATCH_SCHEMA_V1 || document.envelope_type != SD_JWT_VC_BATCH_ENVELOPE_TYPE { diff --git a/crates/registry-evidence-client/src/client.rs b/crates/registry-evidence-client/src/client.rs index c9c2112048..abb1179a32 100644 --- a/crates/registry-evidence-client/src/client.rs +++ b/crates/registry-evidence-client/src/client.rs @@ -61,7 +61,8 @@ use crate::{ retained::RetainedEvidenceVerification, token::TokenProvider, wire::{ - EvidenceRequestBatchResponseItemWire, EvidenceRequestBatchResponseWire, JwksDocumentWire, + decode_definitions_response, decode_response_object, EvidenceRequestBatchResponseItemWire, + EvidenceRequestBatchResponseWire, JwksDocumentWire, }, }; use registry_platform_crypto::PrivateJwk; @@ -996,7 +997,7 @@ impl EvidenceClient { let body = read_bounded(response, self.config.max_metadata_bytes) .await .map_err(|error| EvidenceClientError::transport(outbound::read_failure_kind(&error)))?; - let value = decode_response_json::(&body) + let value = decode_response_object::(&body) .map(T::from_wire) .map_err(|_| metadata_protocol_failure())?; Ok(PublicDocument { @@ -1083,7 +1084,12 @@ impl EvidenceClient { /// for a request already in flight. pub async fn discover(&self) -> Result { let (document, trace_id): (EvidenceDefinitionsDocument, _) = self - .get_json(DEFINITIONS_PATH, JSON_MEDIA_TYPE, Credential::Required) + .get_json( + DEFINITIONS_PATH, + JSON_MEDIA_TYPE, + Credential::Required, + decode_definitions_response, + ) .await?; // These types would accept a later document that happened to fit them, and // the relying party would then author requests for a shape whose meaning @@ -1112,7 +1118,12 @@ impl EvidenceClient { // there is nothing to gain by presenting the relying party's credential // to fetch it. let (document, _trace_id): (JwksDocumentWire, _) = self - .get_json(JWKS_PATH, JWKS_MEDIA_TYPE, Credential::None) + .get_json( + JWKS_PATH, + JWKS_MEDIA_TYPE, + Credential::None, + decode_response_object, + ) .await?; Ok(document.into()) } @@ -1274,7 +1285,7 @@ impl EvidenceClient { response: &RawEvidenceRequestBatchResponse, now: DateTime, ) -> Result { - let envelope: EvidenceRequestBatchResponseWire = decode_response_json(&response.body) + let envelope: EvidenceRequestBatchResponseWire = decode_response_object(&response.body) .map_err(|_| batch_protocol_failure(response.trace_id.clone()))?; if envelope.schema != EVIDENCE_REQUEST_BATCH_SCHEMA_V1 || envelope.response_type @@ -1402,11 +1413,12 @@ impl EvidenceClient { /// The response trace identifier is returned beside the document, so a /// caller that refuses the parsed document still has the one value the /// problem contract calls safe for support correlation. - async fn get_json( + async fn get_json( &self, path: &str, media_type: &str, credential: Credential, + decode: fn(&[u8]) -> Result, ) -> Result<(T, Option), EvidenceClientError> { let url = self.endpoint(path)?; let request = self @@ -1417,13 +1429,12 @@ impl EvidenceClient { let body = self .expect_success(response, media_type, self.config.max_metadata_bytes) .await?; - let document = - decode_response_json(&body.body).map_err(|_| EvidenceClientError::Protocol { - status: StatusCode::OK.as_u16(), - code: None, - trace_id: body.trace_id.clone(), - retry_after_seconds: None, - })?; + let document = decode(&body.body).map_err(|_| EvidenceClientError::Protocol { + status: StatusCode::OK.as_u16(), + code: None, + trace_id: body.trace_id.clone(), + retry_after_seconds: None, + })?; Ok((document, body.trace_id)) } @@ -1554,11 +1565,6 @@ impl EvidenceClient { } } -fn decode_response_json(body: &[u8]) -> Result { - let value = registry_platform_canonical_json::parse_json_strict(body).map_err(|_| ())?; - serde_json::from_value(value).map_err(|_| ()) -} - /// A relying party that requests holder-bound credentials and does not verify /// them. /// @@ -1922,6 +1928,7 @@ mod tests { }, outbound::read_failure_kind, prepare::{ChannelPolicy, EvidenceRequestSpec, SubjectExpectations, SubjectRequest}, + problem::PROBLEM_MEDIA_TYPE, request::SelectorValue, response_format::EvidenceResponseFormat, token::StaticToken, @@ -1945,6 +1952,257 @@ mod tests { const TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736"; const TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct ResponseBodies { + additive: String, + duplicate: String, + missing_required: String, + } + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct ResponseFixtures { + definitions: ResponseBodies, + definitions_without_modes: String, + request_batch: ResponseBodies, + holder_batch: ResponseBodies, + problems: Vec, + wrong_shapes: Vec, + } + + #[derive(Deserialize)] + struct WrongShapeFixture { + target: OrdinaryResponse, + name: String, + body: String, + } + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum OrdinaryResponse { + Definitions, + RequestBatch, + HolderBatch, + Jwks, + } + + #[derive(Deserialize)] + struct ProblemFixture { + name: String, + status: u16, + body: String, + kind: String, + code: Option, + #[serde(rename = "problemType")] + problem_type: Option, + } + + fn response_fixtures() -> ResponseFixtures { + serde_json::from_str(include_str!( + "../../../products/platform/fixtures/client-response-tolerance/evidence.json" + )) + .expect("the shared Evidence response fixtures are valid") + } + + #[tokio::test] + async fn shared_ordinary_response_fixtures_use_the_public_decoders() { + let fixtures = response_fixtures(); + let fixture = signed_evidence(); + let server = MockServer::start().await; + let definitions = fixtures.definitions; + for (body, accepted) in [ + (definitions.additive, true), + (definitions.duplicate, false), + (definitions.missing_required, false), + ] { + let client = discovery_client(&server, &fixture, body).await; + match client.discover().await { + Ok(document) if accepted => { + assert_eq!(document.schema, EVIDENCE_DEFINITIONS_SCHEMA_V1); + assert!(document.definitions.is_empty()); + } + Err(EvidenceClientError::Protocol { status: 200, .. }) if !accepted => {} + other => panic!("unexpected definitions result: {other:?}"), + } + server.reset().await; + } + + let client = client_for(&server.uri(), &fixture); + let batch = fixtures.request_batch; + for (body, accepted) in [ + (batch.additive, true), + (batch.duplicate, false), + (batch.missing_required, false), + ] { + Mock::given(method("POST")) + .and(path("/v1/evidence/batch")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("traceparent", TRACEPARENT) + .set_body_raw(body, EVIDENCE_REQUEST_BATCH_MEDIA_TYPE), + ) + .expect(1) + .mount(&server) + .await; + let prepared = client.prepare_batch(request_batch_spec(2)).unwrap(); + match client.request_and_verify_batch(&prepared).await { + Ok(verified) if accepted => assert!(matches!( + verified.items(), + [ + VerifiedEvidenceRequestBatchItem::NotAvailable, + VerifiedEvidenceRequestBatchItem::NotAvailable + ] + )), + Err(EvidenceClientError::Protocol { status: 200, .. }) if !accepted => {} + other => panic!("unexpected request batch result: {other:?}"), + } + server.verify().await; + server.reset().await; + } + + let holder = fixtures.holder_batch; + let parsed = SdJwtVcBatchResponse::parse(holder.additive.as_bytes()).unwrap(); + assert_eq!( + parsed.credentials(), + ["credential-for-key-0", "credential-for-key-1"] + ); + for body in [holder.duplicate, holder.missing_required] { + assert!(matches!( + SdJwtVcBatchResponse::parse(body.as_bytes()), + Err(EvidenceClientError::Protocol { status: 200, .. }) + )); + } + } + + #[tokio::test] + async fn shared_discovery_defaults_omitted_binding_mode_and_channel() { + let server = MockServer::start().await; + let fixture = signed_evidence(); + let client = discovery_client( + &server, + &fixture, + response_fixtures().definitions_without_modes, + ) + .await; + let document = client.discover().await.unwrap(); + let [definition] = document.definitions.as_slice() else { + panic!("expected one discovery definition"); + }; + assert_eq!(definition.subject_binding_mode, None); + assert_eq!(definition.channel, None); + assert_eq!(definition.own_channel(), ChannelKind::Source); + } + + #[tokio::test] + async fn shared_ordinary_responses_refuse_wrong_json_types() { + let fixture = signed_evidence(); + let server = MockServer::start().await; + let client = client_for(&server.uri(), &fixture); + let mut missed = Vec::new(); + for case in response_fixtures().wrong_shapes { + let result = if matches!(case.target, OrdinaryResponse::HolderBatch) { + SdJwtVcBatchResponse::parse(case.body.as_bytes()).map(|_| ()) + } else { + let (verb, route, media) = match case.target { + OrdinaryResponse::Definitions => ("GET", DEFINITIONS_PATH, JSON_MEDIA_TYPE), + OrdinaryResponse::RequestBatch => ( + "POST", + EVIDENCE_BATCH_PATH, + EVIDENCE_REQUEST_BATCH_MEDIA_TYPE, + ), + OrdinaryResponse::Jwks => ("GET", JWKS_PATH, JWKS_MEDIA_TYPE), + OrdinaryResponse::HolderBatch => unreachable!(), + }; + Mock::given(method(verb)) + .and(path(format!("/{route}"))) + .respond_with( + ResponseTemplate::new(200) + .insert_header("traceparent", TRACEPARENT) + .set_body_raw(case.body, media), + ) + .expect(1) + .mount(&server) + .await; + let result = match case.target { + OrdinaryResponse::Definitions => client.discover().await.map(|_| ()), + OrdinaryResponse::RequestBatch => { + let prepared = client.prepare_batch(request_batch_spec(2)).unwrap(); + client.request_and_verify_batch(&prepared).await.map(|_| ()) + } + OrdinaryResponse::Jwks => client.fetch_jwks().await.map(|_| ()), + OrdinaryResponse::HolderBatch => unreachable!(), + }; + server.verify().await; + server.reset().await; + result + }; + if !matches!( + result, + Err(EvidenceClientError::Protocol { status: 200, .. }) + ) { + missed.push(case.name); + } + } + assert!( + missed.is_empty(), + "expected protocol refusals for {missed:?}" + ); + } + + #[tokio::test] + async fn shared_problem_fixtures_use_status_fallback_and_redacted_diagnostics() { + let fixture = signed_evidence(); + let server = MockServer::start().await; + let client = client_for(&server.uri(), &fixture); + for expected in response_fixtures().problems { + Mock::given(method("POST")) + .and(path("/v1/evidence")) + .respond_with( + ResponseTemplate::new(expected.status) + .insert_header("traceparent", TRACEPARENT) + .insert_header("retry-after", "2") + .set_body_raw(expected.body, PROBLEM_MEDIA_TYPE), + ) + .expect(1) + .mount(&server) + .await; + let prepared = client + .prepare(spec(SubjectExpectations::AcceptFirstUse)) + .unwrap(); + let error = client.send(&prepared).await.unwrap_err(); + assert_eq!(error.kind(), expected.kind, "{}", expected.name); + assert_eq!(error.trace_id(), Some(TRACE_ID), "{}", expected.name); + assert_eq!(error.status(), Some(expected.status), "{}", expected.name); + assert_eq!( + error.problem_code(), + expected.code.as_deref(), + "{}", + expected.name + ); + assert_eq!( + error.problem_type(), + expected.problem_type, + "{}", + expected.name + ); + assert_eq!( + error.retry_after_seconds(), + (expected.status == 429).then_some(2) + ); + let diagnostics = format!("{error} {error:?}"); + assert!(!diagnostics.contains("Example problem")); + if let Some(uri) = expected.problem_type { + assert!(!diagnostics.contains(&uri), "{}", expected.name); + } + if let Some(code) = expected.code.filter(|code| code.contains("future-")) { + assert!(!diagnostics.contains(&code), "{}", expected.name); + } + server.verify().await; + server.reset().await; + } + } + #[tokio::test] async fn response_posture_follows_the_peer_policy() { use crate::PeerPolicy::{AcceptDevelopmentPeer, RefuseDevelopmentPeer}; diff --git a/crates/registry-evidence-client/src/error.rs b/crates/registry-evidence-client/src/error.rs index 5ea64fc367..d5ed425044 100644 --- a/crates/registry-evidence-client/src/error.rs +++ b/crates/registry-evidence-client/src/error.rs @@ -1,18 +1,24 @@ //! One coarse failure type for the whole client. //! -//! Every variant is deliberately uninformative about response content. A -//! rendering carries the HTTP status, the closed public problem code, and the -//! validated W3C trace identifier for support correlation, and nothing else. It -//! never carries response bytes, a credential, a header value, a selector -//! value, or a subject binding. +//! Diagnostics use fixed text, the HTTP status, registered public problem +//! codes, and the validated W3C trace identifier for support correlation. +//! Consumers can explicitly read validated future identifiers as structured +//! fields. Response prose, extension values and other response data are +//! withheld. + +use std::fmt; use registry_evidence_verifier::verifier::VerificationError; use thiserror::Error; -use crate::{nonce::NonceError, token::TokenError}; +use crate::{ + nonce::NonceError, + problem::{problem_type_uri, registered_status}, + token::TokenError, +}; pub use registry_platform_httputil::TransportKind; -#[derive(Debug, Error, Clone, PartialEq, Eq)] +#[derive(Error, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum EvidenceClientError { #[error( @@ -43,7 +49,7 @@ pub enum EvidenceClientError { /// The deployment refused the request. Authentication, authorization, and /// rate limiting are indistinguishable by design at the public boundary. - #[error("the deployment refused the request: status {status}, code {code}")] + #[error("the deployment refused the request: status {status}{}", diagnostic_code(.code))] Denied { status: u16, code: String, @@ -59,9 +65,17 @@ pub enum EvidenceClientError { #[error("the deployment could not produce evidence for this request")] NotAvailable { trace_id: Option }, + /// A valid but unrecognized Problem with HTTP 422. It uses the same coarse + /// status fallback as `NotAvailable`, while retaining the distinct code. + #[error("the deployment refused the request: status 422")] + NotAvailableStatus { + code: String, + trace_id: Option, + }, + /// The deployment rejected the request shape or named resource. Correct /// the request before sending another one. - #[error("the Evidence request is invalid: status {status}, code {code}")] + #[error("the Evidence request is invalid: status {status}{}", diagnostic_code(.code))] InvalidRequest { status: u16, code: String, @@ -70,7 +84,7 @@ pub enum EvidenceClientError { /// The Evidence service or one of its authoritative sources is currently /// unavailable. A retry is a caller decision and requires a fresh request. - #[error("the Evidence service is unavailable: status {status}, code {code}")] + #[error("the Evidence service is unavailable: status {status}{}", diagnostic_code(.code))] Unavailable { status: u16, code: String, @@ -111,8 +125,9 @@ impl EvidenceClientError { /// an enum this crate may extend: a metric label, a structured log field, or /// a language binding that carries the discriminant across a boundary. The /// rendered message is for people and may be reworded; these names are part - /// of the crate's contract and will not be renamed. A variant added later - /// brings a new name rather than reusing one of these. + /// of the crate's contract and will not be renamed. The + /// `not-available` kind covers the registered refusal and the HTTP 422 + /// fallback. #[must_use] pub fn kind(&self) -> &'static str { match self { @@ -122,7 +137,7 @@ impl EvidenceClientError { Self::Token(_) => "token", Self::Transport { .. } => "transport", Self::Denied { .. } => "denied", - Self::NotAvailable { .. } => "not-available", + Self::NotAvailable { .. } | Self::NotAvailableStatus { .. } => "not-available", Self::InvalidRequest { .. } => "invalid-request", Self::Unavailable { .. } => "unavailable", Self::Protocol { .. } => "protocol", @@ -130,6 +145,59 @@ impl EvidenceClientError { } } + /// The explicit HTTP status attached to a refusal or protocol failure. + #[must_use] + pub fn status(&self) -> Option { + match self { + Self::Denied { status, .. } + | Self::InvalidRequest { status, .. } + | Self::Unavailable { status, .. } + | Self::Protocol { status, .. } => Some(*status), + Self::NotAvailableStatus { .. } => Some(422), + _ => None, + } + } + + /// The structured Problem code attached to a classified refusal. + #[must_use] + pub fn problem_code(&self) -> Option<&str> { + match self { + Self::Denied { code, .. } + | Self::NotAvailableStatus { code, .. } + | Self::InvalidRequest { code, .. } + | Self::Unavailable { code, .. } => Some(code), + Self::Protocol { code, .. } => code.as_deref(), + _ => None, + } + } + + /// The structured Problem type URI. Evidence requires the exact URI + /// derived from the validated code, so one identifier suffices to retain + /// both. Protocol failures expose no type. + #[must_use] + pub fn problem_type(&self) -> Option { + match self { + Self::Protocol { .. } => None, + _ => self.problem_code().and_then(problem_type_uri), + } + } + + /// The bounded wait indicated by the HTTP response, when actionable. + #[must_use] + pub fn retry_after_seconds(&self) -> Option { + match self { + Self::Denied { + retry_after_seconds, + .. + } + | Self::Protocol { + retry_after_seconds, + .. + } => *retry_after_seconds, + _ => None, + } + } + /// The validated W3C trace identifier to quote when asking the deployment /// operator about this failure. It is transport correlation only, not an /// Evidence audit operation identity. @@ -138,6 +206,7 @@ impl EvidenceClientError { match self { Self::Denied { trace_id, .. } | Self::NotAvailable { trace_id } + | Self::NotAvailableStatus { trace_id, .. } | Self::InvalidRequest { trace_id, .. } | Self::Unavailable { trace_id, .. } | Self::Protocol { trace_id, .. } => trace_id.as_deref(), @@ -146,6 +215,25 @@ impl EvidenceClientError { } } +impl fmt::Debug for EvidenceClientError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("EvidenceClientError") + .field("kind", &self.kind()) + .field("message", &format_args!("{self}")) + .field("trace_id", &self.trace_id()) + .finish() + } +} + +fn diagnostic_code(code: &str) -> String { + if registered_status(code).is_some() { + format!(", code {code}") + } else { + String::new() + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/registry-evidence-client/src/problem.rs b/crates/registry-evidence-client/src/problem.rs index 8d79243842..154fd95c50 100644 --- a/crates/registry-evidence-client/src/problem.rs +++ b/crates/registry-evidence-client/src/problem.rs @@ -18,7 +18,7 @@ const EVIDENCE_NOT_AVAILABLE: &str = "evidence.unavailable"; /// Longest accepted problem body. The closed contract is far smaller. pub(crate) const MAXIMUM_PROBLEM_BYTES: usize = 4 * 1024; -const REGISTERED_PROBLEMS: [(u16, &str, &str, &str); 11] = [ +const REGISTERED_PROBLEMS: [(u16, &str, &str, &str); 12] = [ ( 400, "evidence.invalid-request", @@ -43,6 +43,12 @@ const REGISTERED_PROBLEMS: [(u16, &str, &str, &str); 11] = [ "Bearer access token is invalid", "bearer access token validation failed", ), + ( + 401, + "platform.task-grant.development-assertion", + "Development task assertion refused", + "task grant was issued in the development posture", + ), ( 403, "evidence.denied", @@ -89,9 +95,8 @@ const REGISTERED_PROBLEMS: [(u16, &str, &str, &str); 11] = [ /// Map a refused or failed exchange onto one coarse client failure. /// -/// `Retry-After` is actionable only for a registered 429 response. The caller -/// passes the trace ID extracted from an exact v0 `traceparent`, never a -/// caller-controlled outbound context. +/// `Retry-After` is actionable only for a valid 429 problem response. +/// The caller passes the trace ID extracted from an exact v0 `traceparent`. pub(crate) fn map_problem( status: u16, media_type: Option<&str>, @@ -100,54 +105,55 @@ pub(crate) fn map_problem( header_trace_id: Option<&str>, ) -> EvidenceClientError { let Some(problem) = parse_problem(media_type, body) else { - return protocol(status, header_trace_id, None); + return protocol(status, header_trace_id); }; if problem.status != status || header_trace_id != Some(problem.trace_id.as_str()) { - return protocol(status, header_trace_id, None); + return protocol(status, header_trace_id); } if !(400..=599).contains(&status) - || !valid_problem_code(&problem.code) - || problem.type_uri != expected_type_uri(&problem.code) + || problem_type_uri(&problem.code).as_deref() != Some(problem.type_uri.as_str()) { - return protocol(status, header_trace_id, None); + return protocol(status, header_trace_id); } - let registered = REGISTERED_PROBLEMS - .iter() - .find(|(_, registered_code, _, _)| *registered_code == problem.code); - if registered.is_some_and(|(registered_status, _, _, _)| *registered_status != status) { - return protocol(status, header_trace_id, None); + if registered_status(&problem.code).is_some_and(|registered| registered != status) { + return protocol(status, header_trace_id); } - match (status, registered.map(|(_, code, _, _)| *code)) { - (401 | 403 | 429, code) => EvidenceClientError::Denied { + + let trace_id = Some(problem.trace_id.as_str().to_owned()); + let code = problem.code; + match status { + 401 | 403 | 429 => EvidenceClientError::Denied { status, - code: code.unwrap_or(problem.code.as_str()).to_owned(), - trace_id: Some(problem.trace_id.as_str().to_owned()), + code, + trace_id, retry_after_seconds: retry_after_seconds.filter(|_| status == 429), }, - (422, Some(EVIDENCE_NOT_AVAILABLE)) => EvidenceClientError::NotAvailable { - trace_id: Some(problem.trace_id.as_str().to_owned()), - }, - (422, None) => EvidenceClientError::NotAvailable { - trace_id: Some(problem.trace_id.as_str().to_owned()), - }, - (400..=499, code) => EvidenceClientError::InvalidRequest { + 422 if code == EVIDENCE_NOT_AVAILABLE => EvidenceClientError::NotAvailable { trace_id }, + 422 => EvidenceClientError::NotAvailableStatus { code, trace_id }, + 400..=499 => EvidenceClientError::InvalidRequest { status, - code: code.unwrap_or(problem.code.as_str()).to_owned(), - trace_id: Some(problem.trace_id.as_str().to_owned()), + code, + trace_id, }, - (500..=599, code) => EvidenceClientError::Unavailable { + 500..=599 => EvidenceClientError::Unavailable { status, - code: code.unwrap_or(problem.code.as_str()).to_owned(), - trace_id: Some(problem.trace_id.as_str().to_owned()), + code, + trace_id, }, - _ => protocol(status, header_trace_id, None), + _ => protocol(status, header_trace_id), } } -fn protocol(status: u16, trace_id: Option<&str>, code: Option) -> EvidenceClientError { +pub(crate) fn registered_status(code: &str) -> Option { + REGISTERED_PROBLEMS + .iter() + .find_map(|(status, registered, _, _)| (*registered == code).then_some(*status)) +} + +fn protocol(status: u16, trace_id: Option<&str>) -> EvidenceClientError { EvidenceClientError::Protocol { status, - code, + code: None, trace_id: trace_id.map(str::to_owned), retry_after_seconds: None, } @@ -164,6 +170,10 @@ fn parse_problem(media_type: Option<&str>, body: &[u8]) -> Option Option { + valid_problem_code(code).then(|| expected_type_uri(code)) +} + fn expected_type_uri(code: &str) -> String { format!("{}{}", PROBLEM_TYPE_PREFIX, code.replace('.', "/")) } @@ -172,16 +182,7 @@ fn valid_problem_code(code: &str) -> bool { if code.is_empty() || code.len() > 128 { return false; } - let mut segments = code.split('.'); - let Some(family) = segments.next() else { - return false; - }; - let Some(reason) = segments.next() else { - return false; - }; - segments.next().is_none() - && valid_problem_code_segment(family) - && valid_problem_code_segment(reason) + code.contains('.') && code.split('.').all(valid_problem_code_segment) } fn valid_problem_code_segment(segment: &str) -> bool { @@ -189,9 +190,12 @@ fn valid_problem_code_segment(segment: &str) -> bool { .as_bytes() .first() .is_some_and(|byte| byte.is_ascii_lowercase()) - && segment - .bytes() - .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + && segment.split('-').all(|part| { + !part.is_empty() + && part + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) + }) } /// The media type without its parameters. diff --git a/crates/registry-evidence-client/src/wire.rs b/crates/registry-evidence-client/src/wire.rs index b1128532c8..a87b5bf2b7 100644 --- a/crates/registry-evidence-client/src/wire.rs +++ b/crates/registry-evidence-client/src/wire.rs @@ -8,18 +8,161 @@ use registry_evidence_verifier::model::{ EvidenceRequestBatchResponseType, FlattenedJws, JwksDocument, }; -use serde::Deserialize; -use serde_json::Value; +use serde::{ + de::{value::StringDeserializer, DeserializeOwned, Error as _}, + Deserialize, Deserializer, +}; +use serde_json::{Map, Value}; + +use crate::definitions::EvidenceDefinitionsDocument; + +fn parse_response_object(body: &[u8]) -> Result { + let value = registry_platform_canonical_json::parse_json_strict(body).map_err(|_| ())?; + if !value.is_object() { + return Err(()); + } + Ok(value) +} + +pub(crate) fn decode_response_object(body: &[u8]) -> Result { + serde_json::from_value(parse_response_object(body)?).map_err(|_| ()) +} + +pub(crate) fn decode_definitions_response(body: &[u8]) -> Result { + let value = parse_response_object(body)?; + if !object_with( + &value, + &[ + ("assuranceProfile", Value::is_string), + ("definitions", |value| array_of(value, definition_shape)), + ], + ) { + return Err(()); + } + serde_json::from_value(value).map_err(|_| ()) +} + +type JsonShape = fn(&Value) -> bool; + +// The shared definitions DTO validates field presence and values. Check JSON +// shape here, after duplicate rejection, so governed deserialization stays +// on its own Serde path and sees each raw member. +fn object_with(value: &Value, fields: &[(&str, JsonShape)]) -> bool { + value.as_object().is_some_and(|object| { + fields + .iter() + .all(|(name, shape)| object.get(*name).is_none_or(shape)) + }) +} + +fn array_of(value: &Value, shape: JsonShape) -> bool { + value + .as_array() + .is_some_and(|items| items.iter().all(shape)) +} + +fn definition_shape(value: &Value) -> bool { + object_with( + value, + &[ + ("kind", Value::is_string), + ("subjectBindingMode", Value::is_string), + ("channel", Value::is_string), + ("responseFormats", string_array), + ("subjects", subject_array), + ("concepts", |value| array_of(value, concept_shape)), + ("alternatives", |value| array_of(value, alternative_shape)), + ], + ) +} + +fn alternative_shape(value: &Value) -> bool { + object_with( + value, + &[ + ("channel", Value::is_string), + ("responseFormats", string_array), + ("subjects", subject_array), + ], + ) +} + +fn string_array(value: &Value) -> bool { + array_of(value, Value::is_string) +} + +fn subject_array(value: &Value) -> bool { + array_of(value, |value| { + object_with( + value, + &[ + ("cardinality", Value::is_string), + ("selector", selector_shape), + ], + ) + }) +} + +fn selector_shape(value: &Value) -> bool { + object_with( + value, + &[ + ("valueOrigin", Value::is_string), + ("fields", |value| array_of(value, Value::is_object)), + ], + ) +} + +fn concept_shape(value: &Value) -> bool { + object_with( + value, + &[("form", |form| { + if form.get("type").and_then(Value::as_str) == Some("list") { + object_with(form, &[("items", Value::is_string)]) + } else { + form.is_object() + } + })], + ) +} + +fn deserialize_object<'de, D, T>(deserializer: D) -> Result +where + D: Deserializer<'de>, + T: DeserializeOwned, +{ + let object = Map::deserialize(deserializer)?; + T::deserialize(Value::Object(object)).map_err(D::Error::custom) +} + +fn deserialize_object_list<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: DeserializeOwned, +{ + Vec::>::deserialize(deserializer)? + .into_iter() + .map(|object| T::deserialize(Value::Object(object)).map_err(D::Error::custom)) + .collect() +} + +fn deserialize_string<'de, D, T>(deserializer: D) -> Result +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(StringDeserializer::new(String::deserialize(deserializer)?)) +} #[derive(Clone, Deserialize)] pub(crate) struct JwksDocumentWire { - keys: Vec, + keys: Vec>, } impl From for JwksDocument { fn from(document: JwksDocumentWire) -> Self { Self { - keys: document.keys, + keys: document.keys.into_iter().map(Value::Object).collect(), } } } @@ -27,14 +170,18 @@ impl From for JwksDocument { #[derive(Deserialize)] pub(crate) struct EvidenceRequestBatchResponseWire { pub(crate) schema: String, - #[serde(rename = "type")] + #[serde(rename = "type", deserialize_with = "deserialize_string")] pub(crate) response_type: EvidenceRequestBatchResponseType, + #[serde(deserialize_with = "deserialize_object_list")] pub(crate) items: Vec, } #[derive(Deserialize)] #[serde(tag = "result", rename_all = "kebab-case")] pub(crate) enum EvidenceRequestBatchResponseItemWire { - Evidence { evidence: FlattenedJws }, + Evidence { + #[serde(deserialize_with = "deserialize_object")] + evidence: FlattenedJws, + }, EvidenceNotAvailable {}, } diff --git a/crates/registry-evidence-oid4vci/src/config.rs b/crates/registry-evidence-oid4vci/src/config.rs index 0f04400cba..ca87f1815d 100644 --- a/crates/registry-evidence-oid4vci/src/config.rs +++ b/crates/registry-evidence-oid4vci/src/config.rs @@ -266,7 +266,7 @@ pub enum ValidationMode { static SUPERVISED_VALIDATION: DevelopmentSetting = DevelopmentSetting { code: "evidence.posture.supervised-validation", key: "validationMode", - summary: "supervised validation permits a published loopback HTTP credential issuer", + summary: "Supervised validation permits a published loopback HTTP credential issuer", production: "Use validationMode: strict and publish an HTTPS credential issuer.", }; @@ -993,7 +993,7 @@ shape_union!(IdentifierRestriction { scalar => Unrestricted, list => Listed }); static UNRESTRICTED_OFFER_GATE: DevelopmentSetting = DevelopmentSetting { code: "evidence.posture.unrestricted-offer-gate", key: "allowedClients", - summary: "an unrestricted offer gate admits all values vouched for by the issuer", + summary: "An unrestricted offer gate admits all values vouched for by the issuer", production: "List the required clients and scopes explicitly.", }; diff --git a/crates/registry-evidence-oid4vci/src/issuer.rs b/crates/registry-evidence-oid4vci/src/issuer.rs index 07067825b8..7cf400e42a 100644 --- a/crates/registry-evidence-oid4vci/src/issuer.rs +++ b/crates/registry-evidence-oid4vci/src/issuer.rs @@ -69,7 +69,8 @@ impl From for IssuanceError { Self::Unavailable } EvidenceClientError::Denied { .. } => Self::Refused, - EvidenceClientError::NotAvailable { .. } => Self::NotAvailable, + EvidenceClientError::NotAvailable { .. } + | EvidenceClientError::NotAvailableStatus { .. } => Self::NotAvailable, EvidenceClientError::Configuration { .. } | EvidenceClientError::Nonce(_) => { Self::Configuration("the prepared request was refused before it was sent") } @@ -369,6 +370,17 @@ mod tests { server.abort(); } + #[test] + fn a_future_evidence_422_retains_the_existing_refusal_category() { + assert_eq!( + IssuanceError::from(EvidenceClientError::NotAvailableStatus { + code: "evidence.future-unavailable".to_owned(), + trace_id: None, + }), + IssuanceError::NotAvailable + ); + } + #[test] fn a_deployment_failure_is_never_reported_as_a_subject_statement() { // Every mapped failure is a coarse category. None of them can be read diff --git a/crates/registry-evidence-oid4vp/tests/check_command.rs b/crates/registry-evidence-oid4vp/tests/check_command.rs index 33dbbeadaf..4bcf911bad 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. This issuer entry admits a token from every client this issuer signs for.\n0 errors, 0 warnings in 1 file\n" ); } diff --git a/crates/registry-evidence/src/bundle.rs b/crates/registry-evidence/src/bundle.rs index a06e23b47f..d25c51d9f4 100644 --- a/crates/registry-evidence/src/bundle.rs +++ b/crates/registry-evidence/src/bundle.rs @@ -741,14 +741,14 @@ pub type EvidenceBundle = Bundle; pub static LOCAL_ASSURANCE: DevelopmentSetting = DevelopmentSetting { code: "evidence.posture.local-assurance", key: "assuranceProfile", - summary: "local assurance permits locally held signing keys", + summary: "Local assurance permits locally held signing keys", production: "Build a production or evidence-grade package with a Transit signer.", }; static CREDENTIAL_FREE_SOURCE: DevelopmentSetting = DevelopmentSetting { code: "evidence.posture.credential-free-source", key: "authentication", - summary: "a credential-free source connection provides no client authentication", + summary: "A credential-free source connection provides no client authentication", production: "Bind an mtlsIdentity or configure an authenticated endpoint.", }; diff --git a/crates/registry-evidence/src/contracts.rs b/crates/registry-evidence/src/contracts.rs index 686a623422..73312c26e1 100644 --- a/crates/registry-evidence/src/contracts.rs +++ b/crates/registry-evidence/src/contracts.rs @@ -55,6 +55,20 @@ pub const PUBLIC_CHECK_REQUEST_SCHEMA_FILE: &str = pub const PUBLIC_CHECK_ANSWER_SCHEMA_FILE: &str = "evidence-public-check-answer-v1alpha1.schema.json"; +/// The promised HTTP response documents, each published with +/// [`RESPONSE_EMISSION_NOTE`]. The signed and credential formats (the Evidence +/// payload, its flattened JWS, the unsigned envelope around the same core +/// object, and the SD-JWT VC batch envelope) keep their own closed formats. +const RESPONSE_SCHEMA_FILES: [&str; 4] = [ + REQUEST_BATCH_RESPONSE_SCHEMA_FILE, + DEFINITIONS_SCHEMA_FILE, + PROBLEM_SCHEMA_FILE, + JWKS_SCHEMA_FILE, +]; +/// A closed response schema lists what one release emits; a later minor +/// release may add members, which consumers ignore. +const RESPONSE_EMISSION_NOTE: &str = "This closed schema describes exactly what one release emits. A later minor release may add members, so a consumer ignores members it does not know instead of rejecting the response."; + const REQUEST_SCHEMA_ID: &str = "https://registrystack.org/schemas/evidence/request-v1.json"; const REQUEST_BATCH_SCHEMA_ID: &str = "https://registrystack.org/schemas/evidence/request-batch-v1.json"; @@ -238,10 +252,30 @@ pub fn documents() -> Result, ContractGenerationE ]; values .into_iter() - .map(|(name, value)| Ok((name, pretty_json(&value)?))) + .map(|(name, value)| { + let value = if RESPONSE_SCHEMA_FILES.contains(&name) { + with_emission_note(value) + } else { + value + }; + Ok((name, pretty_json(&value)?)) + }) .collect() } +/// Append [`RESPONSE_EMISSION_NOTE`] to a published response schema's root +/// `$comment`. The OpenAPI document embeds the schemas without it. +fn with_emission_note(mut schema: Value) -> Value { + if let Some(object) = schema.as_object_mut() { + let comment = match object.get("$comment").and_then(Value::as_str) { + Some(existing) => format!("{existing} {RESPONSE_EMISSION_NOTE}"), + None => RESPONSE_EMISSION_NOTE.to_string(), + }; + object.insert("$comment".to_string(), Value::String(comment)); + } + schema +} + /// Write all generated contracts to an otherwise caller-owned directory. pub fn write_documents(output: &Path) -> Result<(), ContractGenerationError> { fs::create_dir_all(output).map_err(|source| ContractGenerationError::Output { @@ -1848,6 +1882,41 @@ pub(crate) fn assert_served_problem( mod tests { use super::*; + #[test] + fn response_schemas_say_they_describe_one_release() { + let documents = documents().expect("contracts generate"); + for file in RESPONSE_SCHEMA_FILES { + let schema: Value = serde_json::from_str(&documents[file]).expect("schema JSON"); + let comment = schema["$comment"].as_str().unwrap_or_default(); + assert!( + comment.ends_with(RESPONSE_EMISSION_NOTE), + "{file}: {comment}" + ); + } + // Requests, the signed and credential formats, the experimental public + // check, and the OpenAPI document, which embeds the schemas, carry no + // note. + let unannotated = [ + REQUEST_SCHEMA_FILE, + REQUEST_BATCH_SCHEMA_FILE, + EVIDENCE_SCHEMA_FILE, + JWS_SCHEMA_FILE, + UNSIGNED_ENVELOPE_SCHEMA_FILE, + SD_JWT_VC_BATCH_SCHEMA_FILE, + PUBLIC_CHECK_REQUEST_SCHEMA_FILE, + PUBLIC_CHECK_ANSWER_SCHEMA_FILE, + OPENAPI_FILE, + ]; + for file in unannotated { + assert!(!documents[file].contains(RESPONSE_EMISSION_NOTE), "{file}"); + } + assert_eq!( + documents.len(), + RESPONSE_SCHEMA_FILES.len() + unannotated.len(), + "every generated document is classified" + ); + } + #[test] fn every_json_schema_is_valid_draft_2020_12() { for schema in [ diff --git a/crates/registry-evidence/src/evidence_source_tests.rs b/crates/registry-evidence/src/evidence_source_tests.rs index ecf7ae1afa..65ff1b7c46 100644 --- a/crates/registry-evidence/src/evidence_source_tests.rs +++ b/crates/registry-evidence/src/evidence_source_tests.rs @@ -1500,6 +1500,43 @@ fn signed_evidence_host_config_has_no_access_attribution_override_surface() { ); } +#[test] +fn signed_evidence_compiler_refuses_a_repeated_definition_member() { + use registry_adapter_engine::evidence::{ + compile_evidence_pack_with_protocols, EvidenceCompileError, EvidenceLimits, + }; + + let valid = serde_json::to_string(&signed_evidence_test_protocol()).unwrap(); + let member = r#""kind":"criterion""#; + assert_eq!(valid.matches(member).count(), 1); + let repeated = valid.replacen(member, &format!("{member},{member}"), 1); + for (config, accepted) in [(valid, true), (repeated, false)] { + let prepared = prepare_signed_evidence_fixture( + "duplicate-subject-binding-secret-32-bytes-minimum", + "https://source.invalid", + "https://identity.invalid/token", + config.as_bytes(), + &FixtureCeilings::deployment_defaults(), + |_| {}, + ); + let bundle = crate::bundle::Bundle::load(&prepared.bundle_root) + .expect("the fixture preserves the digest-pinned raw config"); + let closure = bundle.source_pack("source-b").unwrap(); + let result = compile_evidence_pack_with_protocols( + &closure.pack(), + "residence-region", + &closure.artifacts(), + EvidenceLimits::default(), + &crate::host_protocol::registry().unwrap(), + ); + if accepted { + assert!(result.is_ok(), "the original contract compiles"); + } else { + assert!(matches!(result, Err(EvidenceCompileError::HostProtocol))); + } + } +} + #[test] fn signed_evidence_pack_refuses_unauthenticated_protocol_before_io() { let protocol = serde_json::to_vec(&signed_evidence_test_protocol()).unwrap(); diff --git a/crates/registry-evidence/src/refusal_recording_tests.rs b/crates/registry-evidence/src/refusal_recording_tests.rs index de6d8a2fc3..3c1ab8f0ab 100644 --- a/crates/registry-evidence/src/refusal_recording_tests.rs +++ b/crates/registry-evidence/src/refusal_recording_tests.rs @@ -573,6 +573,22 @@ fn every_refusal_is_counted_logged_once_by_its_check_and_answered_as_before() { scenario.check.as_str() )); } + if let Some(claim) = match scenario.check { + FailedCheck::TokenAudience => Some("aud claim"), + FailedCheck::TokenTime if scenario.name == "expired-token" => Some("exp claim"), + _ => None, + } { + if !refused.first().is_some_and(|record| { + record["fields"]["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(claim)) + }) { + failures.push(format!( + "{}: the operator diagnostic must name {claim}", + scenario.name + )); + } + } let raw = serde_json::to_string(&emitted).expect("captured records serialize"); for canary in [TOKEN_CANARY, CLIENT_CANARY, "requester-principal-canary"] { if raw.contains(canary) { diff --git a/crates/registry-evidencectl/src/check.rs b/crates/registry-evidencectl/src/check.rs index 642cee8937..aa079b7b1f 100644 --- a/crates/registry-evidencectl/src/check.rs +++ b/crates/registry-evidencectl/src/check.rs @@ -51,7 +51,7 @@ pub(crate) fn target_explicit_settings( pointer: Some(clients_pointer), line: position.map(|position| position.line), column: position.map(|position| position.column), - summary: "admits a token from every client this issuer signs for" + summary: "This issuer entry admits a token from every client this issuer signs for" .to_owned(), }); } else { @@ -217,7 +217,7 @@ static LOCAL_ASSURANCE: registry_platform_config::DevelopmentSetting = registry_platform_config::DevelopmentSetting { code: "evidence.posture.local-assurance", key: "assuranceProfile", - summary: "local assurance permits locally held signing keys", + summary: "Local assurance permits locally held signing keys", production: "Build a production or evidence-grade package with a Transit signer.", }; diff --git a/crates/registry-evidencectl/src/store_provision.rs b/crates/registry-evidencectl/src/store_provision.rs index e9981cdd53..5f55aa8f24 100644 --- a/crates/registry-evidencectl/src/store_provision.rs +++ b/crates/registry-evidencectl/src/store_provision.rs @@ -4,12 +4,12 @@ use std::{path::Path, process::ExitCode}; use registry_platform_config::{ - describe_secret_failure, DatabaseConfig, DatabaseMember, DatabaseTransport, DeclaredPosture, - RuntimeConfigLoader, RuntimeEnvelope, StrictSecretProvidersConfig, DEFAULT_STAND_IN, + DatabaseConfig, DatabaseMember, DatabaseTransport, DeclaredPosture, RuntimeConfigLoader, + RuntimeEnvelope, SecretError, StrictSecretProvidersConfig, DEFAULT_STAND_IN, }; use registry_platform_provision::{ - provision_transport, run_provision, ProductDatabase, ProvisionArgs, ProvisionInput, - SchemaLayout, + provision_transport, read_ca_bundle, run_provision, secret_refusal, secret_refusal_code, + url_not_text_refusal, ProductDatabase, ProvisionArgs, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::{Diagnostic, Report, Source}; use serde::{Deserialize, Deserializer}; @@ -247,35 +247,33 @@ fn load(path: &Path, declared: DeclaredPosture) -> Result Result { "/database/testOnlyPlaintext".to_owned() } - Self::DatabaseTransport(_) => "/database/transport".to_owned(), + Self::DatabaseTransport(error) => error.database_pointer().to_owned(), Self::RecordRetentionShorterThanPayload => "/retention/recordRetentionDays".to_owned(), Self::ReceiptRetentionLongerThanRecord => "/retention/receiptRetentionDays".to_owned(), Self::TooManyTlsTrustProfiles => "/tlsTrustProfiles".to_owned(), diff --git a/crates/registry-messaging/src/http.rs b/crates/registry-messaging/src/http.rs index 8424390e17..9f8e6d3d39 100644 --- a/crates/registry-messaging/src/http.rs +++ b/crates/registry-messaging/src/http.rs @@ -3245,6 +3245,11 @@ mod tests { None, ), ), + ( + "expired access token", + FailedCheck::TokenTime, + request("GET", message, bearer(&claims_with("exp", json!(1))), None), + ), ( "other issuer", FailedCheck::TokenIssuer, @@ -3384,6 +3389,15 @@ mod tests { let logs = captured.finish(); assert!(response.status().is_client_error(), "{name}"); assert_counted_under(&metrics, &logs, check, name); + let guidance = match check { + FailedCheck::TokenAudience => Some("aud claim"), + FailedCheck::TokenTime => Some("exp claim"), + FailedCheck::Scope => Some("required_scope="), + _ => None, + }; + if let Some(guidance) = guidance { + assert!(logs.contains(guidance), "{name}: {logs}"); + } } } diff --git a/crates/registry-messaging/src/smtp/settings.rs b/crates/registry-messaging/src/smtp/settings.rs index 1203b3da2c..e53f9f8dca 100644 --- a/crates/registry-messaging/src/smtp/settings.rs +++ b/crates/registry-messaging/src/smtp/settings.rs @@ -13,8 +13,6 @@ use registry_platform_config::{SecretReference, SecretResolver}; use registry_platform_httputil::destination::{ DestinationPolicyError, ProductionAddressPolicy, MAX_DESTINATION_PRIVATE_CIDRS, }; -use rustls::pki_types::pem::PemObject as _; -use rustls::pki_types::CertificateDer; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -319,12 +317,8 @@ impl SmtpProviderSettings { &error, )) })?; - let certificates = CertificateDer::pem_slice_iter(pem.expose_secret()) - .collect::, _>>() + let certificates = registry_platform_postgres::pem_roots(pem.expose_secret()) .map_err(|_| SmtpSettingsError::InvalidTrustedRootCertificate)?; - if certificates.is_empty() { - return Err(SmtpSettingsError::InvalidTrustedRootCertificate); - } for der in certificates { let certificate = Certificate::from_der(der.to_vec()) .map_err(|_| SmtpSettingsError::InvalidTrustedRootCertificate)?; diff --git a/crates/registry-messaging/src/store.rs b/crates/registry-messaging/src/store.rs index 502cf4b469..20e9e9995b 100644 --- a/crates/registry-messaging/src/store.rs +++ b/crates/registry-messaging/src/store.rs @@ -13,7 +13,6 @@ //! the runtime only reads the resulting schema and activation state. use registry_platform_config::{DatabaseTransport, DatabaseTransportError, DevelopmentWitness}; -use std::str::FromStr; use std::time::Duration; use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; @@ -149,7 +148,7 @@ impl PostgresStore { config, secrets, witness, - "database.runtimeUrlRef", + registry_platform_config::DatabaseMember::RuntimeUrl, &config.runtime_url_ref, ) } @@ -163,7 +162,7 @@ impl PostgresStore { config, secrets, witness, - "database.migrationUrlRef", + registry_platform_config::DatabaseMember::MigrationUrl, &config.migration_url_ref, ) } @@ -172,11 +171,15 @@ impl PostgresStore { config: &DatabaseConfig, secrets: &SecretResolver, witness: Option<&DevelopmentWitness>, - field: &'static str, + member: registry_platform_config::DatabaseMember, reference: &str, ) -> Result { let protected = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure(field, reference, &error)) + StoreError::SecretConfiguration(describe_secret_failure( + &format!("database.{member}"), + reference, + &error, + )) })?; let url = std::str::from_utf8(protected.expose_secret()) .map_err(|_| StoreError::Configuration)?; @@ -184,6 +187,7 @@ impl PostgresStore { config, url, witness, + member, ®istry_platform_config::resolve_database_host, )?; let manager_config = ManagerConfig { @@ -469,20 +473,8 @@ fn tls_connector( &error, )) })?; - let mut roots = rustls::RootCertStore::empty(); - use rustls::pki_types::pem::PemObject as _; - let mut count = 0usize; - for certificate in - rustls::pki_types::CertificateDer::pem_slice_iter(certificate.expose_secret()) - { - roots - .add(certificate.map_err(|_| StoreError::Configuration)?) - .map_err(|_| StoreError::Configuration)?; - count += 1; - } - if count == 0 { - return Err(StoreError::Configuration); - } + let roots = registry_platform_postgres::pem_root_store(certificate.expose_secret()) + .map_err(|_| StoreError::Configuration)?; let client = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); @@ -502,9 +494,11 @@ fn driver_config( config: &DatabaseConfig, url: &str, witness: Option<&DevelopmentWitness>, + member: registry_platform_config::DatabaseMember, resolve: ®istry_platform_config::HostResolver, ) -> Result<(PgConfig, bool), StoreError> { - let postgres = PgConfig::from_str(url).map_err(|_| StoreError::Configuration)?; + let postgres = registry_platform_postgres::parse_runtime_url(url, config, witness) + .map_err(|error| error.at_url(member))?; if postgres.get_user().is_none() || postgres.get_dbname().is_none() { return Err(StoreError::Configuration); } @@ -526,6 +520,30 @@ mod driver_config_tests { use super::*; + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config = DatabaseConfig { + runtime_url_ref: "secret:env/DB_RUNTIME".to_owned(), + migration_url_ref: "secret:env/DB_MIGRATION".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: None, + }; + let (postgres, tls) = driver_config( + &config, + "postgresql://app@db.example/messaging?sslmode=verify-full", + None, + registry_platform_config::DatabaseMember::RuntimeUrl, + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert!(tls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping @@ -548,6 +566,7 @@ mod driver_config_tests { &config, "postgresql://app@localhost:5433/messaging", None, + registry_platform_config::DatabaseMember::RuntimeUrl, &fixed, ) .unwrap(); diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index 6d243afba5..946ca92ce7 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -1791,7 +1791,7 @@ fn apply_failure(error: RuntimeError) -> Outcome { let mut outcome = Outcome::refused( DOMAIN_REFUSAL_EXIT, error.code(), - "/database/transport", + error.database_pointer(), error.to_string(), ); outcome.report["diagnostics"][0]["suggestedAction"] = json!(error.suggested_action()); diff --git a/crates/registry-messagingctl/src/provision.rs b/crates/registry-messagingctl/src/provision.rs index a488c5867d..ce06b1db39 100644 --- a/crates/registry-messagingctl/src/provision.rs +++ b/crates/registry-messagingctl/src/provision.rs @@ -8,9 +8,10 @@ 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, DatabaseMember}; +use registry_platform_config::{DatabaseMember, SecretError}; use registry_platform_provision::{ - provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, + provision_transport, read_ca_bundle, secret_refusal, secret_refusal_code, url_not_text_refusal, + ProductDatabase, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::Diagnostic; use zeroize::Zeroizing; @@ -33,6 +34,17 @@ fn refused(code: &str, path: &str, message: String, action: &str) -> Box Vec { + diagnostic.artifact = Some(MESSAGING_RUNTIME_KIND.to_owned()); + vec![diagnostic] +} + +/// The shared refusal of a database member's secret or public document. +fn secret_refused(member: DatabaseMember, error: &SecretError) -> Vec { + in_runtime_file(secret_refusal("database", member, error)) +} + /// Reads the runtime file exactly as `apply` does and resolves the two /// database URLs and the CA behind `database.caBundleRef`. pub(crate) fn load( @@ -68,35 +80,22 @@ pub(crate) fn load( .resolver(config.development_witness()) .map_err(|error| { refuse( - "config.refused", + secret_refusal_code(&error), "/secretProviders", error.to_string(), - "Correct secretProviders in the runtime file, then run provision again.", + error.suggested_action(), ) })?; 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), - error.suggested_action(), - ) - }) + member + .read(&secrets, reference) + .map_err(|error| secret_refused(member, &error)) }; 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( - "config.refused", - &format!("/database/{member}"), - format!("database.{member} is not UTF-8 text"), - "Put a PostgreSQL URL in the secret, then run provision again.", - ) - }) + .map_err(|_| in_runtime_file(url_not_text_refusal("database", member))) }; let migration_url = url( DatabaseMember::MigrationUrl, @@ -107,9 +106,11 @@ pub(crate) fn load( .database .ca_bundle_ref .as_deref() - .map(|reference| resolve(DatabaseMember::CaBundle, reference)) - .transpose()? - .map(|secret| secret.expose_secret().to_vec()); + .map(|reference| { + read_ca_bundle(&secrets, "database", reference) + .map_err(|refused| in_runtime_file(*refused)) + }) + .transpose()?; Ok(ProvisionInput { product: product(), migration_url, diff --git a/crates/registry-messagingctl/tests/provision_cli.rs b/crates/registry-messagingctl/tests/provision_cli.rs index df6f80f1af..2c5633297b 100644 --- a/crates/registry-messagingctl/tests/provision_cli.rs +++ b/crates/registry-messagingctl/tests/provision_cli.rs @@ -200,7 +200,7 @@ fn a_world_readable_ca_bundle_loads_and_the_mount_policy_is_noticed() { let ca = directory.path().join("secrets").join("database-ca.pem"); std::fs::write( &ca, - "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n", + registry_platform_provision::test_support::ca_bundle_pem(), ) .unwrap(); std::fs::set_permissions(&ca, std::fs::Permissions::from_mode(0o644)).unwrap(); @@ -355,12 +355,15 @@ fn a_missing_runtime_url_secret_is_refused_at_its_member() { 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["code"], "platform.provision.secret-unavailable", + "{report:#}" + ); assert_eq!(diagnostic["path"], "/database/runtimeUrlRef", "{report:#}"); } #[test] -fn a_ca_bundle_that_is_not_text_is_refused_at_its_member() { +fn a_ca_bundle_without_a_certificate_is_refused_at_its_member() { let directory = scratch(); let runtime = write_runtime(directory.path()); let ca = directory.path().join("secrets").join("database-ca.pem"); @@ -376,13 +379,16 @@ fn a_ca_bundle_that_is_not_text_is_refused_at_its_member() { 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["code"], "platform.provision.ca-bundle-no-certificate", + "{report:#}" + ); assert_eq!(diagnostic["path"], "/database/caBundleRef", "{report:#}"); assert!( diagnostic["message"] .as_str() .unwrap() - .contains("not UTF-8 text"), + .contains("holds no PEM certificate"), "{report:#}" ); } @@ -396,7 +402,10 @@ fn a_migration_url_secret_that_is_not_text_is_refused_at_its_member() { 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["code"], "platform.provision.secret-value-invalid", + "{report:#}" + ); assert_eq!( diagnostic["path"], "/database/migrationUrlRef", "{report:#}" @@ -405,7 +414,7 @@ fn a_migration_url_secret_that_is_not_text_is_refused_at_its_member() { diagnostic["message"] .as_str() .unwrap() - .contains("not UTF-8"), + .contains("is not UTF-8 text"), "{report:#}" ); } diff --git a/crates/registry-platform-config/src/blocks.rs b/crates/registry-platform-config/src/blocks.rs index 9444678671..63772d1dbe 100644 --- a/crates/registry-platform-config/src/blocks.rs +++ b/crates/registry-platform-config/src/blocks.rs @@ -368,8 +368,33 @@ impl StrictSecretProvidersConfig { /// it is never repeated: the member path and a fixed reason are named. The /// resolved bytes and opened path never appear either. The reference parameter /// stays so a caller keeps one call shape; it is not read. +/// +/// For a refused file or public document the sentence ends with the error's +/// fix, because a runtime refusal carries no separate fix field. A caller that +/// reports [`SecretError::suggested_action`] beside the message uses +/// [`describe_secret_reason`] instead. #[must_use] pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretError) -> String { + let reason = describe_secret_reason(field, error); + match error { + SecretError::UnsafeFile(_) + | SecretError::UnsafePublicDocument(_) + | SecretError::PrivateKeyInPublicDocument => { + format!("{reason}. {}", error.suggested_action()) + } + SecretError::InvalidReference + | SecretError::ProviderDisabled + | SecretError::InvalidProviderConfiguration + | SecretError::Unavailable + | SecretError::Read + | SecretError::InvalidValue => reason, + } +} + +/// [`describe_secret_failure`] without the fix, for a diagnostic that reports +/// [`SecretError::suggested_action`] in its own field. +#[must_use] +pub fn describe_secret_reason(field: &str, error: &SecretError) -> String { let reason = match error { SecretError::InvalidReference => { "it is not an exact secret:env/NAME or secret:file/name reference".to_owned() @@ -381,26 +406,13 @@ pub fn describe_secret_failure(field: &str, _reference: &str, error: &SecretErro SecretError::Unavailable => { "no readable secret of that name exists under the configured provider".to_owned() } - SecretError::UnsafeFile(check) => format!( - "{} ({}). {}", - check.message(), - 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::UnsafeFile(check) => format!("{} ({})", check.message(), check.code()), + SecretError::UnsafePublicDocument(check) => { + format!("{} ({})", check.public_message(), check.code()) + } + SecretError::PrivateKeyInPublicDocument => { + "the public document holds a PEM private key block".to_owned() + } 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 \ @@ -461,16 +473,16 @@ impl DatabaseMember { } /// 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. + /// bundle is a public document; its certificates are read by + /// `registry_platform_postgres::pem_roots` where it is used, so the bytes + /// are returned as they are. pub fn read( self, resolver: &SecretResolver, reference: &str, ) -> Result { match self { - Self::CaBundle => utf8_text(resolver.resolve_public_document(reference)?), + Self::CaBundle => resolver.resolve_public_document(reference), Self::RuntimeUrl | Self::MigrationUrl => resolver.resolve(reference), } } @@ -482,19 +494,12 @@ impl DatabaseMember { reference: &SecretReference, ) -> Result { match self { - Self::CaBundle => utf8_text(resolver.resolve_public_document_reference(reference)?), + Self::CaBundle => 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()) @@ -578,11 +583,87 @@ pub enum DatabaseHost { Unix, } +/// TLS policy for PostgreSQL connection-string diagnostics. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DatabaseSslModePolicy { + /// Only settings compatible with plaintext are accepted. + Plaintext, + /// The caller accepts the driver modes without interpreting verify-full. + DriverModes, + /// A verified TLS connector accepts verify-full in URL form. + VerifiedUrl, + /// A verified TLS connector received a keyword connection string. + VerifiedKeywords, +} + +/// Value-free PostgreSQL connection string refusals. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DatabaseUrlError { + /// The connection string could not be parsed. + Invalid, + /// The spelling is unsupported by this connection-string form or policy. + UnsupportedSslMode(DatabaseSslModePolicy), + /// A verify-full URL has another sslmode parameter. + DuplicateSslMode, + /// The URL requests TLS and the selected transport uses plaintext. + SslModeTransportMismatch, +} + +impl DatabaseUrlError { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::Invalid => "platform.database.invalid-url", + Self::UnsupportedSslMode(_) => "platform.database.unsupported-sslmode", + Self::DuplicateSslMode => "platform.database.duplicate-sslmode", + Self::SslModeTransportMismatch => "platform.database.sslmode-transport-mismatch", + } + } + + #[must_use] + pub const fn message(self) -> &'static str { + match self { + Self::Invalid => "the PostgreSQL connection URL is invalid", + Self::UnsupportedSslMode(DatabaseSslModePolicy::VerifiedUrl) => { + "unsupported PostgreSQL sslmode; accepted values are disable, prefer, require, and verify-full" + } + Self::UnsupportedSslMode(DatabaseSslModePolicy::Plaintext) => { + "unsupported PostgreSQL sslmode; accepted values for plaintext are disable and prefer" + } + Self::UnsupportedSslMode(_) => { + "unsupported PostgreSQL sslmode; accepted values are disable, prefer, and require" + } + Self::DuplicateSslMode => "the PostgreSQL URL must specify sslmode only once", + Self::SslModeTransportMismatch => "the PostgreSQL sslmode disagrees with the plaintext transport", + } + } + + #[must_use] + pub const fn suggested_action(self) -> &'static str { + match self { + Self::Invalid => "Supply a valid PostgreSQL connection URL.", + Self::UnsupportedSslMode(DatabaseSslModePolicy::VerifiedUrl) => { + "Set sslmode to verify-full or require. Verified TLS checks the server certificate and hostname." + } + Self::UnsupportedSslMode(DatabaseSslModePolicy::VerifiedKeywords) => { + "Write the connection as a postgresql:// URL to use verify-full." + } + Self::UnsupportedSslMode(_) => "Use a supported sslmode or omit it.", + Self::DuplicateSslMode => "Keep only one sslmode query parameter.", + Self::SslModeTransportMismatch => { + "Set the transport to verified-tls, or remove sslmode from the connection URL to use the configured plaintext transport." + } + } + } +} + /// Why a database transport was refused. No variant repeats a configured /// value, except that `BracketedHost` names the IP address literal it /// refuses: never a name, a port or a credential. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DatabaseTransportError { + /// The runtime or migration connection string was refused. + Url(DatabaseUrlError, Option), /// A host is not one the plaintext transport permits. HostMismatch(DatabaseTransport), /// The transport is development-only and the caller holds no witness. @@ -599,10 +680,48 @@ pub enum DatabaseTransportError { } impl DatabaseTransportError { + /// Attach the configuration member to a URL refusal. + #[must_use] + pub fn at_url(self, member: DatabaseMember) -> Self { + match self { + Self::Url(error, _) => Self::Url(error, Some(member)), + other => other, + } + } + + #[must_use] + pub const fn url_member(self) -> Option { + match self { + Self::Url(_, member) => member, + _ => None, + } + } + + #[must_use] + pub fn database_pointer(self) -> &'static str { + match self.url_member() { + Some(DatabaseMember::RuntimeUrl) => "/database/runtimeUrlRef", + Some(DatabaseMember::MigrationUrl) => "/database/migrationUrlRef", + Some(DatabaseMember::CaBundle) => "/database/caBundleRef", + None => "/database/transport", + } + } + + #[must_use] + pub fn database_field(self) -> &'static str { + match self.url_member() { + Some(DatabaseMember::RuntimeUrl) => "database.runtimeUrlRef", + Some(DatabaseMember::MigrationUrl) => "database.migrationUrlRef", + Some(DatabaseMember::CaBundle) => "database.caBundleRef", + None => "database.transport", + } + } + /// The stable code of the refusal (CFG-DIAG-3). #[must_use] pub const fn code(&self) -> &'static str { match self { + Self::Url(error, _) => error.code(), Self::HostMismatch(_) => "platform.database.transport-host-mismatch", Self::DevelopmentOnly(refused) => refused.setting.code, Self::Conflict => "platform.database.transport-conflict", @@ -615,6 +734,7 @@ impl DatabaseTransportError { #[must_use] pub const fn suggested_action(&self) -> &'static str { match self { + Self::Url(error, _) => error.suggested_action(), Self::HostMismatch(DatabaseTransport::PrivateNetworkPlaintext) => { "Name a Unix socket, a loopback address, a private-network address or a name that resolves only to such addresses, or write database.transport: verified-tls." } @@ -631,11 +751,12 @@ impl DatabaseTransportError { } } } -} -impl fmt::Display for DatabaseTransportError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - let text = match self { + /// The value-free description shared by runtime and CLI diagnostics. + #[must_use] + pub const fn message(&self) -> &'static str { + match self { + Self::Url(error, _) => error.message(), Self::HostMismatch(_) => { "a database host is not one the configured plaintext transport permits" } @@ -644,14 +765,28 @@ impl fmt::Display for DatabaseTransportError { } Self::Conflict => "database.transport and database.testOnlyPlaintext are both set", Self::TestOnlyPlaintext => "database.testOnlyPlaintext is accepted only by test builds", - Self::BracketedHost(address) => { - return write!( - formatter, - "the database host [{address}] is written in brackets in a keyword connection string" - ); + Self::BracketedHost(_) => { + "the database host is an IP address written in brackets in a keyword connection string" } - }; - formatter.write_str(text) + } + } +} + +impl From for DatabaseTransportError { + fn from(error: DatabaseUrlError) -> Self { + Self::Url(error, None) + } +} + +impl fmt::Display for DatabaseTransportError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Self::BracketedHost(address) = self { + return write!( + formatter, + "the database host [{address}] is written in brackets in a keyword connection string" + ); + } + formatter.write_str(self.message()) } } @@ -672,6 +807,20 @@ impl DatabaseConfig { Ok(()) } + /// The named transport, defaulting to verified TLS, before checking hosts. + pub fn declared_transport( + &self, + witness: Option<&DevelopmentWitness>, + ) -> Result { + match &self.transport { + None => Ok(DatabaseTransport::VerifiedTls), + Some(gated) => gated + .get(witness) + .copied() + .map_err(DatabaseTransportError::DevelopmentOnly), + } + } + /// The transport the connection uses, once `hosts` are known, and under a /// plaintext transport the numeric addresses each host was checked as. A /// plaintext transport is returned only when every host is one it @@ -739,12 +888,7 @@ pub(crate) fn permitted_transport_with( witness: Option<&DevelopmentWitness>, resolve: &dyn Fn(&str) -> std::io::Result>, ) -> Result { - let transport = match &config.transport { - None => DatabaseTransport::VerifiedTls, - Some(gated) => *gated - .get(witness) - .map_err(DatabaseTransportError::DevelopmentOnly)?, - }; + let transport = config.declared_transport(witness)?; check_database_hosts(transport, hosts, resolve) } diff --git a/crates/registry-platform-config/src/blocks_tests.rs b/crates/registry-platform-config/src/blocks_tests.rs index 472d72c968..45ce83bb35 100644 --- a/crates/registry-platform-config/src/blocks_tests.rs +++ b/crates/registry-platform-config/src/blocks_tests.rs @@ -140,27 +140,20 @@ fn public_documents(files: &[(&str, &[u8])]) -> (tempfile::TempDir, SecretResolv #[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])]); +fn a_database_ca_bundle_is_read_as_its_bytes() { + // The certificates are read where the bundle is used, so bytes that are + // not UTF-8 reach that reader unchanged. + let bytes = [0xff, 0xfe, 0xfd]; + let (_root, resolver) = public_documents(&[("binary", &bytes)]); 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}"); + let read = DatabaseMember::CaBundle + .read(&resolver, "secret:file/binary") + .unwrap(); + assert_eq!(read.expose_secret(), bytes); + let read = DatabaseMember::CaBundle + .read_reference(&resolver, &reference) + .unwrap(); + assert_eq!(read.expose_secret(), bytes); } #[cfg(unix)] @@ -187,7 +180,7 @@ fn a_database_ca_bundle_accepts_every_text_shape_of_pem() { #[cfg(unix)] #[test] -fn a_private_key_is_refused_before_the_text_rule() { +fn a_private_key_is_refused_in_a_ca_bundle_of_any_encoding() { let key = [ &[0xff, 0xfe][..], b"\n-----BEGIN PRIVATE KEY-----\nMII\n-----END PRIVATE KEY-----\n", @@ -1215,6 +1208,39 @@ fn a_secret_failure_names_the_member_and_never_the_reference() { } } +#[test] +fn a_secret_reason_is_the_failure_without_its_fix() { + use crate::SecretFileCheck::WorldReadable; + + for error in [ + SecretError::InvalidReference, + SecretError::ProviderDisabled, + SecretError::InvalidProviderConfiguration, + SecretError::Unavailable, + SecretError::UnsafeFile(WorldReadable), + SecretError::UnsafePublicDocument(WorldReadable), + SecretError::PrivateKeyInPublicDocument, + SecretError::Read, + SecretError::InvalidValue, + ] { + let reason = describe_secret_reason("database.caBundleRef", &error); + let failure = describe_secret_failure("database.caBundleRef", "secret:file/canary", &error); + assert!(reason.contains("database.caBundleRef"), "{reason}"); + assert!(!reason.contains(error.suggested_action()), "{reason}"); + // The failure is the reason, with the fix appended where the runtime + // refusal carries no separate fix field. + assert!(failure.starts_with(&reason), "{failure}"); + match error { + SecretError::UnsafeFile(_) + | SecretError::UnsafePublicDocument(_) + | SecretError::PrivateKeyInPublicDocument => { + assert_eq!(failure, format!("{reason}. {}", error.suggested_action())); + } + _ => assert_eq!(failure, reason), + } + } +} + const TASK_GRANT_STATUS: &str = "sourceIssuer: urn:authority:source\n\ baseUrl: https://authority.example.test\n\ tokenEndpoint: https://identity.example.test/oauth2/token\n\ diff --git a/crates/registry-platform-config/src/caller_issuers.rs b/crates/registry-platform-config/src/caller_issuers.rs index 000a0602e0..1c6298b292 100644 --- a/crates/registry-platform-config/src/caller_issuers.rs +++ b/crates/registry-platform-config/src/caller_issuers.rs @@ -23,31 +23,31 @@ use crate::{ExplicitClass, ExplicitProductionSetting, PackageClients, RuntimeFil static JWT_ACCESS_TOKEN: ExplicitProductionSetting = ExplicitProductionSetting { code: "platform.posture.jwt-access-token", key: "accessTokenType", - summary: "admits access tokens typed JWT. ID tokens stay refused", + summary: "This setting admits access tokens typed JWT. ID tokens stay refused", }; static SCOPE_CLAIM: ExplicitProductionSetting = ExplicitProductionSetting { code: "platform.posture.scope-claim", key: "scopeClaim", - summary: "reads scopes from a claim other than scope", + summary: "The service reads scopes from a claim other than scope", }; static UNRESTRICTED_CLIENTS: ExplicitProductionSetting = ExplicitProductionSetting { code: "platform.posture.unrestricted-clients", key: "allowedClients", - summary: "admits a token from every client this issuer signs for", + summary: "This issuer entry admits a token from every client this issuer signs for", }; static ISSUER_ACTOR_KIND: ExplicitProductionSetting = ExplicitProductionSetting { code: "platform.posture.issuer-actor-kind", key: "actorKind", - summary: "every token from this issuer is treated as the declared kind", + summary: "Every token from this issuer is treated as the declared kind", }; static CLIENT_ACTOR_KINDS: ExplicitProductionSetting = ExplicitProductionSetting { code: "platform.posture.client-actor-kinds", key: "clientActorKinds", - summary: "tokens from the named clients are treated as the declared kinds", + summary: "Tokens from the named clients are treated as the declared kinds", }; /// The claim names a scope claim may not take: they identify the caller, so diff --git a/crates/registry-platform-config/src/lib.rs b/crates/registry-platform-config/src/lib.rs index a2704968ff..4ad9dd89e7 100644 --- a/crates/registry-platform-config/src/lib.rs +++ b/crates/registry-platform-config/src/lib.rs @@ -33,14 +33,15 @@ pub use blocks::non_empty_assertion_issuers; #[cfg(feature = "schema")] pub use blocks::{assertion_issuers_schema, url_hook_destinations_schema}; pub use blocks::{ - check_database_hosts, describe_secret_failure, deserialize_insecure_http, - deserialize_issuer_endpoint, deserialize_jwks_source, deserialize_published_issuer, - 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, DatabaseMember, DatabaseTransport, - DatabaseTransportError, EnvironmentSecretProviderConfig, FileSecretProviderConfig, - HostResolver, InsecureHttp, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, + check_database_hosts, describe_secret_failure, describe_secret_reason, + deserialize_insecure_http, deserialize_issuer_endpoint, deserialize_jwks_source, + deserialize_published_issuer, 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, + DatabaseMember, DatabaseSslModePolicy, DatabaseTransport, DatabaseTransportError, + DatabaseUrlError, EnvironmentSecretProviderConfig, FileSecretProviderConfig, HostResolver, + InsecureHttp, JwksSource, ListenerBind, ListenerConfig, ListenerNetworkExposure, MetricsListenerConfig, ObjectStorageConfig, OidcClientsConfig, OidcIssuerConfig, OidcPackageClientsConfig, PackageClients, PackageClientsError, PackageConfig, PackageDigestMismatch, PermittedTransport, PrivateListenerConfig, SecretProvidersConfig, diff --git a/crates/registry-platform-config/src/posture.rs b/crates/registry-platform-config/src/posture.rs index 9b5ab0dcd3..1ac00a10cd 100644 --- a/crates/registry-platform-config/src/posture.rs +++ b/crates/registry-platform-config/src/posture.rs @@ -139,7 +139,7 @@ pub struct DevelopmentSetting { pub code: &'static str, /// The authored key that holds the value: the last pointer segment. pub key: &'static str, - /// Value-free: what the setting weakens. + /// Value-free sentence describing what the setting weakens, without a final period. pub summary: &'static str, /// What to write for production. pub production: &'static str, @@ -438,7 +438,7 @@ pub struct ExplicitProductionSetting { pub code: &'static str, /// The authored key, the last pointer segment. pub key: &'static str, - /// Value-free: what it relaxes and why the operator states it. + /// Value-free sentence describing what it relaxes, without a final period. pub summary: &'static str, } diff --git a/crates/registry-platform-config/src/secrets.rs b/crates/registry-platform-config/src/secrets.rs index 08a3475e4d..8a8c09ec5a 100644 --- a/crates/registry-platform-config/src/secrets.rs +++ b/crates/registry-platform-config/src/secrets.rs @@ -200,10 +200,6 @@ pub enum SecretError { /// 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")] @@ -233,9 +229,6 @@ impl SecretError { 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." diff --git a/crates/registry-platform-oidc/src/diagnostics.rs b/crates/registry-platform-oidc/src/diagnostics.rs index a6fa1c772a..a65d704a6b 100644 --- a/crates/registry-platform-oidc/src/diagnostics.rs +++ b/crates/registry-platform-oidc/src/diagnostics.rs @@ -58,8 +58,8 @@ impl OidcError { } /// The sentence for the operator's log line that names the issuer entry - /// setting involved in a caller-contract refusal, or `None` for a refusal - /// no setting changes. `admits_jwt` says whether the entry that refused + /// setting or the token claim involved in a caller-contract refusal, or + /// `None` for a refusal no setting or claim names a fix for. `admits_jwt` says whether the entry that refused /// admits access tokens typed `JWT`. /// /// A remedy names keys, never values. It belongs on the log line beside @@ -100,6 +100,15 @@ impl OidcError { kind in clientActorKinds, or the issuer's in actorKind, or have the provider \ grant a scope.", ), + Self::AudienceMismatch => Some( + "The token's aud claim does not name the audience this issuer entry declares. \ + Have the provider issue the token for that audience, or correct audience on \ + the entry.", + ), + Self::TokenExpired => Some( + "The token is past the time in its exp claim. Request a new token, or have the \ + provider issue tokens whose lifetime covers the caller's use.", + ), _ => None, } } @@ -233,6 +242,8 @@ mod failed_check_tests { OidcError::ActorKindConflict, OidcError::ActorKindMalformed, OidcError::IdentityOnly, + OidcError::AudienceMismatch, + OidcError::TokenExpired, ] .into_iter() .map(|error| { @@ -254,6 +265,8 @@ mod failed_check_tests { OidcError::ActorKindConflict | OidcError::ActorKindMalformed | OidcError::IdentityOnly => &["actorKind", "clientActorKinds"], + OidcError::AudienceMismatch => &["aud", "audience"], + OidcError::TokenExpired => &["exp"], _ => &[], }; for key in keys { @@ -309,12 +322,22 @@ mod failed_check_tests { } #[test] - fn a_refusal_no_setting_changes_has_no_remedy() { + fn the_expiry_remedy_names_exp_and_no_other_time_claim() { + let remedy = OidcError::TokenExpired.remedy(true).unwrap(); + assert!(remedy.contains("exp"), "{remedy}"); + assert!( + !remedy.contains("nbf") && !remedy.contains("iat"), + "{remedy}" + ); + } + + #[test] + fn a_refusal_no_setting_or_claim_changes_has_no_remedy() { for error in [ OidcError::MalformedToken, OidcError::SignatureInvalid, - OidcError::TokenExpired, - OidcError::AudienceMismatch, + OidcError::TokenNotYetValid, + OidcError::InvalidTimeClaims, OidcError::ClientNotAllowed, OidcError::UnknownKid, OidcError::DevelopmentAssertion, diff --git a/crates/registry-platform-oidc/src/issuer_set.rs b/crates/registry-platform-oidc/src/issuer_set.rs index c8d04e4e97..0b84feae17 100644 --- a/crates/registry-platform-oidc/src/issuer_set.rs +++ b/crates/registry-platform-oidc/src/issuer_set.rs @@ -80,8 +80,8 @@ pub struct CallerRefusal { /// The refusal. Its [`OidcError::failed_check`] is the check to count and /// log. pub error: OidcError, - /// The sentence for the operator's log line that names the setting - /// involved, from [`OidcError::remedy`]. It names keys, never values, and + /// The sentence for the operator's log line that names the setting or + /// claim involved, from [`OidcError::remedy`]. It names keys, never values, and /// never enters a response body. pub remedy: Option<&'static str>, } diff --git a/crates/registry-platform-oidc/src/issuer_set_tests.rs b/crates/registry-platform-oidc/src/issuer_set_tests.rs index 2a4952cc56..0dc0d84f78 100644 --- a/crates/registry-platform-oidc/src/issuer_set_tests.rs +++ b/crates/registry-platform-oidc/src/issuer_set_tests.rs @@ -748,6 +748,41 @@ async fn the_kind_claim_is_read_with_the_set_s_claim_names() { assert_eq!(verified.kind, CallerKind::Claimed(ActorKind::Agent)); } +#[tokio::test] +async fn a_wrong_audience_or_expired_token_carries_the_remedy_that_names_its_claim() { + let set = issuers(vec![IssuerEntry::new( + "staff", + verifier(ISSUER_A, "a-key", SECRET_A, "at+jwt", vec![]).await, + DeclaredKinds::None, + )]) + .unwrap(); + let other_audience = sign( + "a-key", + SECRET_A, + Some("at+jwt"), + claims(ISSUER_A, json!({"aud": "another-service"})), + ); + let refused = set.verify(&other_audience).await.unwrap_err(); + assert!(matches!(refused.error, OidcError::AudienceMismatch)); + let remedy = refused.remedy.expect("a wrong audience names its fix"); + assert!( + remedy.contains("aud") && remedy.contains("audience"), + "{remedy}" + ); + assert!(!remedy.contains("another-service") && !remedy.contains("registry-api")); + + let expired = sign( + "a-key", + SECRET_A, + Some("at+jwt"), + claims(ISSUER_A, json!({"exp": 1_700_000_100_i64})), + ); + let refused = set.verify(&expired).await.unwrap_err(); + assert!(matches!(refused.error, OidcError::TokenExpired)); + let remedy = refused.remedy.expect("an expired token names its fix"); + assert!(remedy.contains("exp"), "{remedy}"); +} + #[tokio::test] async fn a_refusal_carries_the_remedy_for_the_entry_that_refused() { let set = issuers(vec![ diff --git a/crates/registry-platform-postgres/Cargo.toml b/crates/registry-platform-postgres/Cargo.toml index 5bebd8d188..9db9f4b80b 100644 --- a/crates/registry-platform-postgres/Cargo.toml +++ b/crates/registry-platform-postgres/Cargo.toml @@ -13,8 +13,12 @@ publish = false workspace = true [dependencies] +percent-encoding = "2.3.2" registry-platform-config.workspace = true +rustls.workspace = true tokio-postgres.workspace = true [dev-dependencies] +base64.workspace = true +rcgen.workspace = true serde.workspace = true diff --git a/crates/registry-platform-postgres/README.md b/crates/registry-platform-postgres/README.md index 0d3f150df9..b446353972 100644 --- a/crates/registry-platform-postgres/README.md +++ b/crates/registry-platform-postgres/README.md @@ -2,8 +2,10 @@ `registry-platform-postgres` builds the `tokio_postgres::Config` a runtime's pool hands to the driver, from the host check in `registry-platform-config`. It keeps the PostgreSQL client out of the configuration crate, so a crate that reads configuration does not link `tokio-postgres`. +- `parse_runtime_url` and `parse_database_url` translate `sslmode=verify-full` in a URL to required TLS when the caller uses a connector that verifies the certificate chain and hostname. The original host remains available for verification. The parser refuses `verify-ca`, unsupported modes and repeated modes involving `verify-full` with value-free diagnostics. The selected transport continues to govern legacy driver modes. - `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. - `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. +- `pem_roots` and `pem_root_store` read a database CA bundle into trust roots, the one reading every runtime, `rstack dev` and the `provision` tools share. Text outside the certificate blocks is ignored in any encoding, a leading byte-order mark is skipped, other blocks are skipped, and a bundle over 1 MiB, with an unparseable block or unusable certificate, or with no certificate is refused with a value-free `PemRootsError`. - 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 8ed2cc157f..c1a956a19d 100644 --- a/crates/registry-platform-postgres/src/lib.rs +++ b/crates/registry-platform-postgres/src/lib.rs @@ -5,14 +5,24 @@ //! numeric addresses each was checked as. This crate builds the //! `tokio_postgres::Config` that dials only those addresses, so the //! configuration crate stays free of a PostgreSQL client. +//! +//! It also reads a database CA bundle into trust roots ([`pem_roots`]), the +//! one reading shared by every runtime, `rstack dev` and the `provision` +//! tools. + +mod roots; + +pub use roots::{pem_root_store, pem_roots, PemRootsError, MAX_PEM_ROOTS_BYTES}; -use std::net::IpAddr; #[cfg(unix)] use std::path::PathBuf; +use std::{borrow::Cow, error::Error as _, net::IpAddr}; +use percent_encoding::percent_decode_str; use registry_platform_config::{ - check_database_hosts, CheckedHost, DatabaseConfig, DatabaseHost, DatabaseTransport, - DatabaseTransportError, DevelopmentWitness, HostResolver, PermittedTransport, + check_database_hosts, CheckedHost, DatabaseConfig, DatabaseHost, DatabaseSslModePolicy, + DatabaseTransport, DatabaseTransportError, DatabaseUrlError, DevelopmentWitness, HostResolver, + PermittedTransport, }; use tokio_postgres::config::Host; use tokio_postgres::Config; @@ -20,6 +30,160 @@ use tokio_postgres::Config; /// The port the driver uses for a host when the configuration names none. const DEFAULT_PORT: u16 = 5432; +/// Parse a runtime's connection string for the transport it will use. +pub fn parse_runtime_url( + input: &str, + database: &DatabaseConfig, + witness: Option<&DevelopmentWitness>, +) -> Result { + let transport = database.declared_transport(witness)?; + if transport == DatabaseTransport::VerifiedTls && !database.test_only_plaintext { + return parse_database_url(input, true); + } + parse_connection_string(input, DatabaseSslModePolicy::Plaintext).map_err(Into::into) +} + +/// Parse a PostgreSQL connection string without exposing values in errors. +/// Set `verified_tls` only when the caller uses a connector that verifies the +/// server certificate chain and hostname. In a URL, `verify-full` then maps +/// to the driver's required TLS mode while retaining the original hostname. +pub fn parse_database_url( + input: &str, + verified_tls: bool, +) -> Result { + let policy = if !verified_tls { + DatabaseSslModePolicy::DriverModes + } else if is_postgres_url(input) { + DatabaseSslModePolicy::VerifiedUrl + } else { + DatabaseSslModePolicy::VerifiedKeywords + }; + parse_connection_string(input, policy).map_err(Into::into) +} + +fn is_postgres_url(input: &str) -> bool { + input.starts_with("postgres://") || input.starts_with("postgresql://") +} + +fn parse_connection_string( + input: &str, + policy: DatabaseSslModePolicy, +) -> Result { + let plaintext = policy == DatabaseSslModePolicy::Plaintext; + let input = if is_postgres_url(input) { + normalize_sslmode(input, policy)? + } else { + if plaintext && keyword_requests_tls(input) { + return Err(DatabaseUrlError::SslModeTransportMismatch); + } + Cow::Borrowed(input) + }; + let config = input.parse::().map_err(|error| { + if error + .source() + .is_some_and(|cause| cause.to_string() == "invalid value for option `sslmode`") + { + DatabaseUrlError::UnsupportedSslMode(policy) + } else { + DatabaseUrlError::Invalid + } + })?; + if plaintext && config.get_ssl_mode() == tokio_postgres::config::SslMode::Require { + return Err(DatabaseUrlError::SslModeTransportMismatch); + } + Ok(config) +} + +/// Scan keyword values before the driver collapses repeats by last value. +/// Quoting and backslash escapes keep password or option text out of the scan. +fn keyword_requests_tls(input: &str) -> bool { + let mut chars = input.chars().peekable(); + loop { + while chars.next_if(|ch| ch.is_whitespace()).is_some() {} + if chars.peek().is_none() { + return false; + } + let mut key = String::new(); + while let Some(ch) = chars.next_if(|ch| !ch.is_whitespace() && *ch != '=') { + key.push(ch); + } + while chars.next_if(|ch| ch.is_whitespace()).is_some() {} + if chars.next() != Some('=') { + return false; + } + while chars.next_if(|ch| ch.is_whitespace()).is_some() {} + let quoted = chars.next_if_eq(&'\'').is_some(); + let mut mode = String::new(); + while let Some(ch) = chars.next_if(|ch| { + if quoted { + *ch != '\'' + } else { + !ch.is_whitespace() + } + }) { + let decoded = if ch == '\\' { chars.next() } else { Some(ch) }; + if key == "sslmode" { + mode.extend(decoded); + } + } + if quoted && chars.next() != Some('\'') { + return false; + } + if key == "sslmode" && matches!(mode.as_str(), "require" | "verify-full") { + return true; + } + } +} + +fn normalize_sslmode( + input: &str, + policy: DatabaseSslModePolicy, +) -> Result, DatabaseUrlError> { + // Match the driver's first-at-sign rule for userinfo. Preserve the raw + // spelling of every field except the sslmode value we translate. + let authority = input.find('@').map_or(0, |index| index + 1); + let Some(offset) = input[authority..].find('?') else { + return Ok(Cow::Borrowed(input)); + }; + let (endpoint, query) = input.split_at(authority + offset + 1); + let mut translated = false; + let mut seen = false; + let pairs = query + .split('&') + .map(|pair| { + let Some((key, value)) = pair.split_once('=') else { + return Ok(pair); + }; + if percent_decode_str(key).decode_utf8().as_deref() != Ok("sslmode") { + return Ok(pair); + } + let mode = percent_decode_str(value).decode_utf8(); + if policy == DatabaseSslModePolicy::Plaintext + && matches!(mode.as_deref(), Ok("require" | "verify-full")) + { + return Err(DatabaseUrlError::SslModeTransportMismatch); + } + if seen && (translated || mode.as_deref() == Ok("verify-full")) { + return Err(DatabaseUrlError::DuplicateSslMode); + } + seen = true; + match mode.as_deref() { + Ok("disable" | "prefer" | "require") => Ok(pair), + Ok("verify-full") if policy == DatabaseSslModePolicy::VerifiedUrl => { + translated = true; + Ok("sslmode=require") + } + _ => Err(DatabaseUrlError::UnsupportedSslMode(policy)), + } + }) + .collect::, _>>()?; + if translated { + Ok(Cow::Owned(format!("{endpoint}{}", pairs.join("&")))) + } else { + Ok(Cow::Borrowed(input)) + } +} + /// Check every host and `hostaddr` of a parsed PostgreSQL configuration, as /// [`DatabaseConfig::permitted_transport`] does, with the host names looked /// up by `resolve`, and return the transport with the configuration the pool @@ -290,6 +454,85 @@ mod tests { RuntimeEnvelope, }; + #[test] + fn plaintext_rejects_urls_that_request_tls() { + let database = DatabaseConfig { + runtime_url_ref: "secret:file/runtime".to_owned(), + migration_url_ref: "secret:file/migration".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: Some( + registry_platform_config::Gated::everywhere(DatabaseTransport::LoopbackPlaintext) + .unwrap(), + ), + }; + for url in [ + "postgresql://app@localhost/db?sslmode=require", + "postgresql://app@localhost/db?sslmode=verify-full", + "postgresql://app@localhost/db?sslmode=require&sslmode=disable", + "host=localhost user=app dbname=db sslmode='require'", + r"host=localhost user=app dbname=db sslmode=re\quire sslmode=disable", + ] { + let error = super::parse_runtime_url(url, &database, None) + .unwrap_err() + .at_url(registry_platform_config::DatabaseMember::MigrationUrl); + assert_eq!(error.database_pointer(), "/database/migrationUrlRef"); + assert_eq!(error.code(), "platform.database.sslmode-transport-mismatch"); + assert!(error.to_string().contains("sslmode disagrees")); + } + let url = "host=localhost user=app dbname=db password='x sslmode=require'"; + assert!(super::parse_runtime_url(url, &database, None).is_ok()); + } + + #[test] + fn verify_full_requires_verified_tls_and_preserves_the_server_name() { + let url = "postgresql://app:synthetic%2Bpassword@db.example/registry?application_name=a+b&hostaddr=127.0.0.1&%73slmode=verify%2Dfull"; + let config = super::parse_database_url(url, true).unwrap(); + assert_eq!( + config.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + assert!(matches!(config.get_hosts(), [Host::Tcp(host)] if host == "db.example")); + assert_eq!( + config.get_hostaddrs(), + &["127.0.0.1".parse::().unwrap()] + ); + assert_eq!( + config.get_password(), + Some(b"synthetic+password".as_slice()) + ); + assert_eq!(config.get_application_name(), Some("a+b")); + + let error = super::parse_database_url(url, false).unwrap_err(); + assert_eq!(error.code(), "platform.database.unsupported-sslmode"); + } + + #[test] + fn verify_full_cannot_be_overridden_by_another_sslmode() { + let error = super::parse_database_url( + "postgresql://app@db.example/registry?sslmode=verify-full&%73slmode=disable", + true, + ) + .unwrap_err(); + assert_eq!(error.code(), "platform.database.duplicate-sslmode"); + } + + #[test] + fn sslmode_errors_do_not_expose_connection_values() { + for input in [ + "postgresql://app:secret-sentinel@db.example/registry?sslmode=verify-ca", + "postgresql://app:secret-sentinel@db.example/registry?sslmode=secret-sentinel", + "host=db.example password='secret-sentinel' sslmode='secret-sentinel'", + "host=db.example password='secret-sentinel' sslmode=allow", + ] { + let error = super::parse_database_url(input, true).unwrap_err(); + assert_eq!(error.code(), "platform.database.unsupported-sslmode"); + let display = error.to_string(); + assert!(display.contains("sslmode") && display.contains("require")); + assert!(!format!("{error:?} {error}").contains("secret-sentinel")); + } + } + use super::postgres_connection; const ENVELOPE: RuntimeEnvelope = RuntimeEnvelope { diff --git a/crates/registry-platform-postgres/src/roots.rs b/crates/registry-platform-postgres/src/roots.rs new file mode 100644 index 0000000000..5553fb8ca6 --- /dev/null +++ b/crates/registry-platform-postgres/src/roots.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The trust roots of a database CA bundle (`caBundleRef`, Messaging's +//! `tlsTrustProfiles.*.bundleRef`), read one way by every runtime, `rstack +//! dev` and the `provision` tools, so they accept and refuse the same bundles. +//! +//! A bundle is PEM bytes. Text outside the certificate blocks is ignored +//! whatever its encoding, a leading byte-order mark is skipped, and blocks +//! that are not certificates are skipped. Each certificate must be one a TLS +//! client can trust, and the bundle must hold at least one. + +use rustls::pki_types::CertificateDer; +use rustls::RootCertStore; + +/// The largest CA bundle read: 1 MiB. +pub const MAX_PEM_ROOTS_BYTES: usize = 1024 * 1024; + +/// Why a CA bundle was refused. No variant carries a value from the bundle. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PemRootsError { + /// The bundle is larger than [`MAX_PEM_ROOTS_BYTES`]. + TooLarge, + /// A PEM block, of a certificate or another known kind, is not valid. + InvalidPem, + /// A certificate cannot be used as a trust root. + UnusableCertificate, + /// The bundle holds no certificate. + NoCertificate, +} + +impl PemRootsError { + /// What is wrong, without a value. + #[must_use] + pub const fn message(self) -> &'static str { + match self { + Self::TooLarge => "the CA bundle is larger than 1 MiB", + Self::InvalidPem => "a PEM block in the CA bundle is not valid", + Self::UnusableCertificate => { + "a certificate in the CA bundle cannot be used as a trusted root" + } + Self::NoCertificate => "the CA bundle holds no PEM certificate", + } + } + + /// The fix. + #[must_use] + pub const fn suggested_action(self) -> &'static str { + match self { + Self::TooLarge => "Keep only the roots the database needs, within 1 MiB.", + Self::InvalidPem | Self::UnusableCertificate => { + "Replace the bundle with the database server's root certificates, each as a complete PEM CERTIFICATE block." + } + Self::NoCertificate => { + "Put the database server's root certificates in the bundle as PEM CERTIFICATE blocks." + } + } + } +} + +impl std::fmt::Display for PemRootsError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.message()) + } +} + +impl std::error::Error for PemRootsError {} + +const BYTE_ORDER_MARK: &[u8] = b"\xEF\xBB\xBF"; + +/// Every certificate of a CA bundle, each checked as a trust root. +pub fn pem_roots(pem: &[u8]) -> Result>, PemRootsError> { + Ok(read(pem)?.0) +} + +/// A CA bundle's certificates as the root store of a TLS client. +pub fn pem_root_store(pem: &[u8]) -> Result { + Ok(read(pem)?.1) +} + +/// The certificates and the store they were each checked into, so a +/// certificate a TLS client would refuse is refused here. +fn read(pem: &[u8]) -> Result<(Vec>, RootCertStore), PemRootsError> { + use rustls::pki_types::pem::PemObject as _; + + if pem.len() > MAX_PEM_ROOTS_BYTES { + return Err(PemRootsError::TooLarge); + } + let pem = pem.strip_prefix(BYTE_ORDER_MARK).unwrap_or(pem); + let mut certificates = Vec::new(); + let mut store = RootCertStore::empty(); + for certificate in CertificateDer::pem_slice_iter(pem) { + let certificate = certificate.map_err(|_| PemRootsError::InvalidPem)?; + store + .add(certificate.clone()) + .map_err(|_| PemRootsError::UnusableCertificate)?; + certificates.push(certificate); + } + if certificates.is_empty() { + return Err(PemRootsError::NoCertificate); + } + Ok((certificates, store)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn certificate_pem() -> String { + use base64::Engine as _; + let issued = rcgen::generate_simple_self_signed(vec!["db.example".to_owned()]).unwrap(); + let body = base64::engine::general_purpose::STANDARD.encode(issued.cert.der().as_ref()); + let lines: Vec<_> = body + .as_bytes() + .chunks(64) + .map(|line| std::str::from_utf8(line).unwrap()) + .collect(); + format!( + "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n", + lines.join("\n") + ) + } + + #[test] + fn every_text_shape_of_a_bundle_is_read() { + let first = certificate_pem(); + let second = certificate_pem(); + let bom = [b"\xEF\xBB\xBF".as_slice(), first.as_bytes()].concat(); + let crlf = first.replace('\n', "\r\n"); + let several = format!("issuer comment\n{first}\n{second} \n"); + // Explanatory text outside the blocks in Latin-1, not UTF-8. + let latin1 = [b"Autorit\xE9 racine\n".as_slice(), first.as_bytes()].concat(); + let with_key = + format!("{first}-----BEGIN PUBLIC KEY-----\nMIIB\n-----END PUBLIC KEY-----\n"); + for (name, bundle, count) in [ + ("bom", bom.as_slice(), 1), + ("crlf", crlf.as_bytes(), 1), + ("several", several.as_bytes(), 2), + ("latin1", latin1.as_slice(), 1), + ("other block", with_key.as_bytes(), 1), + ] { + assert_eq!( + pem_roots(bundle).map(|roots| roots.len()), + Ok(count), + "{name}" + ); + assert_eq!( + pem_root_store(bundle).map(|store| store.len()), + Ok(count), + "{name}" + ); + } + } + + #[test] + fn a_bundle_without_a_usable_certificate_is_refused_with_its_reason() { + let unusable = "-----BEGIN CERTIFICATE-----\naGVsbG8=\n-----END CERTIFICATE-----\n"; + let truncated = "-----BEGIN CERTIFICATE-----\nMIIB\n"; + let oversized = vec![b'#'; MAX_PEM_ROOTS_BYTES + 1]; + for (name, bundle, error) in [ + ("empty", b"".as_slice(), PemRootsError::NoCertificate), + ("text", b"not a certificate\n", PemRootsError::NoCertificate), + ("binary", &[0xff, 0xfe, 0xfd], PemRootsError::NoCertificate), + ("truncated", truncated.as_bytes(), PemRootsError::InvalidPem), + ( + "unusable", + unusable.as_bytes(), + PemRootsError::UnusableCertificate, + ), + ("oversized", &oversized, PemRootsError::TooLarge), + ] { + assert_eq!(pem_roots(bundle), Err(error), "{name}"); + assert_eq!(pem_root_store(bundle).err(), Some(error), "{name}"); + assert!(!error.message().is_empty() && !error.suggested_action().is_empty()); + } + } + + #[test] + fn a_malformed_block_of_any_kind_is_named_as_a_pem_block() { + // A truncated PUBLIC KEY block is as malformed as a certificate one. + let bundle = "-----BEGIN PUBLIC KEY-----\nMIIB\n"; + assert_eq!(pem_roots(bundle.as_bytes()), Err(PemRootsError::InvalidPem)); + let message = PemRootsError::InvalidPem.message(); + assert!(message.contains("PEM block"), "{message}"); + assert!(!message.contains("certificate block"), "{message}"); + } +} diff --git a/crates/registry-platform-provision/Cargo.toml b/crates/registry-platform-provision/Cargo.toml index f96cd07c5f..20594e7069 100644 --- a/crates/registry-platform-provision/Cargo.toml +++ b/crates/registry-platform-provision/Cargo.toml @@ -22,7 +22,7 @@ postgres-test = [] # Test helpers for the provision tests of the products that use this crate: # a verified-TLS superuser session and the two PROVISION_TEST_DATABASE_* # variables. Dev-dependencies only, never a runtime build. -test-support = [] +test-support = ["dep:base64", "dep:rcgen"] # The shared `provision` command: clap arguments, the runner and the report. cli = [ @@ -44,8 +44,10 @@ name = "provision-report-schema" required-features = ["schema"] [dependencies] +base64 = { workspace = true, optional = true } clap = { workspace = true, optional = true } postgres-protocol.workspace = true +rcgen = { workspace = true, optional = true } registry-cli-report = { workspace = true, optional = true } registry-platform-activation.workspace = true registry-platform-config.workspace = true diff --git a/crates/registry-platform-provision/README.md b/crates/registry-platform-provision/README.md index 4fd90d6ce8..d8b2c3a630 100644 --- a/crates/registry-platform-provision/README.md +++ b/crates/registry-platform-provision/README.md @@ -32,8 +32,8 @@ name. They open network connections. `admin_config` and `admin_config_with_transport` accept only a `postgres://` or `postgresql://` URL naming one TCP host. By default (`DatabaseTransport::VerifiedTls`) every connection uses TLS verified - against `caBundleRef` or the platform roots (`sslmode=verify-ca` is checked as - `verify-full`). Under `DatabaseTransport::LoopbackPlaintext`, connections use + against `caBundleRef` or the platform roots and checks the hostname. The URL accepts + `sslmode=require` and `sslmode=verify-full`. Under `DatabaseTransport::LoopbackPlaintext`, connections use plaintext to a numeric loopback address or `localhost` resolving only to loopback addresses, with `sslmode` omitted or `disable`, and dial the checked addresses directly. `DatabaseTransport::PrivateNetworkPlaintext` is refused diff --git a/crates/registry-platform-provision/src/admin.rs b/crates/registry-platform-provision/src/admin.rs index 1d092f57da..59dd7fec48 100644 --- a/crates/registry-platform-provision/src/admin.rs +++ b/crates/registry-platform-provision/src/admin.rs @@ -4,10 +4,9 @@ //! Nothing in this module echoes the URL, the password or a driver message //! into an error. Errors name the rule that failed or the SQLSTATE. -use std::{future::Future, str::FromStr, time::Duration}; +use std::{future::Future, time::Duration}; use registry_platform_config::{DatabaseTransport, HostResolver}; -use rustls::pki_types::{pem::PemObject as _, CertificateDer}; use tokio_postgres::{ config::{Host, SslMode}, Client, Config, @@ -53,7 +52,7 @@ pub enum AdminConfigError { #[error("the PostgreSQL admin URL must not override its endpoint or credentials in the query")] QueryOverridesEndpoint, #[error( - "the PostgreSQL admin URL sslmode must be require, verify-ca, or verify-full for \ + "the PostgreSQL admin URL sslmode must be require or verify-full for \ verified-tls, or disable for loopback-plaintext" )] UnsupportedSslMode, @@ -96,6 +95,7 @@ impl AdminConfigError { "platform.provision.admin-ca-invalid" } Self::UnsupportedTransport => "platform.provision.transport-unsupported", + Self::UnsupportedSslMode => "platform.database.unsupported-sslmode", _ => "platform.provision.admin-url-invalid", } } @@ -160,12 +160,12 @@ pub fn admin_config_with_resolver( for (key, value) in parsed.query_pairs() { match key.as_ref() { "sslmode" => match (transport, value.as_ref()) { - (DatabaseTransport::VerifiedTls, "require" | "verify-ca" | "verify-full") => {} + (DatabaseTransport::VerifiedTls, "require" | "verify-full") => {} (DatabaseTransport::VerifiedTls, _) => { return Err(AdminConfigError::UnsupportedSslMode); } (DatabaseTransport::LoopbackPlaintext, "disable") => {} - (DatabaseTransport::LoopbackPlaintext, "require" | "verify-ca" | "verify-full") => { + (DatabaseTransport::LoopbackPlaintext, "require" | "verify-full") => { return Err(AdminConfigError::SslModeDisagreesWithTransport); } (DatabaseTransport::LoopbackPlaintext, _) => { @@ -181,21 +181,23 @@ pub fn admin_config_with_resolver( } } - // tokio-postgres does not parse verify-ca or verify-full, and provisioning - // 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") - .map(|(key, value)| (key.into_owned(), value.into_owned())) - .collect(); - if kept.is_empty() { - sanitized.set_query(None); - } else { - sanitized.query_pairs_mut().clear().extend_pairs(kept); - } - let mut config = - Config::from_str(sanitized.as_str()).map_err(|_| AdminConfigError::InvalidQueryValue)?; + let mut config = registry_platform_postgres::parse_database_url( + parsed.as_str(), + transport == DatabaseTransport::VerifiedTls, + ) + .map_err(|error| { + if matches!( + error, + registry_platform_config::DatabaseTransportError::Url( + registry_platform_config::DatabaseUrlError::Invalid, + _ + ) + ) { + AdminConfigError::InvalidQueryValue + } else { + AdminConfigError::UnsupportedSslMode + } + })?; config.keepalives_idle(KEEPALIVE_IDLE); if config.get_hosts().len() != 1 || !matches!(config.get_hosts().first(), Some(Host::Tcp(_))) @@ -351,18 +353,8 @@ fn tls_connector(ca_pem: Option<&[u8]>) -> Result &'static str { + match error { + SecretError::InvalidReference => "platform.provision.secret-reference-invalid", + SecretError::ProviderDisabled => "platform.provision.secret-provider-disabled", + SecretError::InvalidProviderConfiguration => "platform.provision.secret-providers-invalid", + SecretError::Unavailable => "platform.provision.secret-unavailable", + SecretError::UnsafeFile(_) => "platform.provision.secret-file-unsafe", + SecretError::UnsafePublicDocument(_) => "platform.provision.public-document-unsafe", + SecretError::PrivateKeyInPublicDocument => "platform.provision.public-document-private-key", + SecretError::Read => "platform.provision.secret-unreadable", + SecretError::InvalidValue => "platform.provision.secret-value-invalid", + } +} + +/// A refusal of `block.member`, such as `database.caBundleRef`, at +/// `/block/member`. +#[must_use] +pub fn secret_refusal(block: &str, member: DatabaseMember, error: &SecretError) -> Diagnostic { + Diagnostic::error( + secret_refusal_code(error), + format!("/{block}/{member}"), + describe_secret_reason(&format!("{block}.{member}"), error), + error.suggested_action(), + ) +} + +/// A refusal of a database URL secret, such as `database.runtimeUrlRef`, +/// whose value is not UTF-8 text. It shares the code of a refused value and +/// names the encoding, which the runtime's value rule does not require of a +/// binary secret. +#[must_use] +pub fn url_not_text_refusal(block: &str, member: DatabaseMember) -> Diagnostic { + Diagnostic::error( + secret_refusal_code(&SecretError::InvalidValue), + format!("/{block}/{member}"), + format!("{block}.{member}: the PostgreSQL URL secret is not UTF-8 text"), + "Store the PostgreSQL URL in the secret as UTF-8 text.", + ) +} + +/// The `platform.provision.*` code for a CA bundle with no usable root. +#[must_use] +pub fn ca_bundle_refusal_code(error: PemRootsError) -> &'static str { + match error { + PemRootsError::TooLarge => "platform.provision.ca-bundle-too-large", + PemRootsError::InvalidPem => "platform.provision.ca-bundle-invalid-pem", + PemRootsError::UnusableCertificate => "platform.provision.ca-bundle-unusable-certificate", + PemRootsError::NoCertificate => "platform.provision.ca-bundle-no-certificate", + } +} + +/// A refusal of `block.caBundleRef` whose certificates cannot be trusted. +#[must_use] +pub fn ca_bundle_refusal(block: &str, error: PemRootsError) -> Diagnostic { + let member = DatabaseMember::CaBundle; + Diagnostic::error( + ca_bundle_refusal_code(error), + format!("/{block}/{member}"), + format!("{block}.{member}: {}", error.message()), + error.suggested_action(), + ) +} + +/// Read `block.caBundleRef` and its trust roots as the runtime reads them, so +/// `--print-sql` refuses what apply and the runtime would. +pub fn read_ca_bundle( + secrets: &SecretResolver, + block: &str, + reference: &str, +) -> Result, Box> { + let member = DatabaseMember::CaBundle; + let bundle = member + .read(secrets, reference) + .map_err(|error| Box::new(secret_refusal(block, member, &error)))?; + pem_roots(bundle.expose_secret()).map_err(|error| Box::new(ca_bundle_refusal(block, error)))?; + Ok(bundle.expose_secret().to_vec()) +} + +#[cfg(test)] +mod tests { + use registry_platform_config::SecretFileCheck; + + use super::*; + + const KINDS: [SecretError; 9] = [ + SecretError::InvalidReference, + SecretError::ProviderDisabled, + SecretError::InvalidProviderConfiguration, + SecretError::Unavailable, + SecretError::UnsafeFile(SecretFileCheck::WorldReadable), + SecretError::UnsafePublicDocument(SecretFileCheck::WorldWritable), + SecretError::PrivateKeyInPublicDocument, + SecretError::Read, + SecretError::InvalidValue, + ]; + + #[test] + fn each_kind_has_its_own_provision_code() { + let codes: Vec<_> = KINDS.iter().map(secret_refusal_code).collect(); + assert_eq!( + codes, + [ + "platform.provision.secret-reference-invalid", + "platform.provision.secret-provider-disabled", + "platform.provision.secret-providers-invalid", + "platform.provision.secret-unavailable", + "platform.provision.secret-file-unsafe", + "platform.provision.public-document-unsafe", + "platform.provision.public-document-private-key", + "platform.provision.secret-unreadable", + "platform.provision.secret-value-invalid", + ] + ); + // A secret refusal is not a shared reader problem (CFG-DIAG-3). + assert!(codes.iter().all(|code| !code.starts_with("config."))); + } + + #[test] + fn a_refusal_names_the_member_and_states_its_fix_once() { + for error in KINDS { + let diagnostic = secret_refusal("store", DatabaseMember::CaBundle, &error); + assert_eq!(diagnostic.code, secret_refusal_code(&error)); + assert_eq!(diagnostic.path, "/store/caBundleRef"); + assert!(diagnostic.message.contains("store.caBundleRef")); + assert_eq!(diagnostic.suggested_action, error.suggested_action()); + assert!(!diagnostic.message.contains(error.suggested_action())); + } + } + + #[test] + fn a_ca_bundle_without_a_usable_root_is_refused_at_its_member() { + for (error, code) in [ + ( + PemRootsError::TooLarge, + "platform.provision.ca-bundle-too-large", + ), + ( + PemRootsError::InvalidPem, + "platform.provision.ca-bundle-invalid-pem", + ), + ( + PemRootsError::UnusableCertificate, + "platform.provision.ca-bundle-unusable-certificate", + ), + ( + PemRootsError::NoCertificate, + "platform.provision.ca-bundle-no-certificate", + ), + ] { + assert_eq!(ca_bundle_refusal_code(error), code); + let diagnostic = ca_bundle_refusal("database", error); + assert_eq!(diagnostic.code, code); + assert_eq!(diagnostic.path, "/database/caBundleRef"); + assert!(diagnostic.message.contains("database.caBundleRef")); + assert!(diagnostic.message.contains(error.message())); + assert_eq!(diagnostic.suggested_action, error.suggested_action()); + } + } + + #[cfg(unix)] + #[test] + fn reading_a_ca_bundle_refuses_a_missing_document_and_one_without_a_root() { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir().unwrap(); + let canonical = std::fs::canonicalize(root.path()).unwrap(); + let path = canonical.join("ca"); + std::fs::write(&path, "no certificate here\n").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let secrets = registry_platform_config::SecretProvidersConfig { + file: Some(registry_platform_config::FileSecretProviderConfig::new( + canonical, + )), + environment: None, + } + .resolver(None) + .unwrap(); + + let refused = read_ca_bundle(&secrets, "store", "secret:file/ca").unwrap_err(); + assert_eq!(refused.code, "platform.provision.ca-bundle-no-certificate"); + assert_eq!(refused.path, "/store/caBundleRef"); + let missing = read_ca_bundle(&secrets, "store", "secret:file/absent").unwrap_err(); + assert_eq!(missing.code, "platform.provision.secret-unavailable"); + assert_eq!(missing.path, "/store/caBundleRef"); + } + + #[test] + fn a_url_that_is_not_text_is_a_refused_value_that_names_utf8() { + let diagnostic = url_not_text_refusal("store", DatabaseMember::MigrationUrl); + assert_eq!(diagnostic.code, "platform.provision.secret-value-invalid"); + assert_eq!(diagnostic.path, "/store/migrationUrlRef"); + assert!(diagnostic.message.contains("store.migrationUrlRef")); + assert!( + diagnostic.message.contains("UTF-8"), + "{}", + diagnostic.message + ); + assert!( + diagnostic.suggested_action.contains("UTF-8"), + "{}", + diagnostic.suggested_action + ); + assert!(!diagnostic.message.contains(&diagnostic.suggested_action)); + } +} diff --git a/crates/registry-platform-provision/src/test_support.rs b/crates/registry-platform-provision/src/test_support.rs index f52994d383..9bc8efbf07 100644 --- a/crates/registry-platform-provision/src/test_support.rs +++ b/crates/registry-platform-provision/src/test_support.rs @@ -33,3 +33,23 @@ pub async fn connect_verified(url: &str, ca_pem: &[u8], database: Option<&str>) .await .unwrap_or_else(|error| panic!("cannot open a verified-TLS test session: {error}")) } + +/// A PEM bundle holding one freshly issued self-signed certificate, for a +/// `caBundleRef` that print mode reads and accepts. +#[must_use] +pub fn ca_bundle_pem() -> String { + use base64::Engine as _; + + let issued = rcgen::generate_simple_self_signed(vec!["db.example".to_owned()]) + .expect("a self-signed test certificate"); + let body = base64::engine::general_purpose::STANDARD.encode(issued.cert.der().as_ref()); + let lines: Vec<&str> = body + .as_bytes() + .chunks(64) + .map(|line| std::str::from_utf8(line).expect("base64 is ASCII")) + .collect(); + format!( + "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n", + lines.join("\n") + ) +} diff --git a/crates/registry-render/src/cli.rs b/crates/registry-render/src/cli.rs index c90f7f4505..6ee80a0a0e 100644 --- a/crates/registry-render/src/cli.rs +++ b/crates/registry-render/src/cli.rs @@ -312,7 +312,8 @@ pub enum Command { /// Serve the HTTP rendering API (see the runtime YAML). /// /// Configure OIDC authentication with authentication.oidc, or shared API - /// key authentication with authentication.apiKeyRef for unsigned rendering. + /// key authentication with authentication.apiKeyRef for unsigned rendering + /// in explicit development posture on a loopback listener. /// Sealing requires OIDC. Serve { /// Runtime configuration file. diff --git a/crates/registry-render/src/runtime.rs b/crates/registry-render/src/runtime.rs index 6df7d6ad28..dc3408aff8 100644 --- a/crates/registry-render/src/runtime.rs +++ b/crates/registry-render/src/runtime.rs @@ -340,23 +340,43 @@ fn default_shutdown_grace( #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct AuthenticationRuntime { - /// Secret reference to the shared API key, under a declared provider: one - /// static bearer credential that every request presents. It is supported for a - /// single trusted caller where no OIDC issuer is available. It never seals. - /// Every request carries the same key, so the audit records one fingerprint - /// for all calls and cannot tell callers apart. Omit when OIDC authentication - /// is configured. + /// Secret reference to the shared API key, under a declared provider. + /// Requires explicit development posture and a loopback API listener. + /// Every call shares one bearer credential and one audit fingerprint. + /// Omit when using OIDC, which is required for production and sealing. #[cfg_attr( feature = "schema", - schemars(with = "registry_platform_config::SecretReference") + schemars( + with = "registry_platform_config::SecretReference", + extend("x-registry-development-only" = [RENDER_SHARED_API_KEY.code]) + ) )] #[serde(default, deserialize_with = "present_auth_member")] - pub api_key_ref: Option, + pub api_key_ref: Option>, #[serde(default, deserialize_with = "present_auth_member")] #[cfg_attr(feature = "schema", schemars(with = "OidcRuntime"))] pub oidc: Option, } +#[derive(Debug, Clone, Deserialize)] +#[serde(transparent)] +pub struct SharedApiKeyReference(pub(crate) String); + +static RENDER_SHARED_API_KEY: DevelopmentSetting = DevelopmentSetting { + code: "render.posture.shared-api-key", + key: "apiKeyRef", + summary: "Render accepts a shared bearer key for rendering", + production: "Replace authentication.apiKeyRef with authentication.oidc and configure callers to obtain Render access tokens.", +}; + +impl DevelopmentClass for SharedApiKeyReference { + const SETTINGS: &'static [&'static DevelopmentSetting] = &[&RENDER_SHARED_API_KEY]; + + fn development_setting(&self) -> Option<&'static DevelopmentSetting> { + Some(&RENDER_SHARED_API_KEY) + } +} + fn present_auth_member<'de, D, T>(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, @@ -838,14 +858,14 @@ pub enum AssuranceProfile { static RENDER_LOCAL_ASSURANCE: DevelopmentSetting = DevelopmentSetting { code: "render.posture.local-assurance", key: "assuranceProfile", - summary: "seals use a local key file and are marked as test seals", + summary: "Seals use a local key file and are marked as test seals", production: "Configure assuranceProfile: production and sign through Transit.", }; static RENDER_SEALS_NOT_SERVED: DevelopmentSetting = DevelopmentSetting { code: "render.posture.seals-not-served", key: "signing", - summary: "the bundle declares seals, but this runtime has no signing block and renders those document types unsealed", + summary: "The bundle declares seals, but this runtime has no signing block and renders those document types unsealed", production: "Configure signing.seals for the bundle's seals, or deploy a bundle whose documents do not declare seals.", }; @@ -1088,14 +1108,21 @@ pub fn load_with_positions( declared: DeclaredPosture, ) -> Result<(LoadedRuntimeConfig, RuntimePositions), RenderProblem> { let (loaded, positions) = load_before_posture_decision(path, declared)?; - loaded.posture.decide(path).map_err(|error| { + decide_runtime_posture(&loaded.posture, path)?; + Ok((loaded, positions)) +} + +pub(crate) fn decide_runtime_posture( + posture: &PostureReport, + path: &Path, +) -> Result<(), RenderProblem> { + posture.decide(path).map_err(|error| { RenderProblem::new( ProblemKind::RuntimeInvalid, "the runtime configuration was refused", ) .with_diagnostics(error.diagnostics().to_vec()) - })?; - Ok((loaded, positions)) + }) } /// Load the runtime's structure before evaluating its posture with its package. @@ -1185,6 +1212,9 @@ fn read_runtime( declared.posture, check.defers("/listener/bind"), check.defers("/metricsListener/networkExposure"), + check + .authored_scalar("/authentication/apiKeyRef") + .map(|(reference, _)| reference), ) { let audit_deferred = finding.pointer.starts_with("/audit") && check.defers("/audit/destination"); @@ -1462,6 +1492,7 @@ fn findings( posture: Posture, listener_deferred: bool, metrics_exposure_deferred: bool, + authored_key_ref: Option<&str>, ) -> Vec { let mut findings = Vec::new(); if !runtime.listener.bind_allowed() { @@ -1537,10 +1568,27 @@ fn findings( } } } - (None, Some(api_key_ref)) => { - if let Err(error) = runtime.secret_providers.check_reference("authentication.apiKeyRef", api_key_ref) { findings.push(block_finding(&error)); } + (None, Some(_)) => { + if !listener_deferred + && runtime.listener.bind_allowed() + && !runtime.listener.bind.socket_addr().ip().is_loopback() + { + findings.push(Finding { + code: "render.runtime.shared-key-requires-loopback", + pointer: "/listener/bind".to_owned(), + message: "The shared API key requires a loopback listener.".to_owned(), + action: "Bind the API listener to 127.0.0.1 or ::1, or configure authentication.oidc.".to_owned(), + }); + } + // The authored reference can be checked without unlocking the gated value. + // Secret references never accept substitutions. + if let Some(reference) = authored_key_ref { + if let Err(error) = runtime.secret_providers.check_reference("authentication.apiKeyRef", reference) { + findings.push(block_finding(&error)); + } + } } - _ => findings.push(Finding { code: "render.runtime.authentication", pointer: "/authentication".to_owned(), message: "authentication must configure exactly one of oidc or apiKeyRef".to_owned(), action: "Configure authentication.oidc for the Render resource, or one shared API key in apiKeyRef; remove the other mode.".to_owned() }), + _ => findings.push(Finding { code: "render.runtime.authentication", pointer: "/authentication".to_owned(), message: "authentication must configure exactly one of oidc or apiKeyRef".to_owned(), action: "Configure authentication.oidc for the Render resource. For explicit loopback development, you can configure only authentication.apiKeyRef.".to_owned() }), } if let Err(error) = runtime.audit.settings() { findings.push(audit_finding(&error)); @@ -2314,14 +2362,17 @@ mod tests { source: PostureSource::Flag, }; - fn load_text(home: &Path, text: &str) -> Result { + fn load_development_text(home: &Path, text: &str) -> Result { + load_text(home, text, DEVELOPMENT_POSTURE) + } + + fn load_text( + home: &Path, + text: &str, + declared: DeclaredPosture, + ) -> Result { let file = home.join("runtime.yaml"); std::fs::write(&file, text).expect("runtime file"); - let declared = if text.lines().any(|line| line == "assuranceProfile: local") { - DEVELOPMENT_POSTURE - } else { - DEFAULT_POSTURE - }; load_with_positions(&file, declared).map(|(loaded, _)| loaded.config) } @@ -2335,8 +2386,16 @@ mod tests { .collect() } - fn refused(home: &Path, text: &str) -> RenderProblem { - let problem = load_text(home, text).expect_err("the runtime file is refused"); + fn first_error(problem: &RenderProblem) -> &Diagnostic { + problem + .diagnostics + .iter() + .find(|finding| finding.severity == Severity::Error) + .expect("one refusing diagnostic") + } + + fn refused(home: &Path, text: &str, declared: DeclaredPosture) -> RenderProblem { + let problem = load_text(home, text, declared).expect_err("the runtime file is refused"); assert_eq!(problem.kind, ProblemKind::RuntimeInvalid); problem } @@ -2362,7 +2421,8 @@ mod tests { std::fs::write(&path, minimal(&home)).unwrap(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); - load(&path).expect("an owner-writable runtime in a private directory loads"); + load_with_positions(&path, DEVELOPMENT_POSTURE) + .expect("an owner-writable runtime in a private directory loads"); } #[cfg(unix)] @@ -2404,7 +2464,9 @@ mod tests { let (_dir, home) = home(); let file = home.join("runtime.yaml"); std::fs::write(&file, minimal(&home)).expect("runtime file"); - let (runtime, digest) = load(&file).expect("the minimal runtime loads"); + let (loaded, _) = + load_with_positions(&file, DEVELOPMENT_POSTURE).expect("the minimal runtime loads"); + let (runtime, digest) = (loaded.config, loaded.effective_digest); assert_eq!(runtime.listener.bind.socket_addr().port(), 8080); assert_eq!(runtime.package.root, PathBuf::from("/srv/render/package")); assert!( @@ -2418,6 +2480,7 @@ mod tests { "apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1", "apiVersion: render.registrystack.org/v1alpha1", ), + DEFAULT_POSTURE, ); assert_eq!( codes(&problem), @@ -2434,12 +2497,13 @@ mod tests { "apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1", "apiVersion: registry.registrystack.org/render-runtime/v1alpha1", ), + DEFAULT_POSTURE, ); assert_eq!( codes(&problem), [("config.retired-api-version", "/apiVersion")] ); - let action = &problem.diagnostics[0].suggested_action; + let action = &first_error(&problem).suggested_action; for rename in [ "id.registrystack.org/formats/render/runtime/v1alpha1", "listener.shutdownGraceMilliseconds", @@ -2456,10 +2520,10 @@ mod tests { fn the_listener_bind_is_required() { let (_dir, home) = home(); let text = minimal(&home).replace("listener:\n bind: 127.0.0.1:8080\n", ""); - let problem = refused(&home, &text); - assert_eq!(problem.diagnostics[0].code, "config.missing-key"); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); + assert_eq!(first_error(&problem).code, "config.missing-key"); assert!( - problem.diagnostics[0].message.contains("listener"), + first_error(&problem).message.contains("listener"), "{:?}", problem.diagnostics ); @@ -2535,7 +2599,7 @@ mod tests { "Rename `auth` to `authentication`", ), ] { - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEFAULT_POSTURE); let removed = problem .diagnostics .iter() @@ -2566,7 +2630,10 @@ mod tests { ("render.runtime.invalid-audit-path", "/audit/path"), ), ] { - assert_eq!(codes(&refused(&home, &text)), [expected]); + assert_eq!( + codes(&refused(&home, &text, DEVELOPMENT_POSTURE)), + [expected] + ); } } @@ -2586,7 +2653,7 @@ mod tests { ), &format!("secretProviders:\n {member}:\n"), ); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEFAULT_POSTURE); assert!( codes(&problem).contains(&("config.null-value", pointer)), "{member}: {:?}", @@ -2602,7 +2669,7 @@ mod tests { "apiKeyRef: secret:file/api.key", "apiKeyRef: secret:env/RENDER_API_KEY", ); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [( @@ -2611,18 +2678,19 @@ mod tests { )] ); assert!( - problem.diagnostics[0] + first_error(&problem) .message .contains("secretProviders.environment"), "{}", - problem.diagnostics[0].message + first_error(&problem).message ); let text = text.replace( "secretProviders:\n", "secretProviders:\n environment: {}\n", ); - load_text(&home, &text).expect("the declared environment provider admits the reference"); + load_development_text(&home, &text) + .expect("the declared environment provider admits the reference"); let text = minimal(&home).replace( &format!( @@ -2631,7 +2699,7 @@ mod tests { ), "secretProviders: {}\n", ); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [ @@ -2656,15 +2724,17 @@ mod tests { ), ) .expect("runtime file"); - let (runtime, _) = load(&file).expect("a defaulted expression loads"); + let (loaded, _) = + load_with_positions(&file, DEVELOPMENT_POSTURE).expect("a defaulted expression loads"); + let runtime = loaded.config; assert_eq!(runtime.package.root, PathBuf::from("/srv/render/default")); let text = minimal(&home).replace( "apiKeyRef: secret:file/api.key", "apiKeyRef: ${RENDER_API_KEY_REF:-secret:file/api.key}", ); - let problem = refused(&home, &text); - assert_eq!(problem.diagnostics[0].path, "/authentication/apiKeyRef"); + let problem = refused(&home, &text, DEFAULT_POSTURE); + assert_eq!(first_error(&problem).path, "/authentication/apiKeyRef"); } #[test] @@ -2675,7 +2745,10 @@ mod tests { write_secret(&secrets.join("api.key"), b"from-the-declared-root"); // A file beside the runtime file is not a secret root. write_secret(&home.join("audit.key"), b"beside-the-runtime-file"); - let runtime = load_text(&home, &minimal(&home)).expect("runtime loads"); + let file = home.join("runtime.yaml"); + std::fs::write(&file, minimal(&home)).unwrap(); + let (loaded, _) = load_with_positions(&file, DEVELOPMENT_POSTURE).unwrap(); + let runtime = loaded.config; assert_eq!( resolve_secret( &runtime, @@ -2683,8 +2756,11 @@ mod tests { runtime .authentication .api_key_ref - .as_deref() + .as_ref() .expect("key mode") + .get(loaded.development.as_ref()) + .map(|reference| reference.0.as_str()) + .unwrap() ) .expect("declared root"), b"from-the-declared-root" @@ -2700,7 +2776,7 @@ mod tests { #[test] fn the_audit_block_takes_the_shared_destination_shape() { let (_dir, home) = home(); - let file = load_text( + let file = load_development_text( &home, &with_audit( &home, @@ -2718,7 +2794,7 @@ mod tests { panic!("file is the default destination") } } - let stdout = load_text(&home, &with_audit(&home, " destination: stdout\n")) + let stdout = load_development_text(&home, &with_audit(&home, " destination: stdout\n")) .expect("a stdout destination loads"); assert_eq!( stdout.audit.destination().expect("destination"), @@ -2771,16 +2847,17 @@ mod tests { "/audit/path", ), ] { - let problem = refused(&home, &with_audit(&home, audit)); + let problem = refused(&home, &with_audit(&home, audit), DEVELOPMENT_POSTURE); assert_eq!(codes(&problem), [(code, pointer)], "{audit}"); } // The message names the member as this file spells it. let problem = refused( &home, &with_audit(&home, " destination: stdout\n retentionDays: 7\n"), + DEVELOPMENT_POSTURE, ); assert_eq!( - problem.diagnostics[0].message, + first_error(&problem).message, "audit.retentionDays applies only when audit.destination is file" ); } @@ -2795,17 +2872,19 @@ mod tests { #[test] fn container_private_exposure_is_explicit_and_still_refuses_public_addresses() { let (_dir, home) = home(); - let text = minimal(&home).replace( - "bind: 127.0.0.1:8080", - "bind: 0.0.0.0:8080\n networkExposure: container-private", - ); + let text = minimal(&home) + .replace("apiKeyRef: secret:file/api.key", OIDC_ONE_ISSUER) + .replace( + "bind: 127.0.0.1:8080", + "bind: 0.0.0.0:8080\n networkExposure: container-private", + ); assert!( - load_text(&home, &text).is_ok(), + load_text(&home, &text, DEFAULT_POSTURE).is_ok(), "container-private wildcard must load" ); let public = text.replace("0.0.0.0:8080", "203.0.113.9:8080"); assert!( - load_text(&home, &public).is_err(), + load_text(&home, &public, DEFAULT_POSTURE).is_err(), "public address stays refused" ); } @@ -2816,7 +2895,7 @@ mod tests { let oidc = OIDC_ONE_ISSUER; let text = minimal(&home).replace("apiKeyRef: secret:file/api.key", oidc); assert!( - load_text(&home, &text).is_ok(), + load_text(&home, &text, DEFAULT_POSTURE).is_ok(), "OIDC runtime loads without caller API key" ); let both = text.replace( @@ -2824,10 +2903,10 @@ mod tests { "authentication:\n apiKeyRef: secret:file/api.key\n", ); assert!( - load_text(&home, &both).is_err(), + load_development_text(&home, &both).is_err(), "no ambiguous authentication fallback" ); - assert!(load_text( + assert!(load_development_text( &home, &minimal(&home).replace("apiKeyRef: secret:file/api.key", "{}") ) @@ -2852,8 +2931,8 @@ mod tests { "" ), ); - let runtime = - load_text(&home, &with_issuers(&home, &entries, "")).expect("two issuers load"); + let runtime = load_text(&home, &with_issuers(&home, &entries, ""), DEFAULT_POSTURE) + .expect("two issuers load"); let oidc = runtime.authentication.oidc.expect("oidc authentication"); let ids: Vec<&str> = oidc.issuers.iter().map(|(id, _)| id.as_str()).collect(); assert_eq!(ids, ["partners", "staff"]); @@ -2864,7 +2943,7 @@ mod tests { let (_dir, home) = home(); let old = "oidc:\n issuer: https://issuer.example.test\n audience: https://render.example.test\n allowInsecureHttp: false\n jwksSource:\n type: discovery\n allowedClients: [portal]\n assertionIssuers:\n portal: [https://assertion.example.test]"; let text = minimal(&home).replace("apiKeyRef: secret:file/api.key", old); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEFAULT_POSTURE); let mut removed: Vec<&str> = problem .diagnostics .iter() @@ -2953,7 +3032,7 @@ mod tests { &issuer_entry("main", "https://issuer.example.test", "[portal]", &writes), "", ); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEFAULT_POSTURE); assert!( codes(&problem) .iter() @@ -2972,7 +3051,7 @@ mod tests { ), "", ); - let runtime = load_text(&home, &listed).expect("a listed authority loads"); + let runtime = load_text(&home, &listed, DEFAULT_POSTURE).expect("a listed authority loads"); let oidc = runtime.authentication.oidc.expect("oidc"); let (_, entry) = oidc.issuers.iter().next().expect("one entry"); assert_eq!( @@ -3171,7 +3250,7 @@ mod tests { issuer_entry("beta", "https://id.example.test", "[batch]", ""), ); let text = with_issuers(&home, &entries, ""); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEFAULT_POSTURE); let duplicate = problem .diagnostics .iter() @@ -3190,7 +3269,7 @@ mod tests { issuer_entry("alpha", "https://id.example.test", "[portal]", ""), issuer_entry("beta", "https://login.partner.example", "[portal]", ""), ); - let problem = refused(&home, &with_issuers(&home, &entries, "")); + let problem = refused(&home, &with_issuers(&home, &entries, ""), DEFAULT_POSTURE); assert!( codes(&problem).contains(&( "platform.oidc.client-in-two-issuers", @@ -3231,7 +3310,8 @@ mod tests { #[test] fn absent_scope_settings_read_the_two_defaults() { let (_dir, home) = home(); - let runtime = load_text(&home, &with_issuers(&home, MAIN_ENTRY, "")).expect("loads"); + let runtime = + load_text(&home, &with_issuers(&home, MAIN_ENTRY, ""), DEFAULT_POSTURE).expect("loads"); let oidc = runtime.authentication.oidc.expect("oidc authentication"); assert_eq!(oidc.render_scope().as_str(), "render:render"); assert_eq!(oidc.seal_scope().as_str(), "render:seal"); @@ -3241,7 +3321,12 @@ mod tests { fn configured_scope_names_are_read_beside_the_issuers() { let (_dir, home) = home(); let siblings = " renderScope: documents:render\n sealScope: documents:seal\n"; - let runtime = load_text(&home, &with_issuers(&home, MAIN_ENTRY, siblings)).expect("loads"); + let runtime = load_text( + &home, + &with_issuers(&home, MAIN_ENTRY, siblings), + DEFAULT_POSTURE, + ) + .expect("loads"); let oidc = runtime.authentication.oidc.expect("oidc authentication"); assert_eq!(oidc.render_scope().as_str(), "documents:render"); assert_eq!(oidc.seal_scope().as_str(), "documents:seal"); @@ -3256,7 +3341,10 @@ mod tests { " sealScope: \"seal\\tdocuments\"\n", ] { let text = with_issuers(&home, MAIN_ENTRY, siblings); - assert!(load_text(&home, &text).is_err(), "{siblings}"); + assert!( + load_text(&home, &text, DEFAULT_POSTURE).is_err(), + "{siblings}" + ); } } @@ -3267,7 +3355,7 @@ mod tests { let (_dir, home) = home(); let oidc = OIDC_ONE_ISSUER; let text = minimal(&home).replace("apiKeyRef: secret:file/api.key", oidc); - assert!(load_text(&home, &text).is_ok()); + assert!(load_text(&home, &text, DEFAULT_POSTURE).is_ok()); for extra in [" apiKeyRef: null\n", " oidc: null\n"] { let base = if extra.contains("oidc") { minimal(&home) @@ -3275,7 +3363,7 @@ mod tests { text.clone() }; assert!( - load_text( + load_development_text( &home, &base.replace("authentication:\n", &format!("authentication:\n{extra}")) ) @@ -3292,7 +3380,7 @@ mod tests { "fixture must replace the declared file root" ); assert!( - load_text(&home, &relative).is_err(), + load_text(&home, &relative, DEFAULT_POSTURE).is_err(), "unused declared provider is still validated" ); } @@ -3327,8 +3415,11 @@ mod tests { "169.254.10.4:9090", "[fe80::1]:9090", ] { - let text = format!("{}metricsListener:\n bind: \"{bind}\"\n", minimal(&home)); - let problem = refused(&home, &text); + let text = format!( + "{}metricsListener:\n bind: \"{bind}\"\n", + with_issuers(&home, MAIN_ENTRY, "") + ); + let problem = refused(&home, &text, DEFAULT_POSTURE); assert_eq!( codes(&problem), [( @@ -3338,15 +3429,17 @@ mod tests { "{bind}" ); // CFG-SEC-3: the finding names the member, never its value. - assert!(!problem.diagnostics[0].message.contains(bind), "{bind}"); + assert!(!first_error(&problem).message.contains(bind), "{bind}"); } let text = format!( "{}metricsListener:\n bind: 127.0.0.1:9108\n", - minimal(&home) + with_issuers(&home, MAIN_ENTRY, "") ); - let runtime = load_text(&home, &text).expect("a private metrics listener is accepted"); + let runtime = load_text(&home, &text, DEFAULT_POSTURE) + .expect("a private metrics listener is accepted"); assert!(runtime.metrics_listener.is_some()); - let runtime = load_text(&home, &minimal(&home)).expect("no metrics listener"); + let runtime = load_text(&home, &with_issuers(&home, MAIN_ENTRY, ""), DEFAULT_POSTURE) + .expect("no metrics listener"); assert!(runtime.metrics_listener.is_none()); } @@ -3356,12 +3449,13 @@ mod tests { let problem = refused( &home, &minimal(&home).replace("bind: 127.0.0.1:8080", "bind: 0.0.0.0:8080"), + DEVELOPMENT_POSTURE, ); assert_eq!( codes(&problem), [("render.runtime.public-bind", "/listener/bind")] ); - let diagnostic = &problem.diagnostics[0]; + let diagnostic = first_error(&problem); let source = diagnostic.source.as_ref().expect("positioned"); assert_eq!((source.line, source.column), (Some(4), Some(9))); // CFG-SEC-3: the finding names the member, never its value. @@ -3384,7 +3478,7 @@ mod tests { &format!(" bind: 127.0.0.1:8080\n shutdownGraceMilliseconds: {grace}\n"), ); assert_eq!( - codes(&refused(&home, &text)), + codes(&refused(&home, &text, DEVELOPMENT_POSTURE)), [("config.out-of-range", "/listener/shutdownGraceMilliseconds")], "grace {grace}" ); @@ -3399,13 +3493,14 @@ mod tests { " bind: 127.0.0.1:8080\n", &format!(" bind: 127.0.0.1:8080\n shutdownGraceMilliseconds: {grace}\n"), ); - let runtime = load_text(&home, &text).expect("grace at the range end loads"); + let runtime = + load_development_text(&home, &text).expect("grace at the range end loads"); assert_eq!( runtime.listener.shutdown_grace(), Duration::from_millis(grace) ); } - let runtime = load_text(&home, &minimal(&home)).expect("runtime loads"); + let runtime = load_development_text(&home, &minimal(&home)).expect("runtime loads"); assert_eq!(runtime.listener.shutdown_grace(), Duration::from_secs(30)); } @@ -3422,19 +3517,22 @@ mod tests { ("maximumConcurrentRenders", "0"), ("maximumConcurrentRenders", "65"), ] { - let text = format!("{}limits:\n {limit}: {value}\n", minimal(&home)); + let text = format!( + "{}limits:\n {limit}: {value}\n", + with_issuers(&home, MAIN_ENTRY, "") + ); let pointer = format!("/limits/{limit}"); assert_eq!( - codes(&refused(&home, &text)), + codes(&refused(&home, &text, DEFAULT_POSTURE)), [("config.out-of-range", pointer.as_str())], "{limit} {value}" ); } let text = format!( "{}limits:\n renderTimeoutSeconds: 3600\n maximumOutputBytes: 8388608\n maximumRequestBytes: 67108864\n maximumConcurrentRenders: 64\n", - minimal(&home) + with_issuers(&home, MAIN_ENTRY, "") ); - let limits = load_text(&home, &text) + let limits = load_text(&home, &text, DEFAULT_POSTURE) .expect("limits at their maximum load") .limits; assert_eq!(limits.render_timeout(), Duration::from_secs(3600)); @@ -3446,7 +3544,7 @@ mod tests { #[test] fn omitted_limits_take_their_defaults() { let (_dir, home) = home(); - let limits = load_text(&home, &minimal(&home)) + let limits = load_text(&home, &with_issuers(&home, MAIN_ENTRY, ""), DEFAULT_POSTURE) .expect("runtime loads") .limits; assert_eq!(limits.render_timeout(), Duration::from_secs(20)); @@ -3472,7 +3570,7 @@ mod tests { " path: /var/lib/render/audit/render.jsonl\n", " destination: file\n", ); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [ @@ -3502,7 +3600,7 @@ mod tests { "{human}" ); assert!( - human.ends_with("4 errors, 0 warnings in 1 file\n"), + human.ends_with("4 errors, 1 warning in 1 file\n"), "{human}" ); } @@ -3514,6 +3612,7 @@ mod tests { std::fs::write( &file, minimal(&home) + .replace("apiKeyRef: secret:file/api.key", OIDC_ONE_ISSUER) .replace("127.0.0.1:8080", "\"${RENDER_CHECK_UNSET_BIND}\"") .replace( "/var/lib/render/audit/render.jsonl", @@ -3542,13 +3641,17 @@ mod tests { let (_dir, home) = home(); let declared = format!( "{}metricsListener:\n bind: 0.0.0.0:9090\n networkExposure: container-private\n", - minimal(&home) + with_issuers(&home, MAIN_ENTRY, "") ); - let runtime = load_text(&home, &declared).expect("container-private permits the wildcard"); + let runtime = load_text(&home, &declared, DEFAULT_POSTURE) + .expect("container-private permits the wildcard"); assert!(runtime.metrics_listener_allowed()); - let undeclared = format!("{}metricsListener:\n bind: 0.0.0.0:9090\n", minimal(&home)); + let undeclared = format!( + "{}metricsListener:\n bind: 0.0.0.0:9090\n", + with_issuers(&home, MAIN_ENTRY, "") + ); assert_eq!( - codes(&refused(&home, &undeclared)), + codes(&refused(&home, &undeclared, DEFAULT_POSTURE)), [( "render.runtime.invalid-metrics-listener", "/metricsListener/bind" @@ -3557,10 +3660,10 @@ mod tests { for bind in ["203.0.113.4:9090", "169.254.10.4:9090", "0.0.0.0:8080"] { let text = format!( "{}metricsListener:\n bind: \"{bind}\"\n networkExposure: container-private\n", - minimal(&home) + with_issuers(&home, MAIN_ENTRY, "") ); assert_eq!( - codes(&refused(&home, &text)), + codes(&refused(&home, &text, DEFAULT_POSTURE)), [( "render.runtime.invalid-metrics-listener", "/metricsListener/bind" @@ -3574,9 +3677,12 @@ mod tests { fn a_metrics_refusal_names_its_cause_and_remedy() { let (_dir, home) = home(); let refusal = |bind: &str| { - let text = format!("{}metricsListener:\n bind: \"{bind}\"\n", minimal(&home)); - let problem = refused(&home, &text); - let diagnostic = problem.diagnostics[0].clone(); + let text = format!( + "{}metricsListener:\n bind: \"{bind}\"\n", + with_issuers(&home, MAIN_ENTRY, "") + ); + let problem = refused(&home, &text, DEFAULT_POSTURE); + let diagnostic = first_error(&problem).clone(); (diagnostic.message, diagnostic.suggested_action) }; let (message, action) = refusal("203.0.113.4:9090"); @@ -3600,9 +3706,10 @@ mod tests { // The serving path states the same cause and remedy. let text = format!( "{}metricsListener:\n bind: 127.0.0.1:9090\n", - minimal(&home) + with_issuers(&home, MAIN_ENTRY, "") ); - let runtime = load_text(&home, &text).expect("a private metrics bind loads"); + let runtime = + load_text(&home, &text, DEFAULT_POSTURE).expect("a private metrics bind loads"); assert_eq!(runtime.check_metrics_listener(), Ok(())); } @@ -3614,7 +3721,7 @@ mod tests { &file, format!( "{}metricsListener:\n bind: 0.0.0.0:9464\n networkExposure: \"${{RENDER_CHECK_UNSET_EXPOSURE}}\"\n", - minimal(&home) + minimal(&home).replace("apiKeyRef: secret:file/api.key", OIDC_ONE_ISSUER) ), ) .expect("runtime file"); @@ -3630,7 +3737,9 @@ mod tests { &file, format!( "{}metricsListener:\n bind: 127.0.0.1:8080\n", - minimal(&home).replace("127.0.0.1:8080", "\"${RENDER_CHECK_UNSET_BIND}\"") + minimal(&home) + .replace("apiKeyRef: secret:file/api.key", OIDC_ONE_ISSUER) + .replace("127.0.0.1:8080", "\"${RENDER_CHECK_UNSET_BIND}\"") ), ) .expect("runtime file"); @@ -3647,7 +3756,9 @@ mod tests { &file, format!( "{}metricsListener:\n bind: \"{bind}\"\n", - minimal(&home).replace("127.0.0.1:8080", "\"${RENDER_CHECK_UNSET_BIND}\"") + minimal(&home) + .replace("apiKeyRef: secret:file/api.key", OIDC_ONE_ISSUER) + .replace("127.0.0.1:8080", "\"${RENDER_CHECK_UNSET_BIND}\"") ), ) .expect("runtime file"); @@ -3731,7 +3842,8 @@ mod tests { #[test] fn a_signing_block_loads_with_its_defaults_and_accessors() { let (_dir, home) = home(); - let runtime = load_text(&home, &signing_text(&home, SEAL)).expect("signing loads"); + let runtime = + load_development_text(&home, &signing_text(&home, SEAL)).expect("signing loads"); let seal = runtime.seal("ministry").expect("the seal is bound"); assert_eq!( seal.signer, @@ -3756,8 +3868,8 @@ mod tests { #[test] fn a_production_seal_loads_its_transit_signer() { let (_dir, home) = home(); - let runtime = - load_text(&home, &signing_text(&home, TRANSIT_SEAL)).expect("a transit seal loads"); + let runtime = load_text(&home, &signing_text(&home, TRANSIT_SEAL), DEFAULT_POSTURE) + .expect("a transit seal loads"); let seal = runtime.seal("ministry").expect("the seal is bound"); assert_eq!( runtime.assurance_profile(None).unwrap(), @@ -3811,7 +3923,7 @@ mod tests { "", ); let text = with_issuers(&home, &issuers, "") + "assuranceProfile:" + seal_part; - let runtime = load_text(&home, &text).expect("the documented seal loads"); + let runtime = load_text(&home, &text, DEFAULT_POSTURE).expect("the documented seal loads"); let seal = runtime.seal("ministry").expect("the seal is bound"); assert_eq!( runtime.assurance_profile(None).unwrap(), @@ -3828,7 +3940,8 @@ mod tests { fn a_production_runtime_never_signs_with_a_key_file() { let (_dir, home) = home(); let text = signing_text_under(&home, Some("production"), SEAL); - let problem = refused(&home, &text); + let problem = + load_text(&home, &text, DEFAULT_POSTURE).expect_err("production refuses a local key"); assert_eq!( codes(&problem), [( @@ -3836,7 +3949,7 @@ mod tests { "/signing/seals/ministry/signer/type" )] ); - let diagnostic = &problem.diagnostics[0]; + let diagnostic = first_error(&problem); assert!( diagnostic.message.contains("assuranceProfile: production"), "{}", @@ -3862,7 +3975,7 @@ mod tests { fn a_local_runtime_never_signs_through_transit() { let (_dir, home) = home(); let text = signing_text_under(&home, Some("local"), TRANSIT_SEAL); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [( @@ -3912,7 +4025,11 @@ mod tests { fn a_mismatch_is_refused_per_seal() { let (_dir, home) = home(); let seals = format!("{SEAL}{}", TRANSIT_SEAL.replace("ministry", "spare")); - let problem = refused(&home, &signing_text_under(&home, Some("local"), &seals)); + let problem = refused( + &home, + &signing_text_under(&home, Some("local"), &seals), + DEVELOPMENT_POSTURE, + ); assert_eq!( codes(&problem), [( @@ -3926,12 +4043,16 @@ mod tests { fn seals_need_an_assurance_profile() { let (_dir, home) = home(); for seal in [SEAL, TRANSIT_SEAL] { - let problem = refused(&home, &signing_text_under(&home, None, seal)); + let problem = refused( + &home, + &signing_text_under(&home, None, seal), + DEFAULT_POSTURE, + ); assert_eq!(codes(&problem), [("config.missing-key", "")], "{seal}"); assert!( - problem.diagnostics[0].message.contains("assuranceProfile"), + first_error(&problem).message.contains("assuranceProfile"), "{}", - problem.diagnostics[0].message + first_error(&problem).message ); } } @@ -3939,7 +4060,8 @@ mod tests { #[test] fn a_runtime_without_seals_needs_no_assurance_profile() { let (_dir, home) = home(); - let runtime = load_text(&home, &minimal(&home)).expect("a runtime without seals loads"); + let runtime = + load_development_text(&home, &minimal(&home)).expect("a runtime without seals loads"); assert!(runtime.assurance_profile.is_none()); assert!(runtime.signing.is_none()); } @@ -3948,7 +4070,7 @@ mod tests { fn a_per_seal_trust_member_is_refused() { let (_dir, home) = home(); let seal = format!("{SEAL} trust: test-only\n"); - let problem = refused(&home, &signing_text(&home, &seal)); + let problem = refused(&home, &signing_text(&home, &seal), DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [("config.unknown-key", "/signing/seals/ministry/trust")] @@ -3961,6 +4083,7 @@ mod tests { let problem = refused( &home, &signing_text_under(&home, Some("evidence-grade"), SEAL), + DEFAULT_POSTURE, ); assert_eq!( codes(&problem), @@ -3979,7 +4102,7 @@ mod tests { "secretProviders:\n", "secretProviders:\n environment: {}\n", ); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [( @@ -4035,7 +4158,7 @@ mod tests { ), ]; for (seals, pointer) in cases { - let problem = refused(&home, &signing_text(&home, &seals)); + let problem = refused(&home, &signing_text(&home, &seals), DEVELOPMENT_POSTURE); assert!( problem .diagnostics @@ -4050,7 +4173,7 @@ mod tests { #[test] fn without_a_signing_block_sealing_is_off() { let (_dir, home) = home(); - let runtime = load_text(&home, &minimal(&home)).expect("runtime loads"); + let runtime = load_development_text(&home, &minimal(&home)).expect("runtime loads"); assert!(runtime.signing.is_none()); assert!(runtime.seal("ministry").is_none()); let manifest = signing_manifest(&[("licence", Some("ministry"))]); @@ -4247,7 +4370,7 @@ mod tests { ), ]; for (seal, code, pointer) in cases { - let problem = refused(&home, &signing_text(&home, &seal)); + let problem = refused(&home, &signing_text(&home, &seal), DEVELOPMENT_POSTURE); assert!( codes(&problem).contains(&(code, pointer)), "{code} {pointer}: {:?}\n{seal}", @@ -4270,7 +4393,7 @@ mod tests { "https://tsa.example.test/tsr", ] { let seal = SEAL.replace("https://tsa.example.test/tsr", url); - load_text(&home, &signing_text(&home, &seal)).unwrap_or_else(|problem| { + load_development_text(&home, &signing_text(&home, &seal)).unwrap_or_else(|problem| { panic!("{url}: {:?}", codes(&problem)); }); } @@ -4282,7 +4405,7 @@ mod tests { "http://[::ffff:10.0.0.5]/tsr", ] { let seal = SEAL.replace("https://tsa.example.test/tsr", url); - let problem = refused(&home, &signing_text(&home, &seal)); + let problem = refused(&home, &signing_text(&home, &seal), DEVELOPMENT_POSTURE); assert_eq!( codes(&problem), [( @@ -4304,7 +4427,8 @@ mod tests { "https://tsa.example.test/tsr\n attemptTimeoutMilliseconds: {ms}\n" ), ); - let runtime = load_text(&home, &signing_text(&home, &seal)).expect("bound accepted"); + let runtime = + load_development_text(&home, &signing_text(&home, &seal)).expect("bound accepted"); let authority = runtime .seal("ministry") .unwrap() @@ -4317,7 +4441,8 @@ mod tests { " timestampAuthority:\n url: https://tsa.example.test/tsr\n", " withoutTimestamp: seal-stops-validating-when-certificate-expires\n", ); - let runtime = load_text(&home, &signing_text(&home, &without)).expect("B-B is allowed"); + let runtime = + load_development_text(&home, &signing_text(&home, &without)).expect("B-B is allowed"); let seal = runtime.seal("ministry").unwrap(); assert!(seal.timestamp_authority.is_none()); assert_eq!( @@ -4327,7 +4452,7 @@ mod tests { // A boolean or any other value is not the named acknowledgement. for value in ["true", "without-timestamp", "yes"] { let seal = without.replace("seal-stops-validating-when-certificate-expires", value); - let problem = refused(&home, &signing_text(&home, &seal)); + let problem = refused(&home, &signing_text(&home, &seal), DEVELOPMENT_POSTURE); assert!( problem .diagnostics @@ -4343,7 +4468,7 @@ mod tests { fn the_unrestricted_refusal_states_why_and_never_repeats_a_client() { let (_dir, home) = home(); let seal = SEAL.replace("[records-service]", "[records-service, 'batch-*']"); - let problem = refused(&home, &signing_text(&home, &seal)); + let problem = refused(&home, &signing_text(&home, &seal), DEVELOPMENT_POSTURE); let diagnostic = problem .diagnostics .iter() @@ -4366,6 +4491,7 @@ mod tests { let problem = refused( &home, &signing_text(&home, &SEAL.replace("[records-service]", "unrestricted")), + DEVELOPMENT_POSTURE, ); assert!( problem @@ -4376,7 +4502,7 @@ mod tests { .message .contains("never unrestricted"), "{}", - problem.diagnostics[0].message + first_error(&problem).message ); } @@ -4387,14 +4513,14 @@ mod tests { "allowedClients: [portal, records-service]", "allowedClients: unrestricted", ); - load_text(&home, &text).expect("the seal narrows an unrestricted issuer"); + load_development_text(&home, &text).expect("the seal narrows an unrestricted issuer"); } #[test] fn signing_needs_oidc_and_refuses_the_shared_key() { let (_dir, home) = home(); let text = format!("{}signing:\n seals:\n{SEAL}", minimal(&home)); - let problem = refused(&home, &text); + let problem = refused(&home, &text, DEVELOPMENT_POSTURE); assert_eq!( codes(&problem) .into_iter() @@ -4416,9 +4542,13 @@ mod tests { let (_dir, home) = home(); let oidc = OIDC_ONE_ISSUER; let base = minimal(&home).replace("apiKeyRef: secret:file/api.key", oidc); - let problem = refused(&home, &format!("{base}signing:\n seals: {{}}\n")); + let problem = refused( + &home, + &format!("{base}signing:\n seals: {{}}\n"), + DEFAULT_POSTURE, + ); assert!(codes(&problem).contains(&("render.runtime.no-seals", "/signing/seals"))); - let problem = refused(&home, &format!("{base}signing:\n")); + let problem = refused(&home, &format!("{base}signing:\n"), DEFAULT_POSTURE); assert!( codes(&problem).contains(&("config.null-value", "/signing")), "{:?}", @@ -4430,6 +4560,7 @@ mod tests { "{base}signing:\n seals:\n Ministry:\n{}", SEAL.replace(" ministry:\n", "") ), + DEFAULT_POSTURE, ); assert!(!problem.diagnostics.is_empty()); } @@ -4449,7 +4580,8 @@ mod tests { "secretProviders:\n", "secretProviders:\n environment: {}\n", ); - load_text(&home, &text).expect("a declared environment provider admits the reference"); + load_development_text(&home, &text) + .expect("a declared environment provider admits the reference"); } #[test] @@ -4487,17 +4619,21 @@ mod tests { let first_seal = text.lines().position(|l| l == " ministry:").unwrap() + 1; assert_eq!(source.line, Some(first_seal)); - let runtime = load_text(&home, &signing_text(&home, SEAL)).unwrap(); + let runtime = load_development_text(&home, &signing_text(&home, SEAL)).unwrap(); let problem = validate_seal_bindings(&runtime, &manifest).expect_err("unbound seal"); assert_eq!(problem.kind, ProblemKind::RuntimeInvalid); - assert_eq!(problem.diagnostics[0].code, "render.runtime.seal-not-bound"); + assert_eq!(first_error(&problem).code, "render.runtime.seal-not-bound"); } #[test] fn a_sealed_package_without_signing_requires_development() { let (_dir, home) = home(); let file = home.join("runtime.yaml"); - std::fs::write(&file, minimal(&home)).unwrap(); + std::fs::write( + &file, + minimal(&home).replace("apiKeyRef: secret:file/api.key", OIDC_ONE_ISSUER), + ) + .unwrap(); let manifest = signing_manifest(&[ ("licence", Some("ministry")), ("permit", Some("regional")), @@ -4551,7 +4687,7 @@ mod tests { let source = warning.source.as_ref().expect("positioned"); assert_eq!(source.column, Some(5), "placed at the key of the seal"); - let runtime = load_text(&home, &text).unwrap(); + let runtime = load_development_text(&home, &text).unwrap(); let warnings = validate_seal_bindings(&runtime, &manifest).expect("a warning serves"); assert_eq!(warnings.len(), 1); assert_eq!(warnings[0].severity, Severity::Warning); @@ -4560,7 +4696,7 @@ mod tests { #[test] fn seal_for_resolves_the_bundle_declaration_through_the_runtime() { let (_dir, home) = home(); - let runtime = load_text(&home, &signing_text(&home, SEAL)).unwrap(); + let runtime = load_development_text(&home, &signing_text(&home, SEAL)).unwrap(); let manifest = signing_manifest(&[("licence", Some("ministry")), ("notice", None)]); assert!(runtime.seal_for(&manifest, "licence").is_some()); assert!(runtime.seal_for(&manifest, "notice").is_none()); diff --git a/crates/registry-render/src/schema.rs b/crates/registry-render/src/schema.rs index 230a51df8a..dc8a98a1c8 100644 --- a/crates/registry-render/src/schema.rs +++ b/crates/registry-render/src/schema.rs @@ -802,6 +802,17 @@ mod tests { ); } + #[test] + fn authentication_schema_marks_the_shared_api_key_as_development_only() { + let documents = schema_documents().unwrap(); + let runtime: Value = serde_json::from_str(&documents[RUNTIME_SCHEMA_FILE]).unwrap(); + assert_eq!( + runtime["$defs"]["AuthenticationRuntime"]["properties"]["apiKeyRef"] + ["x-registry-development-only"], + json!(["render.posture.shared-api-key"]) + ); + } + fn signing_runtime_document() -> Value { json!({ "apiVersion": RUNTIME_API_VERSION, @@ -1297,7 +1308,15 @@ mod tests { "render.runtime.undeclared-secret-provider", ), ] { - let document = with(&example, pointer, Some(json!(value))); + let document = if pointer == "/authentication/apiKeyRef" { + with( + &example, + "/authentication", + Some(json!({"apiKeyRef": value})), + ) + } else { + with(&example, pointer, Some(json!(value))) + }; assert!(validator.is_valid(&document), "schema: {document}"); std::fs::write(&path, serde_json::to_string_pretty(&document).unwrap()).unwrap(); let codes = check_runtime(&path, false, None) @@ -1305,7 +1324,15 @@ mod tests { .into_iter() .map(|diagnostic| diagnostic.code) .collect::>(); - assert_eq!(codes, [code], "{pointer}: {value}"); + if pointer == "/authentication/apiKeyRef" { + assert_eq!( + codes, + ["render.posture.shared-api-key", code], + "{pointer}: {value}" + ); + } else { + assert_eq!(codes, [code], "{pointer}: {value}"); + } } let documents = schema_documents().unwrap(); let runtime: Value = serde_json::from_str(&documents[RUNTIME_SCHEMA_FILE]).unwrap(); diff --git a/crates/registry-render/src/server.rs b/crates/registry-render/src/server.rs index ef1f0e7475..69282dafe8 100644 --- a/crates/registry-render/src/server.rs +++ b/crates/registry-render/src/server.rs @@ -118,6 +118,12 @@ pub(crate) async fn load_service( declared: DeclaredPosture, ) -> Result<(runtime::RenderRuntime, String, Arc), RenderProblem> { let (mut loaded, positions) = runtime::load_before_posture_decision(runtime_path, declared)?; + // Report the shared-key posture refusal before opening the package. OIDC + // configurations still collect runtime and package-dependent seal findings together. + if loaded.development.is_none() && loaded.config.authentication.api_key_ref.is_some() { + loaded.posture.log_startup(); + runtime::decide_runtime_posture(&loaded.posture, runtime_path)?; + } let runtime = loaded.config; let config_id = loaded.effective_digest; let bundle = runtime::load_package(&runtime)?; @@ -152,8 +158,14 @@ pub(crate) async fn load_service( runtime .authentication .api_key_ref - .as_deref() - .expect("validated key mode"), + .as_ref() + .expect("validated key mode") + .get(loaded.development.as_ref()) + .map_err(|error| { + RenderProblem::new(ProblemKind::RuntimeInvalid, error.to_string()) + })? + .0 + .as_str(), )?)? } else { Vec::new() @@ -3729,6 +3741,18 @@ pub(crate) mod tests { assert_eq!(fields["decision"], "refused", "{name}"); assert_eq!(fields["failed_check"], check, "{name}"); assert_eq!(fields["trace_id"], trace.as_str(), "{name}"); + if let Some(claim) = match name { + "token-audience" => Some("aud claim"), + "token-expired" => Some("exp claim"), + _ => None, + } { + assert!( + fields["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(claim)), + "{name}: the operator diagnostic names the token claim" + ); + } // A scope refusal names the values the operator declared. Every // other check names none. if check == "scope" { diff --git a/crates/registry-render/tests/common/mod.rs b/crates/registry-render/tests/common/mod.rs index 640e89a7ef..8eb495a9c7 100644 --- a/crates/registry-render/tests/common/mod.rs +++ b/crates/registry-render/tests/common/mod.rs @@ -7,7 +7,7 @@ use std::collections::BTreeSet; use std::fs::File; use std::io::{Read, Write}; -use std::net::{TcpListener, TcpStream}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs}; use std::os::unix::fs::FileExt as _; use std::path::Path; use std::sync::Mutex; @@ -20,10 +20,14 @@ use std::time::Duration; /// server then exits with "Address already in use", and the caller retries /// after [`move_to_fresh_port`]. pub fn free_port() -> u16 { + free_port_on(Ipv4Addr::LOCALHOST.into()) +} + +fn free_port_on(ip: IpAddr) -> u16 { static ISSUED_PORTS: Mutex> = Mutex::new(BTreeSet::new()); let mut issued = ISSUED_PORTS.lock().expect("issued test ports"); for _ in 0..1024 { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind for port discovery"); + let listener = TcpListener::bind((ip, 0)).expect("bind for port discovery"); let port = listener.local_addr().expect("local addr").port(); if issued.insert(port) { return port; @@ -35,15 +39,36 @@ pub fn free_port() -> u16 { /// Point the runtime file's listener at a fresh [`free_port`]. pub fn move_to_fresh_port(runtime_path: &Path) { let text = std::fs::read_to_string(runtime_path).unwrap(); - let bind = text - .lines() - .find(|l| l.contains("bind:")) - .expect("listener bind"); - let (address, _) = bind.rsplit_once(':').expect("bind port"); - let moved = text.replacen(bind, &format!("{address}:{}", free_port()), 1); + let line = listener_bind(&text); + let address = listener_address(&text); + let fresh = SocketAddr::new(address.ip(), free_port_on(address.ip())); + let updated = if address.is_ipv6() { + format!(" bind: \"{fresh}\"") + } else { + format!(" bind: {fresh}") + }; + let moved = text.replacen(line, &updated, 1); std::fs::write(runtime_path, moved).unwrap(); } +/// The fixture listener, accepting quoted IPv6 and bare IPv4 socket addresses. +pub fn listener_address(text: &str) -> SocketAddr { + listener_bind(text) + .trim_start() + .strip_prefix("bind:") + .expect("listener bind key") + .trim() + .trim_matches('"') + .parse() + .expect("listener socket address") +} + +fn listener_bind(text: &str) -> &str { + text.lines() + .find(|line| line.trim_start().starts_with("bind:")) + .expect("listener bind") +} + /// Everything the server has written to `stderr`, its standard error file, /// so far. The file is read with `read_exact_at`, which leaves untouched /// the file offset the child writes at. @@ -65,8 +90,8 @@ pub fn server_output(stderr: &File) -> String { /// this server yet"; the caller checks for that exit and bounds the wait. /// The answer may still come from another test's server given the same /// port; [`logged_health_request`] settles which server answered. -pub fn answers_render_health(port: u16) -> bool { - let Ok(mut stream) = TcpStream::connect(("127.0.0.1", port)) else { +pub fn answers_render_health(address: impl ToSocketAddrs) -> bool { + let Ok(mut stream) = TcpStream::connect(address) else { return false; }; if stream diff --git a/crates/registry-render/tests/scaffold.rs b/crates/registry-render/tests/scaffold.rs index 20c48297d7..645d94a08f 100644 --- a/crates/registry-render/tests/scaffold.rs +++ b/crates/registry-render/tests/scaffold.rs @@ -1614,8 +1614,6 @@ use common::{ answers_render_health, free_port, logged_health_request, move_to_fresh_port, server_output, }; -const API_KEY: &str = "test-key-0123456789abcdef0123456789abcdef"; - fn repo_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")) .ancestors() @@ -1644,11 +1642,16 @@ fn serve_deployment() -> (PathBuf, PathBuf, u16) { &repo_root().join("products/render/bundles/receipt"), &bundle, ); - write_secret(&home.join("api.key"), API_KEY); + let mut keys = registry_platform_testing::TokenSigner::new().public_key_set(); + keys["keys"] + .as_array_mut() + .unwrap() + .retain(|key| key["kty"] == "EC"); + write_secret(&home.join("jwks.json"), &keys.to_string()); std::fs::create_dir(home.join("audit")).unwrap(); let port = free_port(); let runtime = format!( - "apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1\nkind: RenderRuntimeConfig\nlistener:\n bind: 127.0.0.1:{port}\npackage:\n root: {}\nsecretProviders:\n file:\n root: {}\nauthentication:\n apiKeyRef: secret:file/api.key\nlimits:\n renderTimeoutSeconds: 20\naudit:\n path: {}\n", + "apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1\nkind: RenderRuntimeConfig\nlistener:\n bind: 127.0.0.1:{port}\npackage:\n root: {}\nsecretProviders:\n file:\n root: {}\nauthentication:\n oidc:\n issuers:\n main:\n issuer: https://issuer.example.test\n audience: urn:render:test\n allowedClients: [portal]\n jwksSource:\n type: static\n documentRef: secret:file/jwks.json\nlimits:\n renderTimeoutSeconds: 20\naudit:\n path: {}\n", bundle.display(), home.display(), home.join("audit/render.jsonl").display() @@ -1709,7 +1712,7 @@ fn try_start_server(runtime_path: &Path) -> Option { } panic!("server exited early with {status}:\n{output}"); } - if answers_render_health(port) && logged_health_request(&stderr) { + if answers_render_health(("127.0.0.1", port)) && logged_health_request(&stderr) { return Some(Server { child, port }); } if Instant::now() > deadline { diff --git a/crates/registry-render/tests/serve.rs b/crates/registry-render/tests/serve.rs index 04fa1a056e..e5c51c31cc 100644 --- a/crates/registry-render/tests/serve.rs +++ b/crates/registry-render/tests/serve.rs @@ -17,7 +17,8 @@ use std::time::{Duration, Instant}; mod common; use common::{ - answers_render_health, free_port, logged_health_request, move_to_fresh_port, server_output, + answers_render_health, free_port, listener_address, logged_health_request, move_to_fresh_port, + server_output, }; const API_KEY: &str = "test-key-0123456789abcdef0123456789abcdef"; @@ -26,6 +27,7 @@ const DEFAULT_LIMITS: &str = "limits:\n renderTimeoutSeconds: 20\n maximumOutp struct Server { child: Child, + stderr: File, port: u16, #[allow(dead_code)] home: PathBuf, @@ -96,6 +98,191 @@ fn deployment(limits: &str, bundle_source: &Path) -> (PathBuf, PathBuf, u16) { (home, runtime_path, port) } +#[test] +fn shared_key_requires_explicit_loopback_development() { + let (home, runtime, port) = deployment( + DEFAULT_LIMITS, + &repo_root().join("products/render/bundles/receipt"), + ); + let original = std::fs::read_to_string(&runtime).unwrap(); + let with_bind = |address: &str| { + original.replace( + &format!("127.0.0.1:{port}"), + &format!("\"{address}:{port}\""), + ) + }; + // A missing file must not replace the posture or bind diagnostic. + std::fs::remove_file(home.join("api.key")).unwrap(); + for (posture, bind, code) in [ + (None, "127.0.0.1", "render.posture.shared-api-key"), + ( + Some("production"), + "127.0.0.1", + "render.posture.shared-api-key", + ), + ( + Some("development"), + "10.0.0.7", + "render.runtime.shared-key-requires-loopback", + ), + ( + Some("development"), + "0.0.0.0", + "render.runtime.shared-key-requires-loopback", + ), + ( + Some("development"), + "[::]", + "render.runtime.shared-key-requires-loopback", + ), + ( + Some("development"), + "[::ffff:127.0.0.1]", + "render.runtime.public-bind", + ), + ] { + let mut text = with_bind(bind); + if matches!(bind, "0.0.0.0" | "[::]") { + text = text.replace( + "listener:\n", + "listener:\n networkExposure: container-private\n", + ); + } + std::fs::write(&runtime, text).unwrap(); + for action in ["check", "serve"] { + let mut command = Command::new(env!("CARGO_BIN_EXE_registry-render")); + command + .env_remove("REGISTRY_STACK_POSTURE") + .arg(action) + .arg("--runtime-config") + .arg(&runtime); + if let Some(posture) = posture { + command.args(["--posture", posture]); + } + let output = command.output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(!output.status.success()); + assert!( + stderr.contains(code) || stdout.contains(code), + "{action}: {stderr}{stdout}" + ); + } + } + + std::fs::write(&runtime, &original).unwrap(); + let bundle = home.join("bundle"); + let facts = home.join("identity-facts.json"); + for action in [ + vec!["healthcheck"], + vec![ + "generate", + "identity-facts", + bundle.to_str().unwrap(), + "--output", + facts.to_str().unwrap(), + ], + ] { + let output = Command::new(env!("CARGO_BIN_EXE_registry-render")) + .env_remove("REGISTRY_STACK_POSTURE") + .args(&action) + .arg("--runtime-config") + .arg(&runtime) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("render.posture.shared-api-key"), + "{action:?}: {stderr}" + ); + } + assert!(!facts.exists()); + + std::fs::write(&runtime, with_bind("[::1]")).unwrap(); + let ipv6 = Command::new(env!("CARGO_BIN_EXE_registry-render")) + .env("REGISTRY_STACK_POSTURE", "development") + .args(["check", "--runtime-config"]) + .arg(&runtime) + .output() + .unwrap(); + assert!(ipv6.status.success(), "{ipv6:?}"); + assert!( + String::from_utf8_lossy(&ipv6.stdout).contains("warning[render.posture.shared-api-key]") + ); + + write_secret(&home.join("api.key"), API_KEY); + move_to_fresh_port(&runtime); + drop(start_development_server(&runtime)); + std::fs::write(&runtime, original).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_registry-render")) + .env_remove("REGISTRY_STACK_POSTURE") + .args(["check", "--posture", "development", "--runtime-config"]) + .arg(&runtime) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stdout).contains("warning[render.posture.shared-api-key]") + ); + let server = start_development_server(&runtime); + let startup = server_output(&server.stderr); + assert!( + startup + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .any(|entry| entry["fields"]["message"] == "posture declared" + && entry["fields"]["posture"] == "development" + && entry["fields"]["development_settings"] == 1), + "{startup}" + ); + assert_eq!( + startup + .lines() + .filter(|line| line.contains("development-only setting in use") + && line.contains("render.posture.shared-api-key")) + .count(), + 1, + "{startup}" + ); + let response = request(server.port, "GET", "/ready", &[], None); + let ready: serde_json::Value = serde_json::from_slice(&response.body).unwrap(); + assert_eq!( + ready["developmentSettings"], + serde_json::json!([{"code": "render.posture.shared-api-key", "pointer": "/authentication/apiKeyRef"}]) + ); + let response = request( + server.port, + "GET", + "/v1/document-types", + &[("Authorization", &format!("Bearer {API_KEY}"))], + None, + ); + assert_eq!(response.status, 200); +} + +#[test] +fn production_shared_key_refusal_precedes_package_loading() { + let (home, runtime, _) = deployment( + DEFAULT_LIMITS, + &repo_root().join("products/render/bundles/receipt"), + ); + let text = std::fs::read_to_string(&runtime).unwrap().replace( + &format!("root: {}", home.join("bundle").display()), + &format!("root: {}", home.join("missing-package").display()), + ); + std::fs::write(&runtime, text).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_registry-render")) + .env_remove("REGISTRY_STACK_POSTURE") + .args(["serve", "--runtime-config"]) + .arg(&runtime) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("render.posture.shared-api-key"), "{stderr}"); +} + fn audit_file(home: &Path) -> PathBuf { home.join("audit").join("render.jsonl") } @@ -111,12 +298,8 @@ fn audit_to_stdout(home: &Path, runtime_path: &Path) { std::fs::write(runtime_path, text).unwrap(); } -fn start_server(runtime_path: &Path) -> Server { - start_server_at(runtime_path, None) -} - -fn start_server_at(runtime_path: &Path, current_dir: Option<&Path>) -> Server { - spawn_server(runtime_path, current_dir, Stdio::null) +fn start_development_server(runtime_path: &Path) -> Server { + spawn_server(runtime_path, None, "development", Stdio::null) } /// The audit stream of a `stdout` destination: a socket pair whose server end @@ -145,7 +328,7 @@ fn start_server_with_stdout(runtime_path: &Path) -> (Server, AuditStream) { reading_end .set_read_timeout(Some(Duration::from_secs(60))) .expect("audit stream read timeout"); - let server = spawn_server(runtime_path, None, || { + let server = spawn_server(runtime_path, None, "development", || { Stdio::from(OwnedFd::from( server_end.try_clone().expect("server audit stream handle"), )) @@ -160,12 +343,13 @@ fn start_server_with_stdout(runtime_path: &Path) -> (Server, AuditStream) { fn spawn_server( runtime_path: &Path, current_dir: Option<&Path>, + posture: &str, mut stdout: impl FnMut() -> Stdio, ) -> Server { // Another socket can take the port before the child binds it, so retry on a fresh one. let mut retries = 0; loop { - if let Some(server) = try_spawn_server(runtime_path, current_dir, stdout()) { + if let Some(server) = try_spawn_server(runtime_path, current_dir, posture, stdout()) { return server; } retries += 1; @@ -188,6 +372,7 @@ fn fail_unless_port_taken(status: ExitStatus, stderr: &File, context: &str) { fn try_spawn_server( runtime_path: &Path, current_dir: Option<&Path>, + posture: &str, stdout: Stdio, ) -> Option { let stderr = tempfile::tempfile().expect("server stderr file"); @@ -202,24 +387,20 @@ fn try_spawn_server( if let Some(dir) = current_dir { command.current_dir(dir); } + command.args(["--posture", posture]); let mut child = command.spawn().expect("spawn registry-render serve"); - let port: u16 = std::fs::read_to_string(runtime_path) - .unwrap() - .lines() - .find(|l| l.contains("bind:")) - .and_then(|l| l.rsplit(':').next()) - .and_then(|p| p.trim().parse().ok()) - .expect("port from runtime"); + let address = listener_address(&std::fs::read_to_string(runtime_path).unwrap()); let deadline = Instant::now() + Duration::from_secs(30); loop { if let Some(status) = child.try_wait().expect("server status") { fail_unless_port_taken(status, &stderr, "server exited early"); return None; } - if answers_render_health(port) && logged_health_request(&stderr) { + if answers_render_health(address) && logged_health_request(&stderr) { return Some(Server { child, - port, + stderr, + port: address.port(), home: PathBuf::from("/tmp"), }); } @@ -345,7 +526,7 @@ fn serve_health_and_ready() { ), ) .unwrap(); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let health = request(server.port, "GET", "/health", &[], None); assert_eq!(health.status, 200); let body: serde_json::Value = serde_json::from_slice(&health.body).expect("health json"); @@ -406,7 +587,7 @@ fn the_metrics_listener_serves_the_series_and_the_api_listener_does_not() { ), ) .unwrap(); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let refused = request( server.port, "POST", @@ -458,7 +639,7 @@ fn another_process_of_the_serving_user_cannot_read_the_serving_environment() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); // Startup has finished, and with it the mark, once health answers. assert_eq!( request(server.port, "GET", "/health", &[], None).status, @@ -493,7 +674,7 @@ fn a_fixture_port_taken_before_the_bind_moves_to_a_fresh_port() { ) .unwrap(); std::thread::spawn(move || holder.incoming().for_each(drop)); - let server = start_server(&runtime); + let server = start_development_server(&runtime); assert_ne!(server.port, port); assert_eq!( request(server.port, "GET", "/health", &[], None).status, @@ -529,7 +710,12 @@ fn the_runtime_file_serves_the_same_from_any_working_directory() { ) .unwrap(); let elsewhere = tempfile::tempdir().expect("unrelated working directory"); - let server = start_server_at(&deploy.join("runtime.yaml"), Some(elsewhere.path())); + let server = spawn_server( + &deploy.join("runtime.yaml"), + Some(elsewhere.path()), + "development", + Stdio::null, + ); let health = request(server.port, "GET", "/health", &[], None); assert_eq!(health.status, 200); let reply = request( @@ -567,7 +753,7 @@ fn api_key_file_with_one_trailing_newline_is_trimmed() { // count: bare LF is what a Linux deployment writes. for ending in ["\n", "\r\n"] { write_secret(&home.join("api.key"), &format!("{API_KEY}{ending}")); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let reply = request( server.port, "POST", @@ -598,7 +784,13 @@ fn api_key_with_stray_whitespace_is_refused_at_startup() { write_secret(&home.join("api.key"), &format!(" {API_KEY}")); let mut child = Command::new(env!("CARGO_BIN_EXE_registry-render")) .env_remove("REGISTRY_STACK_POSTURE") - .args(["serve", "--runtime-config", runtime.to_str().unwrap()]) + .args([ + "serve", + "--posture", + "development", + "--runtime-config", + runtime.to_str().unwrap(), + ]) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() @@ -617,7 +809,7 @@ fn problem_details_are_bounded() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); // HTTP remediation is fixed and value-free even when the refused locale // is large. Detailed diagnostics remain with local operator commands. let locale = "x".repeat(50_000); @@ -670,7 +862,13 @@ fn a_refused_bind_is_caught_before_startup_touches_the_filesystem() { std::fs::write(&runtime, text).unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_registry-render")) .env_remove("REGISTRY_STACK_POSTURE") - .args(["serve", "--runtime-config", runtime.to_str().unwrap()]) + .args([ + "serve", + "--posture", + "development", + "--runtime-config", + runtime.to_str().unwrap(), + ]) .stdin(Stdio::null()) .output() .unwrap(); @@ -720,7 +918,13 @@ fn serve_startup_package_digest_mismatch_uses_common_expected_and_found_shape() std::fs::write(&runtime, text).unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_registry-render")) .env_remove("REGISTRY_STACK_POSTURE") - .args(["serve", "--runtime-config", runtime.to_str().unwrap()]) + .args([ + "serve", + "--posture", + "development", + "--runtime-config", + runtime.to_str().unwrap(), + ]) .output() .unwrap(); assert_eq!( @@ -761,7 +965,7 @@ fn unauthorized_requests_are_refused_and_audited() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let body = receipt_body(); let no_key = request( server.port, @@ -805,7 +1009,7 @@ fn render_returns_pdf_with_hash_headers_matching_golden() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let body = receipt_body(); let reply = request( server.port, @@ -863,7 +1067,7 @@ fn json_variant_serves_openfn_clients() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let body = receipt_body(); let reply = request( server.port, @@ -901,7 +1105,7 @@ fn the_openapi_document_declares_what_the_render_route_answers() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let body = receipt_body(); let render = |accept: &str| { request( @@ -1057,7 +1261,7 @@ fn a_render_with_warnings_reports_the_same_count_in_pdf_and_json() { ) .unwrap(); let (_home, runtime, _) = deployment(DEFAULT_LIMITS, &bundle); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let body = r#"{"issuedAt":"2026-01-01T00:00:00Z","data":{}}"#; let mut replies = Vec::new(); for accept in ["application/pdf", "application/json"] { @@ -1103,7 +1307,7 @@ fn missing_issued_at_and_bad_data_are_named_problems() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let missing = request( server.port, "POST", @@ -1140,7 +1344,7 @@ fn a_render_writes_a_request_entry_then_a_response_entry_sharing_correlation() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let body = receipt_body(); for key in [Some("effect-1234"), None] { let bearer = format!("Bearer {API_KEY}"); @@ -1343,7 +1547,7 @@ fn audit_events_are_value_free() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); // Canary in the data must never reach the audit, even though the // rendered document itself carries it. let body = receipt_body().replace("RCP-2026-W03-000123", "CANARY-DO-NOT-LOG"); @@ -1405,7 +1609,13 @@ fn package_changed_missing_and_extra_files_refuse_startup_by_name() { } let output = Command::new(env!("CARGO_BIN_EXE_registry-render")) .env_remove("REGISTRY_STACK_POSTURE") - .args(["serve", "--runtime-config", runtime.to_str().unwrap()]) + .args([ + "serve", + "--posture", + "development", + "--runtime-config", + runtime.to_str().unwrap(), + ]) .output() .unwrap(); assert_eq!( @@ -1428,7 +1638,7 @@ fn bundle_drift_after_serve_starts_is_refused_per_render() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let bearer = format!("Bearer {API_KEY}"); let auth = [ ("Authorization", bearer.as_str()), @@ -1523,7 +1733,7 @@ fn oversized_bodies_are_refused_after_auth_as_problems() { "limits:\n renderTimeoutSeconds: 20\n maximumOutputBytes: 8388608\n maximumRequestBytes: 1024\n maximumConcurrentRenders: 2\n", &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let oversized = "x".repeat(2048); // Unauthenticated oversized bodies are 401s: auth runs first, and no // unauthenticated body is ever buffered. @@ -1581,7 +1791,7 @@ fn chunked_bodies_are_refused_upfront_as_problems() { "limits:\n renderTimeoutSeconds: 20\n maximumOutputBytes: 8388608\n maximumRequestBytes: 1024\n maximumConcurrentRenders: 2\n", &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); // Chunked framing, oversized payload: once a chunked stream trips the // limit mid-body the connection is broken and NO response can be // delivered, so chunked must be refused up front — as an audited @@ -1627,7 +1837,7 @@ fn wrong_method_on_render_is_a_problem_and_audited() { DEFAULT_LIMITS, &repo_root().join("products/render/bundles/receipt"), ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let reply = request( server.port, "GET", @@ -1691,7 +1901,7 @@ fn pathological_renders_are_bounded_and_the_service_recovers() { "limits:\n renderTimeoutSeconds: 2\n maximumOutputBytes: 8388608\n maximumRequestBytes: 8388608\n maximumConcurrentRenders: 2\n", &bundle, ); - let server = start_server(&runtime); + let server = start_development_server(&runtime); let slow = request( server.port, "POST", @@ -1812,7 +2022,13 @@ fn shutdown_is_bounded_by_grace_even_with_renders_in_flight() { .unwrap(); let mut child = Command::new(env!("CARGO_BIN_EXE_registry-render")) .env_remove("REGISTRY_STACK_POSTURE") - .args(["serve", "--runtime-config", runtime.to_str().unwrap()]) + .args([ + "serve", + "--posture", + "development", + "--runtime-config", + runtime.to_str().unwrap(), + ]) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() @@ -1896,7 +2112,7 @@ fn maintained_sdk_uses_the_real_oidc_adapter_for_render_and_typed_refusals() { " oidc:\n issuers:\n main:\n issuer: https://issuer.example.test\n audience: urn:render:test\n allowedClients: [portal]\n jwksSource:\n type: static\n documentRef: secret:file/jwks.json" ); std::fs::write(&runtime_path, runtime_text).unwrap(); - let server = start_server(&runtime_path); + let server = spawn_server(&runtime_path, None, "production", Stdio::null); let client = RenderClient::new_without_peer_policy(RenderClientConfig::new(format!( "http://127.0.0.1:{}", server.port diff --git a/crates/registry-render/tests/serve_seal.rs b/crates/registry-render/tests/serve_seal.rs index 610491397c..c1da825dfb 100644 --- a/crates/registry-render/tests/serve_seal.rs +++ b/crates/registry-render/tests/serve_seal.rs @@ -752,7 +752,7 @@ fn try_start_server(fixture: &Fixture) -> Option { } panic!("server exited early with {status}:\n{output}"); } - if answers_render_health(port) && logged_health_request(&stderr) { + if answers_render_health(("127.0.0.1", port)) && logged_health_request(&stderr) { return Some(Server { child, port, diff --git a/crates/registry-render/tests/test_seal.rs b/crates/registry-render/tests/test_seal.rs index 9d6778dd29..ca32f100f7 100644 --- a/crates/registry-render/tests/test_seal.rs +++ b/crates/registry-render/tests/test_seal.rs @@ -379,7 +379,7 @@ fn runtime_check_requires_declared_development_for_local_assurance() { let runtime = dir.path().join("runtime.yaml"); let config = |profile| { format!( - "apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1\nkind: RenderRuntimeConfig\nlistener: {{bind: '127.0.0.1:8080'}}\npackage: {{root: /srv/render/package}}\nsecretProviders: {{file: {{root: /srv/render/secrets}}}}\nauthentication: {{apiKeyRef: 'secret:file/api.key'}}\naudit: {{destination: stdout}}\nassuranceProfile: {profile}\n" + "apiVersion: id.registrystack.org/formats/render/runtime/v1alpha1\nkind: RenderRuntimeConfig\nlistener: {{bind: '127.0.0.1:8080'}}\npackage: {{root: /srv/render/package}}\nsecretProviders: {{file: {{root: /srv/render/secrets}}}}\nauthentication: {{oidc: {{issuers: {{main: {{issuer: 'https://issuer.example.test', audience: 'urn:render:test', allowedClients: [portal]}}}}}}}}\naudit: {{destination: stdout}}\nassuranceProfile: {profile}\n" ) }; fs::write(&runtime, config("local")).unwrap(); diff --git a/crates/registry-review-client/src/client.rs b/crates/registry-review-client/src/client.rs index 4261158aa0..afc652b3cb 100644 --- a/crates/registry-review-client/src/client.rs +++ b/crates/registry-review-client/src/client.rs @@ -21,8 +21,11 @@ use registry_review_protocol::{ }; use reqwest::header::{HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE}; use reqwest::{RequestBuilder, Response, StatusCode, Url}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use serde_json::Value; +use serde::{ + de::{DeserializeOwned, IntoDeserializer}, + Deserialize, Deserializer, Serialize, +}; +use serde_json::{Map, Value}; use uuid::Uuid; use crate::model::{check_ask_page, check_result_page}; @@ -50,6 +53,31 @@ fn validate_wire( serde_json::from_value(serde_json::to_value(wire)?) } +// Unit variants also decode from externally tagged JSON objects unless the +// response reader first requires a string. +fn deserialize_string_enum<'de, D, T>(deserializer: D) -> Result +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(String::deserialize(deserializer)?.into_deserializer()) +} + +// Serde's regular struct reader also accepts a positional sequence. Require +// JSON objects at response DTO slots before projecting their known fields. +#[derive(Serialize)] +#[serde(transparent)] +struct ResponseObject(T); + +impl<'de, T: DeserializeOwned> Deserialize<'de> for ResponseObject { + fn deserialize>(deserializer: D) -> Result { + let object = serde_json::Map::deserialize(deserializer)?; + serde_json::from_value(Value::Object(object)) + .map(Self) + .map_err(serde::de::Error::custom) + } +} + #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct SubjectBindingWire { @@ -73,8 +101,8 @@ struct PolicyBindingWire { #[serde(rename_all = "camelCase")] struct ReviewRequestAcceptedWire { request_id: Uuid, - subject: SubjectBindingWire, - policy: PolicyBindingWire, + subject: ResponseObject, + policy: ResponseObject, submission_digest: SubmissionDigest, } @@ -90,10 +118,11 @@ impl ClientResponse for ReviewRequestAccepted { #[serde(rename_all = "camelCase")] struct ReviewRequestViewWire { request_id: Uuid, - subject: SubjectBindingWire, - policy: PolicyBindingWire, + subject: ResponseObject, + policy: ResponseObject, submission_digest: SubmissionDigest, requester_reference: String, + #[serde(deserialize_with = "deserialize_string_enum")] lifecycle: ReviewRequestLifecycle, #[serde(default, skip_serializing_if = "Option::is_none")] active_stage: Option, @@ -111,38 +140,14 @@ impl ClientResponse for ReviewRequestView { } } -#[derive(Default)] -enum OptionalValueWire { - #[default] - Missing, - Present(Value), -} - -impl OptionalValueWire { - fn is_missing(&self) -> bool { - matches!(self, Self::Missing) - } -} - -impl<'de> Deserialize<'de> for OptionalValueWire { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - Value::deserialize(deserializer).map(Self::Present) - } -} - -impl Serialize for OptionalValueWire { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - match self { - Self::Missing => serializer.serialize_none(), - Self::Present(value) => value.serialize(serializer), - } - } +// A missing result defaults to None. A present member must be an object. +fn deserialize_result_object<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, +{ + Map::deserialize(deserializer).map(Some) } #[derive(Deserialize, Serialize)] @@ -150,16 +155,21 @@ impl Serialize for OptionalValueWire { struct ReviewResultWire { result_id: Uuid, request_id: Uuid, - subject: SubjectBindingWire, - policy: PolicyBindingWire, + subject: ResponseObject, + policy: ResponseObject, submission_digest: SubmissionDigest, + #[serde(deserialize_with = "deserialize_string_enum")] status: ReviewResultStatus, #[serde(default, skip_serializing_if = "Option::is_none")] outcome: Option, #[serde(default, skip_serializing_if = "Option::is_none")] public_reason: Option, - #[serde(default, skip_serializing_if = "OptionalValueWire::is_missing")] - result: OptionalValueWire, + #[serde( + default, + deserialize_with = "deserialize_result_object", + skip_serializing_if = "Option::is_none" + )] + result: Option>, completed_at: String, available_until: String, } @@ -184,7 +194,7 @@ struct ReviewResultFeedEntryWire { #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ReviewResultFeedPageWire { - items: Vec, + items: Vec>, #[serde(default, skip_serializing_if = "Option::is_none")] next_cursor: Option, } @@ -209,12 +219,13 @@ enum ReviewAskWantWire { struct ReviewAskWire { ask_id: Uuid, request_id: Uuid, - subject: SubjectBindingWire, + subject: ResponseObject, text: String, - wants: Vec, + wants: Vec>, asked_at: String, #[serde(default, skip_serializing_if = "Option::is_none")] due_at: Option, + #[serde(deserialize_with = "deserialize_string_enum")] state: ReviewAskState, #[serde(default, skip_serializing_if = "Option::is_none")] answered_at: Option, @@ -242,7 +253,7 @@ struct ReviewAskFeedEntryWire { #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ReviewAskFeedPageWire { - items: Vec, + items: Vec>, #[serde(default, skip_serializing_if = "Option::is_none")] next_cursor: Option, } @@ -262,8 +273,12 @@ impl ClientResponse for ReviewAskFeedPage { rename_all_fields = "camelCase" )] enum ReviewCancelResponseWire { - Cancelled { result: ReviewResultWire }, - AlreadyTerminal { result: ReviewResultWire }, + Cancelled { + result: ResponseObject, + }, + AlreadyTerminal { + result: ResponseObject, + }, } impl ClientResponse for ReviewCancelResponse { @@ -939,7 +954,7 @@ impl ReviewClient { Some(trace_id.to_owned()), ) })?; - let wire = serde_json::from_value(value).map_err(|_| { + let ResponseObject(wire) = serde_json::from_value(value).map_err(|_| { protocol( status, ReviewProtocolFailure::Body, @@ -1034,22 +1049,11 @@ impl ReviewClient { Ok(value) => value, Err(_) => return protocol(status, ReviewProtocolFailure::Problem, trace_id), }; - let valid_code = !document.code.is_empty() - && document.code.len() <= 128 - && document.code.bytes().all(|byte| { - byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-') - }); - // Problem URIs are opaque provider identifiers and are never fetched. - let valid_type = document.type_uri.len() <= 2048 - && !document - .type_uri - .chars() - .any(|c| c.is_control() || c.is_whitespace()) - && Url::parse(&document.type_uri).is_ok(); - if document.status != status.as_u16() + if !(status.is_client_error() || status.is_server_error()) + || document.status != status.as_u16() || trace_id.as_deref() != Some(document.trace_id.as_str()) - || !valid_code - || !valid_type + || !valid_problem_code(&document.code) + || !valid_problem_type(&document.type_uri) { return protocol(status, ReviewProtocolFailure::Problem, trace_id); } @@ -1075,7 +1079,7 @@ impl ReviewClient { ReviewClientError::Problem { status: status.as_u16(), problem: Box::new(ReviewProblem { - code: ReviewProblemCode::validated(document.code), + code: ReviewProblemCode::validated(document.code, document.type_uri), title: document.title, detail: document.detail, trace_id: document.trace_id.as_str().to_owned(), @@ -1085,6 +1089,58 @@ impl ReviewClient { } } +fn valid_problem_code(code: &str) -> bool { + code.len() <= 128 + && code.split(['.', '-']).all(|word| { + !word.is_empty() + && word + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) + }) +} + +// Problem types are opaque provider identifiers. Validate the spelling before +// retaining it for a caller, and never resolve or fetch the URI. +fn valid_problem_type(value: &str) -> bool { + if value.len() > 2048 + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-._~:/[]@!$&'()*+,;=%".contains(&byte)) + || !value.split('%').skip(1).all(|escape| { + escape + .as_bytes() + .get(..2) + .is_some_and(|pair| pair.iter().all(u8::is_ascii_hexdigit)) + }) + { + return false; + } + Url::parse(value).is_ok_and(|uri| { + uri.as_str() == value + // Raw brackets are allowed in an IP-literal host only. + && !uri.path().contains(['[', ']']) + && uri.username().is_empty() + && uri.password().is_none() + && match uri.scheme() { + "http" | "https" => uri.has_host(), + "about" => value == "about:blank", + "urn" => { + uri.cannot_be_a_base() + && uri.path().split_once(':').is_some_and(|(nid, name)| { + (2..=32).contains(&nid.len()) + && nid.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + && !nid.starts_with('-') + && !nid.ends_with('-') + && !name.is_empty() + // RFC 8141 requires pchar before any raw slash. + && !name.starts_with('/') + }) + } + _ => false, + } + }) +} + fn accepted_producer( headers: &reqwest::header::HeaderMap, status: StatusCode, diff --git a/crates/registry-review-client/src/error.rs b/crates/registry-review-client/src/error.rs index ea3f938600..790b291b03 100644 --- a/crates/registry-review-client/src/error.rs +++ b/crates/registry-review-client/src/error.rs @@ -1,4 +1,5 @@ use std::fmt; +use std::hash::{Hash, Hasher}; use registry_platform_httputil::client::TransportKind; use thiserror::Error; @@ -24,17 +25,34 @@ pub enum ReviewMutationErrorClass { Ambiguous, } -#[derive(Clone, Eq, Hash, PartialEq)] -pub struct ReviewProblemCode(String); +#[derive(Clone, Eq)] +pub struct ReviewProblemCode { + value: String, + type_uri: String, +} impl ReviewProblemCode { - pub(crate) fn validated(value: String) -> Self { - Self(value) + pub(crate) fn validated(value: String, type_uri: String) -> Self { + Self { value, type_uri } } #[must_use] pub fn as_str(&self) -> &str { - &self.0 + &self.value + } +} + +// A provider's type URI is associated metadata. Code comparisons and hashing +// continue to use the Review code alone. +impl PartialEq for ReviewProblemCode { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + +impl Hash for ReviewProblemCode { + fn hash(&self, state: &mut H) { + self.value.hash(state); } } @@ -42,14 +60,14 @@ impl fmt::Debug for ReviewProblemCode { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_tuple("ReviewProblemCode") - .field(&self.0) + .field(&self.value) .finish() } } impl fmt::Display for ReviewProblemCode { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str(&self.0) + formatter.write_str(&self.value) } } @@ -109,6 +127,14 @@ pub struct ReviewProblem { pub validation: Option, } +impl ReviewProblem { + /// The provider's validated Problem type URI, for use as an opaque identifier. + #[must_use] + pub fn problem_type(&self) -> &str { + &self.code.type_uri + } +} + impl fmt::Debug for ReviewProblem { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter diff --git a/crates/registry-review-client/tests/http_boundary.rs b/crates/registry-review-client/tests/http_boundary.rs index 82fca1e92b..bf17501545 100644 --- a/crates/registry-review-client/tests/http_boundary.rs +++ b/crates/registry-review-client/tests/http_boundary.rs @@ -150,6 +150,7 @@ async fn create_posts_once_with_caller_auth_and_stable_idempotency_key() { .expect("accepted request"); assert_eq!(accepted.value.request_id, Uuid::from_u128(7)); + assert_eq!(accepted.value, expected_binding(Uuid::from_u128(7))); let observations = observations.lock().expect("observations"); assert_eq!(observations.len(), 1); let (method, path, headers) = &observations[0]; @@ -184,18 +185,22 @@ async fn capture_create( ); assert_eq!(sent["policy"], json!(create_request().policy)); assert!(sent.get("kind").is_none()); - let mut accepted = accepted_json(Uuid::from_u128(7)); - accepted["futureAcceptedMember"] = json!({"safeToIgnore": true}); - accepted["subject"]["futureSubjectMember"] = json!(true); - accepted["policy"]["futurePolicyMember"] = json!(true); - json_response(StatusCode::OK, accepted) + json_response( + StatusCode::OK, + with_binding_additions(accepted_json(Uuid::from_u128(7))), + ) } #[tokio::test] async fn current_policy_create_accepts_a_concrete_binding_and_refuses_partial_pins_before_io() { let app = Router::new().route( "/v1/review-requests", - post(|| async { json_response(StatusCode::CREATED, accepted_json(Uuid::from_u128(7))) }), + post(|| async { + json_response( + StatusCode::CREATED, + with_binding_additions(accepted_json(Uuid::from_u128(7))), + ) + }), ); let (client, server) = serve(app).await; let token = BearerToken::new("one-call-secret").unwrap(); @@ -535,6 +540,33 @@ async fn request_progress_rejects_each_substituted_binding_member() { } } +#[tokio::test] +async fn request_view_requires_string_lifecycle() { + let request_id = Uuid::from_u128(7); + let app = Router::new().route( + "/v1/review-requests/{id}", + get(move || async move { + let mut view = request_view_json(request_id); + view["lifecycle"] = json!({"reviewing": null}); + json_response(StatusCode::OK, view) + }), + ); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let result = client + .request(ReviewAuth::new(&token, "producer"), request_id) + .await; + assert!(matches!( + result, + Err(ReviewClientError::Protocol { + status: 200, + failure: ReviewProtocolFailure::Body, + .. + }) + )); + server.abort(); +} + #[tokio::test] async fn request_progress_rejects_terminal_or_invalid_codes() { for (lifecycle, active_stage, progress_code) in [ @@ -744,11 +776,10 @@ async fn capture_request( request: Request, ) -> Response { capture(&observations, &request); - let mut view = request_view_json(request_id); - view["futureRequestMember"] = json!({"safeToIgnore": true}); - view["subject"]["futureSubjectMember"] = json!(true); - view["policy"]["futurePolicyMember"] = json!(true); - json_response(StatusCode::OK, view) + json_response( + StatusCode::OK, + with_binding_additions(request_view_json(request_id)), + ) } async fn capture_progress_request( @@ -757,7 +788,7 @@ async fn capture_progress_request( request: Request, ) -> Response { capture(&observations, &request); - let mut view = request_view_json(request_id); + let mut view = with_binding_additions(request_view_json(request_id)); view["progressCode"] = json!("identity-check"); json_response(StatusCode::OK, view) } @@ -782,6 +813,13 @@ fn request_view_json(request_id: Uuid) -> serde_json::Value { }) } +fn with_binding_additions(mut value: serde_json::Value) -> serde_json::Value { + value["futureMember"] = json!({"safeToIgnore": true}); + value["subject"]["futureSubjectMember"] = json!(true); + value["policy"]["futurePolicyMember"] = json!(true); + value +} + async fn capture_feed( State(observations): State, request: Request, @@ -807,27 +845,14 @@ async fn capture_cancel( request: Request, ) -> Response { capture(&observations, &request); - let mut cancellation = json!({"outcome": "cancelled", "result": { - "resultId": Uuid::from_u128(99), - "requestId": request_id, - "subject": { - "source": "registry", - "type": "change-request", - "id": "proposal-7", - "version": "3", - "digest": DIGEST - }, - "policy": {"id": "registry-correction", "version": "1", "digest": DIGEST}, - "submissionDigest": DIGEST, - "status": "cancelled", - "completedAt": "2026-09-19T00:00:00Z", - "availableUntil": "2026-10-19T00:00:00Z" - }}); - cancellation["futureCancellationMember"] = json!({"safeToIgnore": true}); - cancellation["result"]["futureResultMember"] = json!(true); - cancellation["result"]["subject"]["futureSubjectMember"] = json!(true); - cancellation["result"]["policy"]["futurePolicyMember"] = json!(true); - json_response(StatusCode::OK, cancellation) + json_response( + StatusCode::OK, + json!({ + "outcome": "cancelled", + "result": with_binding_additions(cancelled_result_json(request_id)), + "futureCancellationMember": {"safeToIgnore": true} + }), + ) } fn capture(observations: &Observations, request: &Request) { @@ -896,6 +921,83 @@ async fn result_lookup_accepts_only_the_four_defined_statuses_and_shapes() { server.abort(); } +#[tokio::test] +async fn result_requires_string_status() { + let request_id = Uuid::from_u128(7); + let app = Router::new().route( + "/v1/review-requests/{id}/result", + get(move || async move { + let mut result = result_json(request_id); + result["status"] = json!({"approved": null}); + json_response(StatusCode::OK, result) + }), + ); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let result = client + .result( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ) + .await; + assert!(matches!( + result, + Err(ReviewClientError::Protocol { + status: 200, + failure: ReviewProtocolFailure::Body, + .. + }) + )); + server.abort(); +} + +#[tokio::test] +async fn result_requires_object_data_if_present() { + let request_id = Uuid::from_u128(7); + let opaque = json!({"providerExtension": {"keep": [null, 3, "text"]}}); + let token = BearerToken::new("one-call-secret").expect("fixture token"); + for (data, valid) in [ + (None, true), + (Some(opaque), true), + (Some(json!(null)), false), + (Some(json!([])), false), + (Some(json!("text")), false), + ] { + let mut body = result_json(request_id); + body["status"] = json!("changes-requested"); + body["outcome"] = json!("changes-requested"); + if let Some(data) = &data { + body["result"] = data.clone(); + } + let app = Router::new().route( + "/v1/review-requests/{id}/result", + get(move || async move { json_response(StatusCode::OK, body) }), + ); + let (client, server) = serve(app).await; + let result = client + .result( + ReviewAuth::new(&token, "producer"), + &expected_binding(request_id), + ) + .await; + server.abort(); + match (valid, result) { + (true, Ok(ReviewResultResponse::Available(result))) => { + assert_eq!(result.value.result, data); + } + ( + false, + Err(ReviewClientError::Protocol { + status: 200, + failure: ReviewProtocolFailure::Body, + .. + }), + ) => {} + (_, result) => panic!("unexpected response for fixture data {data:?}: {result:?}"), + } + } +} + #[tokio::test] async fn nil_accepted_request_is_refused_before_authenticated_http() { let client = ReviewClient::new(ReviewClientConfig::new_without_peer_policy( @@ -969,11 +1071,23 @@ async fn result_lookup_refuses_a_non_object_payload() { #[tokio::test] async fn cancellation_refuses_every_mismatched_accepted_binding_field() { let request_id = Uuid::from_u128(300); + let mut wrong_subject = cancelled_json(request_id); + wrong_subject["result"]["subject"]["version"] = json!("4"); + let mut wrong_request = cancelled_json(request_id); + wrong_request["result"]["requestId"] = json!(Uuid::from_u128(301)); let mut wrong_policy = cancelled_json(request_id); wrong_policy["result"]["policy"]["version"] = json!("2"); let mut wrong_submission = cancelled_json(request_id); wrong_submission["result"]["submissionDigest"] = json!(OTHER_DIGEST); - let responses = Arc::new(Mutex::new(VecDeque::from([wrong_policy, wrong_submission]))); + let mut unknown_outcome = cancelled_json(request_id); + unknown_outcome["outcome"] = json!("cancellation-pending"); + let responses = Arc::new(Mutex::new(VecDeque::from([ + wrong_subject, + wrong_request, + wrong_policy, + wrong_submission, + unknown_outcome, + ]))); let app = Router::new() .route( "/v1/review-requests/{id}/cancel", @@ -988,7 +1102,7 @@ async fn cancellation_refuses_every_mismatched_accepted_binding_field() { reason: "source proposal withdrawn".to_owned(), }; - for _ in 0..2 { + for _ in 0..5 { let error = client .cancel_request( ReviewAuth::new(&token, "producer"), @@ -1009,10 +1123,58 @@ async fn cancellation_refuses_every_mismatched_accepted_binding_field() { server.abort(); } +#[tokio::test] +async fn already_terminal_cancellation_keeps_the_opaque_result_data() { + let request_id = Uuid::from_u128(300); + let mut result = with_binding_additions(result_json(request_id)); + result["status"] = json!("changes-requested"); + let data = json!({"providerField": {"nestedField": [true, null]}}); + result["result"] = data.clone(); + let app = Router::new().route( + "/v1/review-requests/{id}/cancel", + post(move || async move { + json_response( + StatusCode::OK, + json!({ + "outcome": "already-terminal", "result": result, "futureMember": true + }), + ) + }), + ); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let expected = expected_binding(request_id); + let response = client + .cancel_request( + ReviewAuth::new(&token, "producer"), + &expected, + "cancel-300", + &ReviewCancelRequest { + subject: subject(), + reason: "source proposal withdrawn".to_owned(), + }, + ) + .await + .expect("terminal cancellation response"); + assert!(matches!(response.value, + registry_review_client::ReviewCancelResponse::AlreadyTerminal { result } + if result.result == Some(data) && result.request_id == request_id + )); + server.abort(); +} + fn cancelled_json(request_id: Uuid) -> serde_json::Value { + json!({"outcome": "cancelled", "result": cancelled_result_json(request_id)}) +} + +fn cancelled_result_json(request_id: Uuid) -> serde_json::Value { let mut result = result_json(request_id); result["status"] = json!("cancelled"); - json!({"outcome": "cancelled", "result": result}) + result + .as_object_mut() + .expect("result object") + .remove("outcome"); + result } async fn queued_cancel_response( @@ -1028,13 +1190,7 @@ async fn queued_cancel_response( async fn result_by_id(Path(id): Path) -> Response { match id.as_u128() { - 200 => { - let mut value = result_json(id); - value["futureResultMember"] = json!({"safeToIgnore": true}); - value["subject"]["futureSubjectMember"] = json!(true); - value["policy"]["futurePolicyMember"] = json!(true); - json_response(StatusCode::OK, value) - } + 200 => json_response(StatusCode::OK, with_binding_additions(result_json(id))), 201 => json_response(StatusCode::OK, result_json(Uuid::from_u128(200))), 202 => empty_response(StatusCode::ACCEPTED), 404 => empty_response(StatusCode::NOT_FOUND), @@ -1075,6 +1231,383 @@ async fn result_by_id(Path(id): Path) -> Response { } } +#[tokio::test] +async fn review_success_routes_refuse_invalid_shapes_before_returning_a_projection() { + let request_id = Uuid::from_u128(7); + let ask_id = Uuid::from_u128(5); + let expected = expected_binding(request_id); + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let cancellation = ReviewCancelRequest { + subject: expected.subject.clone(), + reason: "source proposal withdrawn".to_owned(), + }; + let cases = [ + ( + "create", + "/v1/review-requests", + accepted_json(request_id), + "/policy/version", + ), + ( + "request", + "/v1/review-requests/{id}", + request_view_json(request_id), + "/subject/source", + ), + ( + "progress", + "/v1/review-requests/{id}", + request_view_json(request_id), + "/createdAt", + ), + ( + "result", + "/v1/review-requests/{id}/result", + result_json(request_id), + "/resultId", + ), + ( + "results", + "/v1/review-results", + json!({"items": [feed_entry_json(8)]}), + "/items/0/completedAt", + ), + ( + "cancel", + "/v1/review-requests/{id}/cancel", + cancelled_json(request_id), + "/result/submissionDigest", + ), + ( + "asks", + "/v1/review-asks", + json!({"items": [{ + "eventId": Uuid::from_u128(8), "requestId": request_id, "askId": ask_id, + "changedAt": "2026-11-27T01:00:00Z" + }]}), + "/items/0/askId", + ), + ( + "ask", + "/v1/review-requests/{id}/asks/{ask}", + ask_json(request_id, ask_id), + "/wants/0/kind", + ), + ( + "answer", + "/v1/review-requests/{id}/asks/{ask}/answer", + answered_ask_json(request_id, ask_id), + "/answeredAt", + ), + ]; + for (operation, route, valid, required) in cases { + let (parent, member) = required.rsplit_once('/').expect("member pointer"); + let mut missing = valid.clone(); + missing + .pointer_mut(parent) + .expect("parent") + .as_object_mut() + .expect("object") + .remove(member) + .expect("required member"); + let mut wrong_type = valid.clone(); + *wrong_type.pointer_mut(required).expect("required member") = json!(false); + let valid = valid.to_string(); + let duplicate = format!( + r#"{},"futureMember":{{"item":1,"item":2}}}}"#, + valid.strip_suffix('}').expect("response object") + ); + for (defect, body) in [ + ("missing", missing.to_string()), + ("wrong type", wrong_type.to_string()), + ("duplicate in ignored member", duplicate), + ] { + let handler = move || async move { + raw_response(StatusCode::OK, Some("application/json"), &body) + }; + let method = match operation { + "create" | "cancel" | "answer" => post(handler), + _ => get(handler), + }; + let (client, server) = serve(Router::new().route(route, method)).await; + let auth = ReviewAuth::new(&token, "producer"); + let error = match operation { + "create" => client + .create_or_recover_request( + auth, + "submission-7", + &create_request(), + &expected_submission_digest(), + ) + .await + .err(), + "request" => client.request(auth, request_id).await.err(), + "progress" => client.request_progress(auth, &expected).await.err(), + "result" => client.result(auth, &expected).await.err(), + "results" => client + .requester_results(auth, &ReviewResultsQuery::default()) + .await + .err(), + "cancel" => client + .cancel_request(auth, &expected, "cancel-7", &cancellation) + .await + .err(), + "asks" => client.ask_feed(auth, None, None).await.err(), + "ask" => client.ask(auth, &expected, ask_id).await.err(), + "answer" => client + .answer_ask(auth, "answer-5", &expected, ask_id, &ask_answer()) + .await + .err(), + _ => unreachable!("fixture operation"), + }; + assert!( + matches!( + error, + Some(ReviewClientError::Protocol { + status: 200, + failure: ReviewProtocolFailure::Body, + .. + }) + ), + "{operation} accepted or misclassified {defect}: {error:?}" + ); + server.abort(); + } + } +} + +#[tokio::test] +async fn acceptance_requires_json_objects_for_the_envelope_and_nested_bindings() { + let request_id = Uuid::from_u128(7); + let accepted = accepted_json(request_id); + let mut positional_subject = accepted.clone(); + positional_subject["subject"] = + json!(["registry", "change-request", "proposal-7", "3", DIGEST]); + let positional_acceptance = + json!([request_id, accepted["subject"], accepted["policy"], DIGEST]); + let token = BearerToken::new("one-call-secret").expect("fixture token"); + for body in [positional_subject, positional_acceptance] { + let app = Router::new().route( + "/v1/review-requests", + post(move || async move { json_response(StatusCode::CREATED, body) }), + ); + let (client, server) = serve(app).await; + let response = client + .create_or_recover_request( + ReviewAuth::new(&token, "producer"), + "submission-7", + &create_request(), + &expected_submission_digest(), + ) + .await; + assert!( + matches!( + response, + Err(ReviewClientError::Protocol { + status: 201, + failure: ReviewProtocolFailure::Body, + .. + }) + ), + "positional values must not decode as acceptance objects: {response:?}" + ); + server.abort(); + } +} + +#[tokio::test] +async fn generic_problem_rejects_malformed_identifiers_and_non_error_status() { + const TYPE: &str = "https://review-provider.example.test/problems/refused"; + const CODE: &str = "provider.refused"; + let mut cases = vec![ + ( + "separator only", + TYPE.to_owned(), + ".-".to_owned(), + StatusCode::CONFLICT, + ), + ( + "empty segment", + TYPE.to_owned(), + "provider..refused".to_owned(), + StatusCode::CONFLICT, + ), + ( + "empty word", + TYPE.to_owned(), + "provider.future--refusal".to_owned(), + StatusCode::CONFLICT, + ), + ( + "uppercase code", + TYPE.to_owned(), + "Provider.refused".to_owned(), + StatusCode::CONFLICT, + ), + ( + "long code", + TYPE.to_owned(), + "a".repeat(129), + StatusCode::CONFLICT, + ), + ( + "long type", + format!("{TYPE}/{}", "a".repeat(2048)), + CODE.to_owned(), + StatusCode::CONFLICT, + ), + ( + "redirect status", + TYPE.to_owned(), + CODE.to_owned(), + StatusCode::TEMPORARY_REDIRECT, + ), + ]; + for (name, type_uri) in [ + ( + "userinfo", + "https://fixture-name@review-provider.example.test/problems/refused", + ), + ( + "query", + "https://review-provider.example.test/problems/refused?fixture=value", + ), + ( + "fragment", + "https://review-provider.example.test/problems/refused#fixture", + ), + ( + "noncanonical path", + "https://review-provider.example.test/problems/../refused", + ), + ( + "invalid escape", + "https://review-provider.example.test/problems/%xx", + ), + ("file URI", "file:///problem"), + ] { + cases.push(( + name, + type_uri.to_owned(), + CODE.to_owned(), + StatusCode::CONFLICT, + )); + } + let token = BearerToken::new("one-call-secret").expect("fixture token"); + for (name, type_uri, code, status) in cases { + let value = json!({ + "type": type_uri, "code": code, "status": status.as_u16(), + "title": "Refused", "detail": "The provider refused the request.", + "traceId": "0123456789abcdef0123456789abcdef" + }); + let app = Router::new().route( + "/v1/review-requests/{id}", + get(move || async move { + raw_response(status, Some("application/problem+json"), &value.to_string()) + }), + ); + let (client, server) = serve(app).await; + let error = client + .request(ReviewAuth::new(&token, "producer"), Uuid::from_u128(7)) + .await + .expect_err("invalid problem"); + assert!( + matches!(error, ReviewClientError::Protocol { + status: actual, failure: ReviewProtocolFailure::Problem, .. + } if actual == status.as_u16()), + "{name} was misclassified: {error:?}" + ); + assert_eq!(error.mutation_class(), ReviewMutationErrorClass::Ambiguous); + server.abort(); + } +} + +#[tokio::test] +async fn generic_problem_validates_uri_syntax_by_component() { + const TRACE: &str = "0123456789abcdef0123456789abcdef"; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let mut accepted_code = None; + for (type_uri, valid) in [ + ( + "https://review-provider.example.test/%5Btype-canary%5d", + true, + ), + ("urn:review:%5btype-canary%5D", true), + ("urn:review:type/canary", true), + ("urn:review:%2ftype%2Fcanary", true), + ("http://[2001:db8::1]/type-canary", true), + ("about:blank", true), + ("https://review-provider.example.test/[type-canary]", false), + ("http://[2001:db8::1]/type-canary]", false), + ("urn:review:[type-canary", false), + ("urn:review:type-canary]", false), + ("urn:review:/type-canary", false), + ] { + let value = json!({ + "type": type_uri, "code": "provider.refused", "status": 409, + "title": "Title canary", "detail": "Detail canary", "traceId": TRACE + }); + let app = Router::new().route( + "/v1/review-requests", + post(move || async move { + raw_response( + StatusCode::CONFLICT, + Some("application/problem+json"), + &value.to_string(), + ) + }), + ); + let (client, server) = serve(app).await; + let error = client + .create_or_recover_request( + ReviewAuth::new(&token, "producer"), + "submission-7", + &create_request(), + &expected_submission_digest(), + ) + .await + .expect_err("provider refusal"); + server.abort(); + + for rendered in [format!("{error}"), format!("{error:?}")] { + for canary in [type_uri, "Title canary", "Detail canary"] { + assert!(!rendered.contains(canary), "error disclosed fixture text"); + } + } + let classification = error.mutation_class(); + match (valid, error) { + ( + true, + ReviewClientError::Problem { + status: 409, + problem, + }, + ) => { + assert_eq!(classification, ReviewMutationErrorClass::Deterministic); + assert_eq!(problem.problem_type(), type_uri); + assert_eq!(problem.trace_id, TRACE); + assert_eq!(problem.code.as_str(), "provider.refused"); + assert_eq!( + accepted_code.get_or_insert_with(|| problem.code.clone()), + &problem.code + ); + } + ( + false, + ReviewClientError::Protocol { + status: 409, + failure: ReviewProtocolFailure::Problem, + trace_id, + }, + ) => { + assert_eq!(classification, ReviewMutationErrorClass::Ambiguous); + assert_eq!(trace_id.as_deref(), Some(TRACE)); + } + (_, error) => panic!("unexpected classification for fixture {type_uri}: {error:?}"), + } + } +} + #[tokio::test] async fn malformed_media_oversize_and_header_excess_are_refused() { let app = Router::new() @@ -1138,9 +1671,19 @@ async fn malformed_media_oversize_and_header_excess_are_refused() { .await .unwrap_err(); assert!(matches!( - provider_error, - ReviewClientError::Problem { status: 400, .. } + &provider_error, + ReviewClientError::Problem { status: 400, problem } + if problem.problem_type() == "https://review-provider.example.test/problems/provider/refused" + && problem.code.as_str() == "provider.refused" + && problem.trace_id == "0123456789abcdef0123456789abcdef" + && problem.validation.is_none() )); + for rendered in [provider_error.to_string(), format!("{provider_error:?}")] { + assert!(!rendered.contains("review-provider.example.test")); + assert!(!rendered.contains("title canary")); + assert!(!rendered.contains("detail canary")); + assert!(!rendered.contains("extension canary")); + } assert_eq!( provider_error.mutation_class(), ReviewMutationErrorClass::Deterministic @@ -1273,8 +1816,9 @@ async fn invalid_problem_uri() -> Response { async fn provider_specific_problem() -> Response { let value = json!({ "type":"https://review-provider.example.test/problems/provider/refused", - "title":"Invalid request", "status":400, "detail":"The request is invalid.", - "code":"provider.refused", "traceId":"0123456789abcdef0123456789abcdef" + "title":"Provider title canary", "status":400, "detail":"Provider detail canary", + "code":"provider.refused", "traceId":"0123456789abcdef0123456789abcdef", + "futureMember": {"display": "Provider extension canary"} }); Response::builder() .status(StatusCode::BAD_REQUEST) @@ -1759,7 +2303,7 @@ async fn capture_ask_feed( request: Request, ) -> Response { capture(&observations, &request); - let mut page = json!({ + let page = json!({ "items": [{ "eventId": Uuid::from_u128(8), "requestId": Uuid::from_u128(7), @@ -1770,7 +2314,6 @@ async fn capture_ask_feed( "nextCursor": Uuid::from_u128(8), "futurePageMember": {"safeToIgnore": true} }); - page["items"][0]["futureEntryMember"] = json!(true); json_response(StatusCode::OK, page) } @@ -1780,10 +2323,10 @@ async fn capture_ask( request: Request, ) -> Response { capture(&observations, &request); - let mut ask = ask_json(request_id, ask_id); - ask["futureAskMember"] = json!({"safeToIgnore": true}); - ask["subject"]["futureSubjectMember"] = json!(true); - json_response(StatusCode::OK, ask) + json_response( + StatusCode::OK, + with_ask_additions(ask_json(request_id, ask_id)), + ) } async fn capture_answer( @@ -1792,7 +2335,18 @@ async fn capture_answer( request: Request, ) -> Response { capture(&observations, &request); - json_response(StatusCode::OK, answered_ask_json(request_id, ask_id)) + json_response( + StatusCode::OK, + with_ask_additions(answered_ask_json(request_id, ask_id)), + ) +} + +fn with_ask_additions(mut ask: serde_json::Value) -> serde_json::Value { + ask["futureAskMember"] = json!({"safeToIgnore": true}); + ask["subject"]["futureSubjectMember"] = json!(true); + ask["wants"][0]["futureWantMember"] = json!(true); + ask["wants"][1]["futureWantMember"] = json!({"safeToIgnore": true}); + ask } #[tokio::test] @@ -2092,6 +2646,15 @@ async fn ask_read_refuses_every_mismatched_binding_and_invalid_ask() { let mut unknown_state = ask_json(request_id, ask_id); unknown_state["state"] = json!("reopened"); cases.push(unknown_state); + let mut unknown_want = ask_json(request_id, ask_id); + unknown_want["wants"][0]["kind"] = json!("future-want"); + cases.push(unknown_want); + let mut repeated_want = with_ask_additions(ask_json(request_id, ask_id)); + repeated_want["wants"][1]["kind"] = json!("answer"); + cases.push(repeated_want); + let mut inverted_deadline = ask_json(request_id, ask_id); + inverted_deadline["dueAt"] = json!("2026-11-26T01:00:00Z"); + cases.push(inverted_deadline); let token = BearerToken::new("one-call-secret").expect("fixture token"); for body in cases { @@ -2408,6 +2971,41 @@ async fn answer_refuses_a_returned_ask_that_is_not_the_answered_one() { } } +#[tokio::test] +async fn answer_requires_string_ask_state() { + let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); + let app = Router::new().route( + "/v1/review-requests/{id}/asks/{ask}/answer", + post(move || async move { + let mut ask = answered_ask_json(request_id, ask_id); + ask["state"] = json!({"answered": null}); + json_response(StatusCode::OK, ask) + }), + ); + let (client, server) = serve(app).await; + let token = BearerToken::new("one-call-secret").expect("fixture token"); + let error = client + .answer_ask( + ReviewAuth::new(&token, "producer"), + "answer-5", + &expected_binding(request_id), + ask_id, + &ask_answer(), + ) + .await + .expect_err("object-valued ask state"); + assert!(matches!( + error, + ReviewClientError::Protocol { + status: 200, + failure: ReviewProtocolFailure::Body, + .. + } + )); + assert_eq!(error.mutation_class(), ReviewMutationErrorClass::Ambiguous); + server.abort(); +} + #[tokio::test] async fn answer_refuses_a_success_recorded_at_another_answer_time() { let (request_id, ask_id) = (Uuid::from_u128(7), Uuid::from_u128(5)); diff --git a/crates/registry-rstack-dev/src/database.rs b/crates/registry-rstack-dev/src/database.rs index 318de38fd4..4e1a294bd5 100644 --- a/crates/registry-rstack-dev/src/database.rs +++ b/crates/registry-rstack-dev/src/database.rs @@ -4,7 +4,6 @@ use std::{ cell::Cell, future::Future, net::IpAddr, - str::FromStr, thread, time::{Duration, Instant}, }; @@ -18,7 +17,6 @@ use registry_platform_provision::{ verify_logins, AdminConfig, Mode, Plan, Probe, ProductDatabase, ProvisionError, ProvisionTarget, RoleCredential, SchemaLayout, Scope, Spatial, StatementOutcome, }; -use rustls::pki_types::{pem::PemObject as _, CertificateDer}; use serde::{Deserialize, Serialize}; use sha2::{Digest as _, Sha256}; use tokio::runtime::{Builder, Runtime}; @@ -1338,10 +1336,10 @@ fn admin_config_with_resolver( match key.as_ref() { "sslmode" => { let next = match value.as_ref() { - "require" | "verify-ca" | "verify-full" => DatabaseTransport::VerifiedTls, + "require" | "verify-full" => DatabaseTransport::VerifiedTls, "disable" => DatabaseTransport::LoopbackPlaintext, _ => bail!( - "the PostgreSQL admin URL sslmode must be require, verify-ca, or \ + "platform.database.unsupported-sslmode: the PostgreSQL admin URL sslmode must be require or \ verify-full for verified TLS, or disable for loopback plaintext" ), }; @@ -1376,12 +1374,11 @@ fn admin_config_with_resolver( 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. + // Remove the runner's transport option before handing the URL to the driver. let mut sanitized = parsed.clone(); let kept: Vec<(String, String)> = parsed .query_pairs() - .filter(|(key, _)| key != "sslmode" && key != "transport") + .filter(|(key, _)| key != "transport") .map(|(key, value)| (key.into_owned(), value.into_owned())) .collect(); if kept.is_empty() { @@ -1389,8 +1386,23 @@ fn admin_config_with_resolver( } else { sanitized.query_pairs_mut().clear().extend_pairs(kept); } - let mut config = Config::from_str(sanitized.as_str()) - .map_err(|_| anyhow!("the PostgreSQL admin URL has an invalid query parameter value"))?; + let mut config = registry_platform_postgres::parse_database_url( + sanitized.as_str(), + transport == DatabaseTransport::VerifiedTls, + ) + .map_err(|error| { + if matches!( + error, + registry_platform_config::DatabaseTransportError::Url( + registry_platform_config::DatabaseUrlError::Invalid, + _ + ) + ) { + anyhow!("the PostgreSQL admin URL has an invalid query parameter value") + } else { + anyhow!("{}: {error}", error.code()) + } + })?; config.keepalives_idle(KEEPALIVE_IDLE); if config.get_hosts().len() != 1 || !matches!(config.get_hosts().first(), Some(Host::Tcp(_))) @@ -1475,17 +1487,8 @@ fn tls_connector(ca_pem: Option<&[u8]>) -> Result { } if let Some(pem) = ca_pem { - let mut roots = rustls::RootCertStore::empty(); - let mut count = 0usize; - for certificate in CertificateDer::pem_slice_iter(pem) { - roots - .add(certificate.context("the PostgreSQL CA PEM is invalid")?) - .context("the PostgreSQL CA certificate is invalid")?; - count += 1; - } - if count == 0 { - bail!("the PostgreSQL CA PEM contains no certificates"); - } + let roots = registry_platform_postgres::pem_root_store(pem) + .context("the PostgreSQL CA bundle is refused")?; let config = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); @@ -1879,7 +1882,6 @@ mod tests { ); for accepted in [ "sslmode=require", - "sslmode=verify-ca", "sslmode=verify-full", "connect_timeout=5", "application_name=rstack", @@ -1891,6 +1893,7 @@ mod tests { } for (query, expected) in [ ("sslmode=disable", "numeric loopback address or localhost"), + ("sslmode=verify-ca", "platform.database.unsupported-sslmode"), ( "sslmode=allow", "verified TLS, or disable for loopback plaintext", diff --git a/crates/registry-rstack-dev/src/dev_facts.rs b/crates/registry-rstack-dev/src/dev_facts.rs index afb4da4022..0ee10d91ea 100644 --- a/crates/registry-rstack-dev/src/dev_facts.rs +++ b/crates/registry-rstack-dev/src/dev_facts.rs @@ -1021,14 +1021,12 @@ mod tests { #[test] fn offline_report_requires_unique_members_from_owner_subprocess() { - use std::{fs, os::unix::fs::PermissionsExt}; - let scratch = tempfile::tempdir().unwrap(); let tool = scratch.path().join("offline-report"); let body = r#"{"ok":false,"ok":true,"command":"explain","status":"complete", "kind":"BRegCtlReport","apiVersion":"id.registrystack.org/formats/breg/ctl-report/v1alpha1"}"#; - fs::write(&tool, format!("#!/bin/sh\nprintf '%s' '{body}'\n")).unwrap(); - fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); + crate::write_executable_fixture(&tool, &format!("#!/bin/sh\nprintf '%s' '{body}'\n")) + .unwrap(); let terminate = AtomicBool::new(false); checked_report(&tool, Product::Breg, "explain", &[], &terminate, false).unwrap(); let error = diff --git a/crates/registry-rstack-dev/src/lib.rs b/crates/registry-rstack-dev/src/lib.rs index 4b350848a6..959ebef40a 100644 --- a/crates/registry-rstack-dev/src/lib.rs +++ b/crates/registry-rstack-dev/src/lib.rs @@ -25,6 +25,7 @@ mod journey; mod owner_report; pub(crate) mod plan; mod preview; +mod preview_export; mod products; mod recovery; mod roles; @@ -148,6 +149,13 @@ enum Entry { json: bool, project: PathBuf, }, + ExportPreview { + #[arg(long)] + output: PathBuf, + #[arg(long)] + json: bool, + project: PathBuf, + }, Status { #[arg(long)] json: bool, @@ -667,6 +675,18 @@ pub fn run(args: Args, stdout: &mut dyn Write, stderr: &mut dyn Write) -> ExitCo .and_then(|()| issuer_start(&project, ttl.as_deref())); (json, outcome.map(|value| (value, 0))) } + Entry::ExportPreview { + output, + project, + json, + } => { + let outcome = require_development(declared(None)) + .map_err(|(code, message, action)| { + Usage(format!("{code}: {message}. {action}")).into() + }) + .and_then(|()| export_preview(&project, &output)); + (json, outcome.map(|value| (value, 0))) + } Entry::Status { run_id, json } => (json, status(&run_id).map(|value| (value, 0))), Entry::Token { run_id, @@ -773,6 +793,30 @@ fn emit(output: &mut dyn Write, report: &Value, machine: bool) -> std::io::Resul if machine { return writeln!(output, "{report}"); } + if report["status"] == "exported" { + writeln!( + output, + "Preview bundle exported to {}", + report["output"].as_str().unwrap_or("?") + )?; + writeln!( + output, + " bundle digest {}", + report["bundleDigest"].as_str().unwrap_or("?") + )?; + writeln!( + output, + " declaration digest {}", + report["declarationDigest"].as_str().unwrap_or("?") + )?; + for file in report["files"].as_array().into_iter().flatten() { + writeln!(output, " {}", file.as_str().unwrap_or("?"))?; + } + if let Some(warning) = report["warning"].as_str() { + writeln!(output, " warning: {warning}")?; + } + return Ok(()); + } let run = report["run_id"].as_str().expect("run report"); let status = report["status"].as_str().expect("run status"); writeln!(output, "Run {run} {status}")?; @@ -1209,6 +1253,128 @@ fn start( spawn_supervisor(&base, &root, &input, &signals) } +/// Builds the project's service preview and copies the bundle a host serves +/// outside `rstack dev` into `output`, a new directory. It runs the checks and +/// the build `start` runs, in a private directory under the state directory, +/// and starts no service. +fn export_preview(project: &Path, output: &Path) -> Result { + let output = env::current_dir()?.join(output); + let report_output = output + .to_str() + .context("the preview bundle output path must be UTF-8")?; + preview_export::require_new_output(&output)?; + let project = project.canonicalize().with_context(|| { + format!( + "cannot open the development project directory {}", + project.display() + ) + })?; + let loaded = plan::load(&project)?; + let plan = loaded.plan; + let build = loaded + .preview + .context("dev.yaml declares no preview; add preview to export a preview bundle")?; + products::require_canonical_review_pair(&project, &plan)?; + let preview = preview::Build { + helper: preview::helper(&project)?, + plan: build, + }; + let application_node = Some(products::preflight_preview()?); + let signals = signals()?; + let inspection = products::inspect(&project, &plan, &signals); + loaded + .authored_digests + .verify_preview_native(&preview.plan.product.project)?; + let inspection = inspection?; + plan::validate_application_authority(&plan, &inspection)?; + // An export runs only each product's tool; no runtime is started. + let binaries = plan + .products + .iter() + .map(|entry| { + let tool = product_tool(entry.product)?; + Ok(( + entry.product, + Binaries { + runtime: tool.clone(), + tool, + }, + )) + }) + .collect::>()?; + let base = state_dir()?; + if let Some(parent) = base.parent().filter(|path| !path.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + ensure_private(&base, true)?; + let run_id = Uuid::new_v4().simple().to_string(); + let root = base + .canonicalize()? + .join(format!("preview-export-{run_id}")); + private_directory(&root)?; + let input = Arc::new(RunInput { + authored_digests: Some(loaded.authored_digests), + run_id, + project, + application_root: None, + application_node, + preview: Some(preview), + plan, + scenarios: Vec::new(), + scenario_digest: loaded.scenario_digest, + ttl_seconds: 0, + schema_people: Vec::new(), + breg_authority: inspection.breg_authority, + casework_principals: inspection.casework_principals, + binaries, + managed_database: false, + project_key: None, + clean: false, + issuer_only: false, + }); + let built = root.join("application-preview"); + let exported = (|| { + let mut runner = products::ProductRunner::new(input, &root, &signals)?; + runner.capture_preview_project()?; + runner.check()?; + runner.build_preview(&built)?; + preview_export::export_bundle(&built, &output) + })() + .with_context(|| { + format!( + "the preview export failed; its owner-only logs are kept in {}", + root.display() + ) + })?; + let cleanup = fs::remove_dir_all(&root); + Ok(export_report(report_output, exported, &root, cleanup)) +} + +/// The export report. The bundle is complete once written, so a build +/// directory that cannot be removed is reported beside the digest rather than +/// as a failure that hides it. +fn export_report( + output: &str, + exported: preview_export::Exported, + root: &Path, + cleanup: std::io::Result<()>, +) -> Value { + let mut report = json!({ + "status": "exported", + "output": output, + "bundleDigest": exported.digest, + "declarationDigest": exported.declaration_digest, + "files": exported.files, + }); + if let Err(error) = cleanup { + report["warning"] = json!(format!( + "cannot remove the export build directory {}: {error}; remove it yourself", + root.display() + )); + } + report +} + fn prepare_issuer_input( project: &Path, ttl: Option<&str>, @@ -3010,6 +3176,33 @@ fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { Ok(()) } +/// Write the stub in a separate process so sibling forks cannot inherit its writable handle. +#[cfg(test)] +fn write_executable_fixture(path: &Path, contents: &str) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + + let directory = + tempfile::tempdir_in(path.parent().context("fixture has no parent directory")?)?; + let temporary = directory.path().join("stub"); + let writer = Command::new("/bin/sh") + .args([ + "-c", + r#"printf '%s' "$2" > "$1""#, + "write-executable-fixture", + ]) + .arg(&temporary) + .arg(contents) + .output()?; + ensure!( + writer.status.success(), + "cannot write fixture: {}", + String::from_utf8_lossy(&writer.stderr) + ); + fs::set_permissions(&temporary, fs::Permissions::from_mode(0o700))?; + fs::rename(&temporary, path)?; + Ok(()) +} + fn clock() -> Result { Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()) } @@ -4312,7 +4505,6 @@ mod tests { #[test] fn issuer_only_token_for_default_breg_project_carries_registry_principal() { use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; - use std::os::unix::fs::PermissionsExt; let scratch = tempfile::tempdir().unwrap(); let project = scratch.path().join("project"); @@ -4385,7 +4577,7 @@ mod tests { .unwrap(); let fake_bregctl = scratch.path().join("fake-bregctl"); - fs::write( + write_executable_fixture( &fake_bregctl, r#"#!/usr/bin/env bash set -euo pipefail @@ -4401,10 +4593,9 @@ fi "#, ) .unwrap(); - fs::set_permissions(&fake_bregctl, fs::Permissions::from_mode(0o755)).unwrap(); let fake_caseworkctl = scratch.path().join("fake-caseworkctl"); - fs::write( + write_executable_fixture( &fake_caseworkctl, r#"#!/usr/bin/env bash set -euo pipefail @@ -4414,7 +4605,6 @@ EOF "#, ) .unwrap(); - fs::set_permissions(&fake_caseworkctl, fs::Permissions::from_mode(0o755)).unwrap(); let terminate = AtomicBool::new(false); let loaded = plan::LoadedPlan { @@ -4584,4 +4774,67 @@ EOF json!("urn:dev:breg") ); } + + #[test] + fn an_export_whose_build_directory_stays_still_reports_its_digest() { + let exported = || preview_export::Exported { + digest: "d".repeat(64), + declaration_digest: "c".repeat(64), + files: vec!["manifest.json".to_owned()], + }; + let root = Path::new("/state/preview-export-run"); + let clean = export_report("/out/bundle", exported(), root, Ok(())); + assert_eq!(clean["bundleDigest"], "d".repeat(64)); + assert_eq!(clean["output"], "/out/bundle"); + assert!(clean.get("warning").is_none()); + let kept = export_report( + "/out/bundle", + exported(), + root, + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)), + ); + assert_eq!(kept["bundleDigest"], "d".repeat(64)); + assert_eq!(kept["status"], "exported"); + assert!(kept["warning"] + .as_str() + .unwrap() + .contains("/state/preview-export-run")); + let mut human = Vec::new(); + emit(&mut human, &kept, false).unwrap(); + let human = String::from_utf8(human).unwrap(); + assert!(human.contains(&"d".repeat(64)), "{human}"); + assert!(human.contains("warning:"), "{human}"); + } + + #[test] + fn export_preview_refuses_a_non_utf8_output_before_reading_the_project() { + use std::os::unix::ffi::OsStrExt; + + let scratch = tempfile::tempdir().unwrap(); + let output = scratch + .path() + .join(std::ffi::OsStr::from_bytes(b"bundle-\xff")); + let error = export_preview(&scratch.path().join("missing-project"), &output).unwrap_err(); + assert_eq!( + error.to_string(), + "the preview bundle output path must be UTF-8" + ); + assert!(!output.exists()); + } + + /// The output is refused before the plan is read or any tool runs. The + /// service preview end-to-end test covers a project without a preview, + /// which needs the BReg tool to load its plan. + #[test] + fn export_preview_refuses_an_existing_output_before_reading_the_project() { + let scratch = tempfile::tempdir().unwrap(); + let output = scratch.path().join("bundle"); + fs::create_dir(&output).unwrap(); + let refused = format!( + "{:#}", + export_preview(&scratch.path().join("missing-project"), &output).unwrap_err() + ); + assert!(refused.contains("already exists"), "{refused}"); + assert_eq!(fs::read_dir(&output).unwrap().count(), 0); + } } diff --git a/crates/registry-rstack-dev/src/preview.rs b/crates/registry-rstack-dev/src/preview.rs index ef563ec312..5b4164e518 100644 --- a/crates/registry-rstack-dev/src/preview.rs +++ b/crates/registry-rstack-dev/src/preview.rs @@ -31,8 +31,11 @@ pub(super) struct Preview { /// 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. + /// Declared functions callable by the page and Coordinator. pub functions: UniqueList, + /// Declared functions callable only by Coordinator. These names must be distinct from functions. + #[serde(default, rename = "coordinatorFunctions")] + pub coordinator_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( @@ -124,11 +127,17 @@ impl Preview { .collect() } + pub(super) fn function_names(&self) -> impl Iterator { + self.functions + .iter() + .chain(self.coordinator_functions.iter()) + } + pub(super) fn build_plan(&self, root: &Path, native: &plan::Plan) -> Result { let refusal = || { plan::refuse( "/preview", - "A browser preview requires one named BReg in service.yaml, a UI, declared functions, and issuer run.", + "A browser preview requires one named BReg in service.yaml, a UI, 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.", ) }; @@ -198,7 +207,6 @@ impl Preview { _ => None, }; if service.file != service_file - || service.functions.is_empty() || service .products .iter() @@ -282,7 +290,7 @@ impl Preview { check_routes(routes, "/preview/breg")?; } let selected = &self.functions; - if selected.is_empty() + if (self.function_names().next().is_none() && !service.functions.is_empty()) || selected.len() > 64 || selected .iter() @@ -290,8 +298,21 @@ impl Preview { { return plan::refuse( "/preview/functions", - "Select one or more declared functions.", - "Use names from functions in service.yaml.", + "Select preview functions from the service inventory.", + "Select declared names, or leave both lists empty for a service without functions.", + ) + .map_err(Into::into); + } + if selected.len() + self.coordinator_functions.len() > 64 + || self + .coordinator_functions + .iter() + .any(|id| selected.contains(id) || !service.functions.contains_key(id)) + { + return plan::refuse( + "/preview/coordinatorFunctions", + "Select distinct declared Coordinator-only functions within the 64-function preview limit.", + "Use names from service.yaml that do not appear in preview.functions.", ) .map_err(Into::into); } @@ -801,6 +822,78 @@ functions: [assess-permit] .to_string() } + #[test] + fn coordinator_only_functions_are_selected_and_disjoint_from_page_functions() { + let mut preview = actors(); + preview["functions"] = json!([]); + preview["coordinatorFunctions"] = json!(["assess-permit"]); + let input = native(preview.clone()); + let selected = input.preview.as_ref().unwrap(); + assert_eq!( + selected + .function_names() + .map(LocalId::as_str) + .collect::>(), + ["assess-permit"] + ); + build(preview.clone()).unwrap(); + + preview["functions"] = json!(["assess-permit"]); + assert!(pointer(preview.clone()).contains("/preview/coordinatorFunctions")); + preview["functions"] = json!([]); + preview["coordinatorFunctions"] = json!(["unlisted"]); + assert!(pointer(preview).contains("/preview/coordinatorFunctions")); + } + + #[test] + fn the_combined_function_selection_cannot_exceed_64() { + let names = (0..65) + .map(|index| format!("function-{index}")) + .collect::>(); + let with_inventory = |root: &Path| { + let declaration = SERVICE.replace( + "functions: [assess-permit]", + &format!("functions: [{}]", names.join(", ")), + ); + fs::write(root.join("service.yaml"), declaration).unwrap(); + for name in &names { + let directory = root.join("functions").join(name); + fs::create_dir(&directory).unwrap(); + fs::write(directory.join("index.ts"), "").unwrap(); + } + }; + let mut preview = actors(); + preview["functions"] = json!(&names[..32]); + preview["coordinatorFunctions"] = json!(&names[32..64]); + build_with(preview.clone(), with_inventory).unwrap(); + + preview["coordinatorFunctions"] = json!(&names[32..]); + assert!( + refusal(build_with(preview, with_inventory)).contains("/preview/coordinatorFunctions") + ); + } + + #[test] + fn a_preview_accepts_an_empty_function_inventory_and_selection() { + let without_functions = |root: &Path| { + fs::remove_dir_all(root.join("functions")).unwrap(); + fs::write( + root.join("service.yaml"), + SERVICE.replace("functions: [assess-permit]\n", ""), + ) + .unwrap(); + }; + let mut preview = actors(); + preview["functions"] = json!([]); + let build = build_with(preview.clone(), without_functions).unwrap(); + assert!(build.functions.is_empty()); + + // An empty selection still cannot silently discard a declared function. + assert!(pointer(preview).contains("/preview/functions")); + // Conversely, choosing a function requires declaring it. + assert!(refusal(build_with(actors(), without_functions)).contains("/preview/functions")); + } + #[test] fn an_actors_preview_reaches_casework_and_the_coordinator_as_route_products() { let build = build(actors()).unwrap(); diff --git a/crates/registry-rstack-dev/src/preview_export.rs b/crates/registry-rstack-dev/src/preview_export.rs new file mode 100644 index 0000000000..d389263529 --- /dev/null +++ b/crates/registry-rstack-dev/src/preview_export.rs @@ -0,0 +1,657 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The bundle `rstack dev export-preview` writes from a built service preview: +//! the manifest, each compiled function and every file of the manifest's +//! static output, with one digest a deployment can pin. + +use anyhow::{bail, ensure, Context, Result}; +use registry_platform_yaml::LocalId; +use sha2::{Digest, Sha256}; +use std::fs; +use std::io::{Read, Write}; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Component, Path, PathBuf}; + +const MANIFEST: &str = "manifest.json"; +const MAXIMUM_MANIFEST_BYTES: u64 = 1024 * 1024; + +/// What an export wrote. +pub(super) struct Exported { + /// The bundle digest: the SHA-256, in lowercase hex, of the compact JSON + /// list of `[relative path, SHA-256 of the file]` pairs for every + /// exported file, sorted by path. + pub digest: String, + /// The manifest's `declarationDigest`, the digest of the checked + /// service.yaml the bundle was built from. + pub declaration_digest: String, + /// The exported files' relative paths, sorted. + pub files: Vec, +} + +/// Copies the bundle out of `built` into `output`, a new directory. Refuses an +/// existing `output` and leaves it untouched. +pub(super) fn export_bundle(built: &Path, output: &Path) -> Result { + require_new_output(output)?; + let manifest = read_file(&built.join(MANIFEST), MAXIMUM_MANIFEST_BYTES)?; + let (declaration_digest, mut paths) = bundle_paths(built, &manifest)?; + paths.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes())); + // Created at its final mode, so no umask leaves it writable by others + // while the bundle is written. + fs::DirBuilder::new() + .mode(0o755) + .create(output) + .map_err(|error| match error.kind() { + std::io::ErrorKind::AlreadyExists => anyhow::anyhow!("{}", already_exists(output)), + _ => anyhow::Error::new(error).context(format!("cannot create {}", output.display())), + })?; + let pairs = match write_bundle(built, output, &paths, &manifest) { + Ok(pairs) => pairs, + Err(error) => { + // Leave no partial bundle a deployment could mistake for a complete one. + fs::remove_dir_all(output).with_context(|| { + format!("cannot remove the partial bundle {}", output.display()) + })?; + return Err(error); + } + }; + Ok(Exported { + digest: hex(&Sha256::digest(serde_json::to_vec(&pairs)?)), + declaration_digest, + files: paths, + }) +} + +/// Refuses an output path that already exists, as a file, a directory or a +/// link, or whose parent directory does not exist, before anything is built. +pub(super) fn require_new_output(output: &Path) -> Result<()> { + match fs::symlink_metadata(output) { + Ok(_) => bail!("{}", already_exists(output)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| format!("cannot inspect {}", output.display())) + } + } + let parent = output + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + ensure!( + fs::metadata(parent).is_ok_and(|metadata| metadata.is_dir()), + "the parent directory of {} does not exist; create it first", + output.display() + ); + Ok(()) +} + +fn already_exists(output: &Path) -> String { + format!( + "{} already exists; choose a path for a new bundle directory", + output.display() + ) +} + +/// The manifest's declaration digest and the relative path of every file the +/// bundle holds: the manifest, each compiled function and every file below +/// the manifest's `staticOutput`. +fn bundle_paths(built: &Path, manifest: &[u8]) -> Result<(String, Vec)> { + let manifest: serde_json::Value = + serde_json::from_slice(manifest).context("the preview manifest is not JSON")?; + let declaration_digest = manifest["declarationDigest"] + .as_str() + .context("the preview manifest has no declarationDigest")? + .to_owned(); + let functions = manifest["functions"] + .as_array() + .context("the preview manifest must declare functions as an array")?; + let static_output = manifest["staticOutput"] + .as_str() + .filter(|path| inside(Path::new(path))) + .context("the preview manifest's staticOutput must be a relative path inside the build")?; + let mut paths = vec![MANIFEST.to_owned()]; + for function in functions { + let name = function + .as_str() + .and_then(|name| LocalId::new(name).ok()) + .context("the preview manifest names an invalid compiled function")?; + paths.push(format!("functions/{}.mjs", name.as_str())); + } + static_files(built, Path::new(static_output), &mut paths)?; + Ok((declaration_digest, paths)) +} + +fn inside(path: &Path) -> bool { + path.components().next().is_some() + && path + .components() + .all(|component| matches!(component, Component::Normal(_))) +} + +fn static_files(built: &Path, directory: &Path, paths: &mut Vec) -> Result<()> { + let listed = built.join(directory); + ensure!( + fs::symlink_metadata(&listed) + .with_context(|| format!( + "the preview has no static output at {}", + directory.display() + ))? + .is_dir(), + "the preview's static output must be a directory" + ); + for entry in fs::read_dir(&listed)? { + let entry = entry?; + let relative = directory.join(entry.file_name()); + let kind = entry.file_type()?; + if kind.is_dir() { + static_files(built, &relative, paths)?; + } else { + ensure!( + kind.is_file(), + "a preview bundle holds only regular files; {} is not one", + relative.display() + ); + paths.push( + relative + .to_str() + .context("a static output path is not valid UTF-8")? + .to_owned(), + ); + } + } + Ok(()) +} + +/// Opens a regular file without following a link. +fn open_file(path: &Path) -> Result { + let file = fs::OpenOptions::new() + .read(true) + .custom_flags((rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32) + .open(path) + .with_context(|| format!("cannot open {}", path.display()))?; + ensure!( + file.metadata()?.is_file(), + "a preview bundle holds only regular files" + ); + Ok(file) +} + +fn read_file(path: &Path, limit: u64) -> Result> { + let mut bytes = Vec::new(); + open_file(path)? + .take(limit.saturating_add(1)) + .read_to_end(&mut bytes)?; + ensure!( + bytes.len() as u64 <= limit, + "{} exceeds {limit} bytes", + path.display() + ); + Ok(bytes) +} + +fn write_bundle<'a>( + built: &Path, + output: &Path, + paths: &'a [String], + manifest: &[u8], +) -> Result> { + fs::set_permissions(output, fs::Permissions::from_mode(0o755))?; + let mut pairs = Vec::with_capacity(paths.len()); + let mut buffer = [0; 64 * 1024]; + for path in paths { + let target = output.join(path); + let mut directory = PathBuf::from(output); + for component in Path::new(path) + .parent() + .into_iter() + .flat_map(Path::components) + { + directory.push(component); + match fs::symlink_metadata(&directory) { + Ok(metadata) if metadata.is_dir() => {} + Ok(_) => bail!("{} is not a directory", directory.display()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + fs::DirBuilder::new().mode(0o755).create(&directory)?; + fs::set_permissions(&directory, fs::Permissions::from_mode(0o755))?; + } + Err(error) => return Err(error.into()), + } + } + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o644) + .open(&target) + .with_context(|| format!("cannot write {path}"))?; + let mut source; + let mut manifest_bytes = manifest; + let reader: &mut dyn Read = if path == MANIFEST { + &mut manifest_bytes + } else { + source = open_file(&built.join(path)).with_context(|| format!("cannot read {path}"))?; + &mut source + }; + let mut hash = Sha256::new(); + loop { + let count = reader + .read(&mut buffer) + .with_context(|| format!("cannot read {path}"))?; + if count == 0 { + break; + } + let bytes = &buffer[..count]; + file.write_all(bytes) + .with_context(|| format!("cannot write {path}"))?; + hash.update(bytes); + } + pairs.push((path.as_str(), hex(&hash.finalize()))); + file.set_permissions(fs::Permissions::from_mode(0o644))?; + } + Ok(pairs) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::os::unix::fs::PermissionsExt; + use std::path::PathBuf; + + /// The reference host pins the same digest for the same fixture in + /// deploy/examples/business-registration/tests/host.test.mjs. + const FIXTURE_DIGEST: &str = "4156a7e44cde4dbb78af14ee722dffcdfd9388f7b70400bdd124ad935f44e2a4"; + + fn fixture() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../deploy/examples/business-registration/tests/bundle") + .canonicalize() + .unwrap() + } + + /// A built preview directory: the fixture bundle plus the run-only files + /// and staged sources the build also leaves there. + fn built_preview(root: &Path) -> PathBuf { + let built = root.join("application-preview"); + copy_tree(&fixture(), &built); + fs::write(built.join("run.mjs"), "run").unwrap(); + fs::write(built.join("configure.mjs"), "configure").unwrap(); + fs::write(built.join("service.yaml"), "kind: RStackService\n").unwrap(); + fs::create_dir_all(built.join("project/functions/register-business")).unwrap(); + fs::write( + built.join("project/functions/register-business/index.ts"), + "source", + ) + .unwrap(); + built + } + + fn built_page_only_preview(root: &Path) -> PathBuf { + let built = root.join("application-preview"); + let static_output = built.join("project/web/dist"); + fs::create_dir_all(&static_output).unwrap(); + fs::write(static_output.join("index.html"), "

Licences

\n").unwrap(); + fs::write( + built.join(MANIFEST), + r#"{ + "version": "registry-preview test", + "declarationDigest": "1111111111111111111111111111111111111111111111111111111111111111", + "product": {"id":"licenses","member":"licenses","audience":"urn:example:licenses","profile":"holder"}, + "routeProducts": [], + "preview": {"page":"/","breg":{},"functions":[]}, + "functions": [], + "staticOutput": "project/web/dist" +} +"#, + ) + .unwrap(); + fs::write(built.join("run.mjs"), "run").unwrap(); + built + } + + fn copy_tree(source: &Path, destination: &Path) { + fs::create_dir_all(destination).unwrap(); + for entry in fs::read_dir(source).unwrap() { + let entry = entry.unwrap(); + let target = destination.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + fs::copy(entry.path(), target).unwrap(); + } + } + } + + fn tree(root: &Path) -> Vec<(String, u32)> { + let mut found = Vec::new(); + let mut pending = vec![root.to_path_buf()]; + while let Some(directory) = pending.pop() { + for entry in fs::read_dir(&directory).unwrap() { + let path = entry.unwrap().path(); + let metadata = fs::symlink_metadata(&path).unwrap(); + let relative = path + .strip_prefix(root) + .unwrap() + .to_str() + .unwrap() + .to_owned(); + found.push((relative, metadata.permissions().mode() & 0o7777)); + if metadata.is_dir() { + pending.push(path); + } + } + } + found.sort(); + found + } + + fn manifest(built: &Path, edit: impl FnOnce(&mut serde_json::Value)) { + let path = built.join("manifest.json"); + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + edit(&mut value); + fs::write(path, serde_json::to_vec(&value).unwrap()).unwrap(); + } + + fn refusal(built: &Path, output: &Path) -> String { + let Err(error) = export_bundle(built, output) else { + panic!("the export was accepted"); + }; + format!("{error:#}") + } + + #[test] + fn exports_exactly_the_manifest_functions_and_static_output_with_the_pinned_digest() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + let output = scratch.path().join("bundle"); + + let exported = export_bundle(&built, &output).unwrap(); + + assert_eq!(exported.digest, FIXTURE_DIGEST); + assert_eq!(exported.declaration_digest, "0".repeat(64)); + // Sorted by the bytes of the whole path: `assets.json` precedes + // `assets/note.txt`, which a walk sorted per directory would not give. + let files = [ + "functions/register-business.mjs", + "manifest.json", + "project/web/dist/app.js", + "project/web/dist/assets.json", + "project/web/dist/assets/note.txt", + "project/web/dist/caf\u{e9}.txt", + "project/web/dist/index.html", + "project/web/dist/service.css", + ]; + assert_eq!(exported.files, files); + let directories = [ + "functions", + "project", + "project/web", + "project/web/dist", + "project/web/dist/assets", + ]; + let mut expected: Vec<(String, u32)> = files + .iter() + .map(|file| ((*file).to_owned(), 0o644)) + .chain(directories.iter().map(|path| ((*path).to_owned(), 0o755))) + .collect(); + expected.sort(); + assert_eq!(tree(&output), expected); + assert_eq!( + fs::metadata(&output).unwrap().permissions().mode() & 0o7777, + 0o755 + ); + for file in files { + assert_eq!( + fs::read(output.join(file)).unwrap(), + fs::read(fixture().join(file)).unwrap(), + "{file}" + ); + } + } + + #[test] + fn exports_a_page_only_preview_with_an_explicitly_empty_function_inventory() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_page_only_preview(scratch.path()); + let output = scratch.path().join("bundle"); + + let exported = export_bundle(&built, &output).unwrap(); + + assert_eq!( + exported.digest, + "52e4b8b65027937769916cd627da2131db4051f752119825f2dd148985171465" + ); + assert_eq!(exported.declaration_digest, "1".repeat(64)); + let files = [MANIFEST, "project/web/dist/index.html"]; + assert_eq!(exported.files, files); + for file in files { + assert_eq!( + fs::read(output.join(file)).unwrap(), + fs::read(built.join(file)).unwrap(), + "{file}" + ); + } + assert_eq!( + tree(&output), + [ + (MANIFEST.to_owned(), 0o644), + ("project".to_owned(), 0o755), + ("project/web".to_owned(), 0o755), + ("project/web/dist".to_owned(), 0o755), + ("project/web/dist/index.html".to_owned(), 0o644), + ] + ); + } + + #[test] + fn refuses_missing_or_malformed_function_inventories_before_creating_output() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_page_only_preview(scratch.path()); + let output = scratch.path().join("bundle"); + for inventory in [ + None, + Some(serde_json::Value::Null), + Some(serde_json::json!({})), + Some(serde_json::json!("register-business")), + Some(serde_json::json!([7])), + ] { + manifest(&built, |value| match &inventory { + None => { + assert!(value.as_object_mut().unwrap().remove("functions").is_some()); + } + Some(inventory) => value["functions"] = inventory.clone(), + }); + let message = refusal(&built, &output); + assert!(message.contains("function"), "{inventory:?}: {message}"); + assert!(!output.exists(), "{inventory:?}: {message}"); + } + } + + #[test] + fn refuses_a_page_only_manifest_over_the_byte_limit_before_creating_output() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_page_only_preview(scratch.path()); + let output = scratch.path().join("bundle"); + let path = built.join(MANIFEST); + let mut bytes = fs::read(&path).unwrap(); + bytes.resize(MAXIMUM_MANIFEST_BYTES as usize + 1, b' '); + fs::write(path, bytes).unwrap(); + + let message = refusal(&built, &output); + + assert!( + message.contains(&format!("exceeds {MAXIMUM_MANIFEST_BYTES} bytes")), + "{message}" + ); + assert!(!output.exists(), "{message}"); + } + + #[test] + fn hashes_every_chunk_of_an_auxiliary_file_as_exported() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + let output = scratch.path().join("bundle"); + let auxiliary = "project/web/dist/large.bin"; + let bytes = vec![0x61; 256 * 1024 + 1]; + fs::write(built.join(auxiliary), &bytes).unwrap(); + + let exported = export_bundle(&built, &output).unwrap(); + let pairs: Vec<_> = exported + .files + .iter() + .map(|path| { + ( + path, + hex(&Sha256::digest(fs::read(output.join(path)).unwrap())), + ) + }) + .collect(); + assert_eq!( + exported.digest, + hex(&Sha256::digest(serde_json::to_vec(&pairs).unwrap())) + ); + assert_eq!(fs::read(output.join(auxiliary)).unwrap(), bytes); + } + + #[test] + fn two_exports_of_one_build_are_identical() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + let first = export_bundle(&built, &scratch.path().join("first")).unwrap(); + let second = export_bundle(&built, &scratch.path().join("second")).unwrap(); + assert_eq!(first.digest, second.digest); + assert_eq!( + tree(&scratch.path().join("first")), + tree(&scratch.path().join("second")) + ); + } + + #[test] + fn refuses_an_existing_output_and_leaves_it_untouched() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + let directory = scratch.path().join("existing-directory"); + fs::create_dir(&directory).unwrap(); + let file = scratch.path().join("existing-file"); + fs::write(&file, "kept").unwrap(); + let link = scratch.path().join("dangling-link"); + std::os::unix::fs::symlink(scratch.path().join("absent"), &link).unwrap(); + + for output in [&directory, &file, &link] { + for message in [ + format!("{:#}", require_new_output(output).unwrap_err()), + refusal(&built, output), + ] { + assert!(message.contains("already exists"), "{message}"); + } + } + assert_eq!(fs::read_dir(&directory).unwrap().count(), 0); + assert_eq!(fs::read_to_string(&file).unwrap(), "kept"); + assert!(!scratch.path().join("absent").exists()); + require_new_output(&scratch.path().join("new")).unwrap(); + } + + #[test] + fn refuses_a_manifest_that_names_files_outside_the_bundle() { + for (edit, expected) in [ + ( + json_edit("staticOutput", serde_json::json!("/etc")), + "staticOutput", + ), + ( + json_edit("staticOutput", serde_json::json!("project/../..")), + "staticOutput", + ), + ( + json_edit("staticOutput", serde_json::json!("")), + "staticOutput", + ), + ( + json_edit("functions", serde_json::json!(["../escape"])), + "function", + ), + ( + json_edit("declarationDigest", serde_json::json!(7)), + "declarationDigest", + ), + ] { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + manifest(&built, edit); + let output = scratch.path().join("bundle"); + let message = refusal(&built, &output); + assert!(message.contains(expected), "{message}"); + assert!(!output.exists(), "{message}"); + } + } + + fn json_edit( + member: &'static str, + value: serde_json::Value, + ) -> impl FnOnce(&mut serde_json::Value) { + move |manifest| manifest[member] = value + } + + #[test] + fn removes_its_partial_output_when_a_write_fails_after_the_directory_exists() { + // A function named twice writes its file twice; the second write + // fails after the output directory and earlier files exist. + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + manifest(&built, |manifest| { + manifest["functions"] = serde_json::json!(["register-business", "register-business"]); + }); + let output = scratch.path().join("bundle"); + assert!(refusal(&built, &output).contains("functions/register-business.mjs")); + assert!(!output.exists()); + } + + #[test] + fn refuses_a_linked_manifest_or_function_without_following_it() { + for linked in ["manifest.json", "functions/register-business.mjs"] { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + let target = scratch.path().join("elsewhere"); + fs::copy(built.join(linked), &target).unwrap(); + fs::remove_file(built.join(linked)).unwrap(); + std::os::unix::fs::symlink(&target, built.join(linked)).unwrap(); + let output = scratch.path().join("bundle"); + let message = refusal(&built, &output); + assert!(message.contains(linked), "{linked}: {message}"); + assert!(!output.exists(), "{linked}"); + } + } + + #[test] + fn reports_a_missing_parent_as_such_before_anything_is_built() { + let scratch = tempfile::tempdir().unwrap(); + let output = scratch.path().join("missing-parent/bundle"); + let early = format!("{:#}", require_new_output(&output).unwrap_err()); + assert!(early.contains("parent"), "{early}"); + assert!(!early.contains("already exists"), "{early}"); + let built = built_preview(scratch.path()); + let late = refusal(&built, &output); + assert!(!late.contains("already exists"), "{late}"); + } + + #[test] + fn refuses_a_link_or_a_missing_function_and_removes_its_partial_output() { + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + let page = built.join("project/web/dist/app.js"); + fs::remove_file(&page).unwrap(); + std::os::unix::fs::symlink("/etc/hosts", &page).unwrap(); + let output = scratch.path().join("linked"); + assert!(refusal(&built, &output).contains("regular files")); + assert!(!output.exists()); + + let scratch = tempfile::tempdir().unwrap(); + let built = built_preview(scratch.path()); + fs::remove_file(built.join("functions/register-business.mjs")).unwrap(); + let output = scratch.path().join("missing"); + assert!(refusal(&built, &output).contains("register-business")); + assert!(!output.exists()); + } +} diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 35fca0986d..db1376777f 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -849,8 +849,8 @@ impl<'a> ProductRunner<'a> { "productId": build.product.id, "profile": build.product.profile, "declarationDigest": build.declaration_digest, - "functionHost": self.function_host_input()?, }); + self.add_preview_function_host(&mut run_preview)?; if let Some(file) = &authorization.single { run_preview["authorizationFile"] = json!(file); } else { @@ -1982,7 +1982,14 @@ impl<'a> ProductRunner<'a> { /// 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() { + if self + .input + .plan + .preview + .as_ref() + .is_none_or(|preview| preview.function_names().next().is_none()) + || self.function_host.is_some() + { return Ok(()); } let state = self @@ -2021,20 +2028,19 @@ impl<'a> ProductRunner<'a> { 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.") + format!("Coordinator connection {id} calls a service function, which needs the preview function host. Declare preview.functions or preview.coordinatorFunctions 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() + .function_names() .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." + "Coordinator connection {id} binds function {function}, which the preview does not serve. Declare it in service.yaml functions and select it in dev.yaml preview.functions or preview.coordinatorFunctions." ); let object = connection .as_object_mut() @@ -2049,7 +2055,23 @@ impl<'a> ProductRunner<'a> { Ok(()) } - /// The preview run input's function host member. + /// Include the host reservation when the preview serves any selected function. + fn add_preview_function_host(&self, run_preview: &mut Value) -> Result<()> { + if self + .input + .plan + .preview + .as_ref() + .context("missing preview routes")? + .function_names() + .next() + .is_some() + { + run_preview["functionHost"] = self.function_host_input()?; + } + Ok(()) + } + fn function_host_input(&self) -> Result { let host = self .function_host @@ -5808,12 +5830,11 @@ mod tests { fs::write(root.join(name), "fixture").unwrap(); } let node = root.join("node"); - write_private( + crate::write_executable_fixture( &node, - format!("#!/usr/bin/env bash\nset -euo pipefail\nif [[ $1 == --version ]]; then\n printf '{node_version}\\n'\nelse\n printf 'fixture-prepare 1.0\\n'\nfi\n").as_bytes(), + &format!("#!/usr/bin/env bash\nset -euo pipefail\nif [[ $1 == --version ]]; then\n printf '{node_version}\\n'\nelse\n printf 'fixture-prepare 1.0\\n'\nfi\n"), ) .unwrap(); - fs::set_permissions(&node, fs::Permissions::from_mode(0o700)).unwrap(); let plan: ApplicationPlan = serde_json::from_value(json!({ "client": "browser-client", "callbackPath": "/callback", "healthPath": "/health", "entry": "entry.js", "prepare": "prepare.js", @@ -6115,7 +6136,7 @@ mod tests { let error = preflight_application_with_node(root.path(), &plan, &node) .err() .unwrap(); - assert!(error.to_string().contains("Node 24 or newer"), "{error}"); + assert!(error.to_string().contains("Node 24 or newer"), "{error:#}"); } const APPLICATION_FIXTURE_PORT: &str = "APPLICATION_FIXTURE_PORT"; @@ -6507,6 +6528,61 @@ mod tests { assert!(TcpListener::bind((Ipv4Addr::LOCALHOST, port)).is_err()); } + #[test] + fn a_coordinator_only_preview_reserves_the_host_and_binds_the_connection() { + let root = tempfile::tempdir().unwrap(); + let package = function_project(root.path()); + let terminate = AtomicBool::new(false); + let mut input = function_runner_input(Some(&[])); + input.plan.preview = Some( + serde_json::from_value(json!({ + "actor": "tester", "page": "/", "breg": {}, "functions": [], + "coordinatorFunctions": ["draft-notice"] + })) + .unwrap(), + ); + let mut runner = ProductRunner::new(Arc::new(input), root.path(), &terminate).unwrap(); + runner.reserve_function_host().unwrap(); + let host = runner.function_host.as_ref().unwrap(); + let mut run_preview = json!({}); + runner.add_preview_function_host(&mut run_preview).unwrap(); + assert_eq!( + run_preview["functionHost"], + json!({"port": host.port, "keyFile": root.path().join(FUNCTION_HOST_KEY)}) + ); + let config = coordinator_config(&runner, root.path(), &package).unwrap(); + let drafts = &config["connections"]["drafts"]; + assert_eq!( + drafts["baseUrl"], + format!("http://127.0.0.1:{}/", host.port) + ); + assert_eq!(drafts["hostKeyRef"], secret_ref(FUNCTION_HOST_KEY)); + assert!(drafts.get("authorization").is_none()); + } + + #[test] + fn a_function_free_preview_skips_host_reservation_and_refuses_a_coordinator_binding() { + 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(&[]))), + root.path(), + &terminate, + ) + .unwrap(); + runner.reserve_function_host().unwrap(); + let mut run_preview = json!({}); + runner.add_preview_function_host(&mut run_preview).unwrap(); + assert!(run_preview.get("functionHost").is_none()); + assert!(runner.function_host.is_none()); + assert!(!root.path().join(FUNCTION_HOST_KEY).exists()); + let error = coordinator_config(&runner, root.path(), &package) + .unwrap_err() + .to_string(); + assert!(error.contains("preview.functions"), "{error}"); + } + #[test] fn a_service_function_the_preview_does_not_serve_is_refused() { let root = tempfile::tempdir().unwrap(); @@ -6692,7 +6768,7 @@ mod tests { fn breg_config_binds_two_url_hook_destinations_from_the_inventory() { let root = tempfile::tempdir().unwrap(); let tool = root.path().join("bregctl"); - fs::write(&tool, r#"#!/bin/sh + crate::write_executable_fixture(&tool, r#"#!/bin/sh [ "$1 $2 $3 $4" = "--format json explain events" ] || exit 9 cat <<'INVENTORY' {"ok":true,"explanation":{"deliveries":[ @@ -6702,8 +6778,6 @@ cat <<'INVENTORY' ]}} INVENTORY "#).unwrap(); - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); let mut input = breg_input(false); input.binaries.insert( Product::Breg, @@ -6798,14 +6872,11 @@ INVENTORY #[test] fn external_hook_ids_must_match_the_inventory_exactly() { - use std::os::unix::fs::PermissionsExt; - let root = tempfile::tempdir().unwrap(); let tool = root.path().join("bregctl"); - fs::write(&tool, r#"#!/bin/sh + crate::write_executable_fixture(&tool, r#"#!/bin/sh printf '%s' '{"ok":true,"explanation":{"deliveries":[{"destinationId":"declared","classificationCeiling":"public","attemptTimeoutMs":2000,"maximumAttempts":4}]}}' "#).unwrap(); - fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap(); let mut input = breg_input(false); input.binaries.insert( Product::Breg, diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index 9a2d48a022..7d0936cfe1 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -323,6 +323,23 @@ enum DevCommand { #[arg(long, value_name = "DURATION")] ttl: Option, }, + /// Build a project's service preview and export the bundle a host serves outside rstack dev. + /// + /// Writes exactly the preview manifest, each compiled function and every file of the + /// manifest's static output into a new directory, and prints the bundle digest a + /// deployment pins with the declaration digest of the checked service.yaml. Starts + /// no service. + #[command( + after_help = "Example:\n rstack dev export-preview ./my-service --output ./preview-bundle" + )] + ExportPreview { + /// Project directory containing dev.yaml with preview and its service.yaml. + #[arg(value_name = "PROJECT")] + project: PathBuf, + /// New directory for the bundle. An existing path is refused. + #[arg(long, value_name = "DIRECTORY")] + output: PathBuf, + }, /// Report the state of a development environment. #[command(after_help = "Example:\n rstack dev status 0123456789abcdef0123456789abcdef")] Status { @@ -1980,6 +1997,15 @@ impl DevNeeds { } } + /// `export-preview` checks and builds with every product's tool, and + /// starts no service. + fn export_preview(project: &std::path::Path) -> Self { + Self { + products: plan_dev_products(project), + services: false, + } + } + /// The source binary overrides the action needs, the host's tool first. fn variables(&self) -> Vec<&'static str> { self.products @@ -2095,6 +2121,7 @@ fn admit_dev(action: &DevCommand, format: ReportFormat) -> Result<(), CliFailure .. } | DevCommand::Start { .. } | DevCommand::Issuer { .. } + | DevCommand::ExportPreview { .. } ) { return Ok(()); } @@ -2116,7 +2143,10 @@ fn admit_dev(action: &DevCommand, format: ReportFormat) -> Result<(), CliFailure Ok(_) => return Ok(()), }; - if matches!(action, DevCommand::Start { .. } | DevCommand::Issuer { .. }) { + if matches!( + action, + DevCommand::Start { .. } | DevCommand::Issuer { .. } | DevCommand::ExportPreview { .. } + ) { return Err(format!("{code}: {message}. {fix}").into()); } @@ -2216,6 +2246,13 @@ fn dispatch_dev(cli: &Cli, action: &DevCommand, format: ReportFormat) -> Result< None, DevNeeds::check(project), ), + DevCommand::ExportPreview { project, output } => ( + "export-preview", + vec![option("output", output.as_os_str())], + project.as_os_str(), + None, + DevNeeds::export_preview(project), + ), DevCommand::Status { run_id } => ( "status", Vec::new(), diff --git a/crates/registry-rstack/tests/dev.rs b/crates/registry-rstack/tests/dev.rs index 2126544891..258d4d58d0 100644 --- a/crates/registry-rstack/tests/dev.rs +++ b/crates/registry-rstack/tests/dev.rs @@ -453,6 +453,56 @@ fn source_start_passes_a_built_application_root_to_the_runner() { ); } +#[test] +fn export_preview_passes_its_output_and_needs_only_the_product_tools() { + let tools = SourceTools::new(); + write_plan(&tools.project, &["breg"]); + let output_dir = tools.project.join("bundle"); + for (format, options) in [ + (&[][..], vec![format!("--output={}", output_dir.display())]), + ( + &["--format", "json"][..], + vec![ + format!("--output={}", output_dir.display()), + "--json".to_owned(), + ], + ), + ] { + let output = tools + .empty_command() + .args(format) + .args(["dev", "export-preview"]) + .arg(&tools.project) + .arg("--output") + .arg(&output_dir) + .env("RSTACK_BREGCTL_BIN", &tools.bregctl) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let options: Vec<&str> = options.iter().map(String::as_str).collect(); + assert_eq!( + hosted(&output), + ( + "bregctl".to_owned(), + runner_arguments("export-preview", &options, &tools.project) + ) + ); + // No runtime is resolved: the export starts no service. + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("breg:\n"), "{stdout}"); + } + + let missing = tools + .empty_command() + .args(["dev", "export-preview"]) + .arg(&tools.project) + .env("RSTACK_BREGCTL_BIN", &tools.bregctl) + .output() + .unwrap(); + assert_eq!(missing.status.code(), Some(2), "{missing:?}"); + assert!(String::from_utf8_lossy(&missing.stderr).contains("--output")); +} + #[test] fn dev_actions_encode_the_public_contract_and_launcher_json_format() { let tools = SourceTools::new(); diff --git a/crates/registry-scheduling/src/config.rs b/crates/registry-scheduling/src/config.rs index ce061cf4d2..dc462df563 100644 --- a/crates/registry-scheduling/src/config.rs +++ b/crates/registry-scheduling/src/config.rs @@ -2156,7 +2156,7 @@ impl RuntimeConfigError { Self::DatabaseTransport(DatabaseTransportError::TestOnlyPlaintext) => { "database.testOnlyPlaintext" } - Self::DatabaseTransport(_) => "database.transport", + Self::DatabaseTransport(error) => error.database_field(), Self::InvalidAuditDestination(error) => audit_field(error), Self::HookDestinationInventoryMismatch => "destinations.hooks", Self::Policy(_) | Self::PolicyUnreadable | Self::PolicyChanged => { diff --git a/crates/registry-scheduling/src/store.rs b/crates/registry-scheduling/src/store.rs index ead4b590e5..917c5a5dda 100644 --- a/crates/registry-scheduling/src/store.rs +++ b/crates/registry-scheduling/src/store.rs @@ -36,7 +36,6 @@ use registry_platform_config::{DatabaseTransport, DatabaseTransportError, DevelopmentWitness}; use std::collections::HashMap; -use std::str::FromStr; #[cfg(feature = "postgres-test")] use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -992,7 +991,7 @@ impl PostgresStore { config, secrets, witness, - "database.runtimeUrlRef", + registry_platform_config::DatabaseMember::RuntimeUrl, &config.runtime_url_ref, ) } @@ -1006,7 +1005,7 @@ impl PostgresStore { config, secrets, witness, - "database.migrationUrlRef", + registry_platform_config::DatabaseMember::MigrationUrl, &config.migration_url_ref, ) } @@ -1015,11 +1014,15 @@ impl PostgresStore { config: &DatabaseConfig, secrets: &SecretResolver, witness: Option<&DevelopmentWitness>, - field: &'static str, + member: registry_platform_config::DatabaseMember, reference: &str, ) -> Result { let protected = secrets.resolve(reference).map_err(|error| { - StoreError::SecretConfiguration(describe_secret_failure(field, reference, &error)) + StoreError::SecretConfiguration(describe_secret_failure( + &format!("database.{member}"), + reference, + &error, + )) })?; let url = std::str::from_utf8(protected.expose_secret()) .map_err(|_| StoreError::Configuration)?; @@ -1027,6 +1030,7 @@ impl PostgresStore { config, url, witness, + member, ®istry_platform_config::resolve_database_host, )?; let manager_config = ManagerConfig { @@ -5702,20 +5706,8 @@ fn tls_connector( &error, )) })?; - let mut roots = rustls::RootCertStore::empty(); - use rustls::pki_types::pem::PemObject as _; - let mut count = 0usize; - for certificate in - rustls::pki_types::CertificateDer::pem_slice_iter(certificate.expose_secret()) - { - roots - .add(certificate.map_err(|_| StoreError::Configuration)?) - .map_err(|_| StoreError::Configuration)?; - count += 1; - } - if count == 0 { - return Err(StoreError::Configuration); - } + let roots = registry_platform_postgres::pem_root_store(certificate.expose_secret()) + .map_err(|_| StoreError::Configuration)?; let client = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); @@ -5852,9 +5844,11 @@ fn driver_config( config: &DatabaseConfig, url: &str, witness: Option<&DevelopmentWitness>, + member: registry_platform_config::DatabaseMember, resolve: ®istry_platform_config::HostResolver, ) -> Result<(PgConfig, bool), StoreError> { - let postgres = PgConfig::from_str(url).map_err(|_| StoreError::Configuration)?; + let postgres = registry_platform_postgres::parse_runtime_url(url, config, witness) + .map_err(|error| error.at_url(member))?; if postgres.get_user().is_none() || postgres.get_dbname().is_none() { return Err(StoreError::Configuration); } @@ -5876,6 +5870,30 @@ mod driver_config_tests { use super::*; + #[test] + fn verify_full_reaches_the_verified_tls_pool() { + let config = registry_platform_config::DatabaseConfig { + runtime_url_ref: "secret:env/DB_RUNTIME".to_owned(), + migration_url_ref: "secret:env/DB_MIGRATION".to_owned(), + ca_bundle_ref: None, + test_only_plaintext: false, + transport: None, + }; + let (postgres, tls) = driver_config( + &config, + "postgresql://app@db.example/registry?sslmode=verify-full", + None, + registry_platform_config::DatabaseMember::RuntimeUrl, + &|_| panic!("TLS retains the name for certificate verification"), + ) + .unwrap(); + assert!(tls); + assert_eq!( + postgres.get_ssl_mode(), + tokio_postgres::config::SslMode::Require + ); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping @@ -5898,6 +5916,7 @@ mod driver_config_tests { &config, "postgresql://app@localhost:5433/scheduling", None, + registry_platform_config::DatabaseMember::RuntimeUrl, &fixed, ) .unwrap(); diff --git a/crates/registry-scheduling/tests/postgres_commitments.rs b/crates/registry-scheduling/tests/postgres_commitments.rs index 19d4c279ae..daf57060be 100644 --- a/crates/registry-scheduling/tests/postgres_commitments.rs +++ b/crates/registry-scheduling/tests/postgres_commitments.rs @@ -892,6 +892,68 @@ fn token(mut claims: Value) -> String { jsonwebtoken::encode(&header, &claims, &EncodingKey::from_secret(SECRET)).unwrap() } +#[tokio::test] +async fn catalogue_fault_controls_name_the_claim_or_setting_to_change() { + use tracing::instrument::WithSubscriber as _; + let fixture = fixture().await; + let app = fixture.http_declared(registry_platform_config::Posture::Development); + for (field, value, status, check, guidance) in [ + ( + "aud", + json!("urn:other"), + 401, + "token-audience", + "aud claim", + ), + ("exp", json!(1), 401, "token-time", "exp claim"), + ( + "registry_scopes", + json!("unrelated"), + 403, + "scope", + "scheduling-read", + ), + ] { + let mut claims = json!({ + "sub": "principal-read", + "azp": CLIENT, + "registry_scopes": "scheduling-read", + "registry_actor_kind": "service", + }); + claims[field] = value; + let logs = registry_platform_testing::CapturedDiagnosticLogs::default(); + let (actual, body) = send( + app.clone(), + "GET".into(), + "/v1/locations".into(), + token(claims), + None, + None, + ) + .with_subscriber(logs.subscriber()) + .await; + assert_eq!(actual.as_u16(), status, "{field}"); + assert_eq!(body["failedCheck"], check, "{field}"); + let text = logs.text(); + let records: Vec = text + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|record| record["fields"]["decision"] == "refused") + .collect(); + assert_eq!(records.len(), 1, "{field}"); + let fields = &records[0]["fields"]; + assert_eq!(fields["trace_id"], body["traceId"], "{field}"); + assert_eq!(fields["failed_check"], check, "{field}"); + if check == "scope" { + assert_eq!(fields["required_scope"], guidance); + } else { + assert!(fields["remedy"] + .as_str() + .is_some_and(|remedy| remedy.contains(guidance))); + } + } +} + fn reader_token() -> String { token(json!({ "sub": "principal-read", diff --git a/crates/registry-schedulingctl/src/lib.rs b/crates/registry-schedulingctl/src/lib.rs index d45787e680..2c2cd30434 100644 --- a/crates/registry-schedulingctl/src/lib.rs +++ b/crates/registry-schedulingctl/src/lib.rs @@ -1092,7 +1092,7 @@ fn classify_failure(error: &anyhow::Error) -> (u8, Value) { "severity": "error", "code": error.code(), "artifact": "database", - "path": "/database/transport", + "path": error.database_pointer(), "message": error.to_string(), "suggestedAction": error.suggested_action(), }), diff --git a/crates/registry-schedulingctl/src/provision.rs b/crates/registry-schedulingctl/src/provision.rs index 7190cef0ab..f651a3bb56 100644 --- a/crates/registry-schedulingctl/src/provision.rs +++ b/crates/registry-schedulingctl/src/provision.rs @@ -6,9 +6,10 @@ use std::path::Path; -use registry_platform_config::{describe_secret_failure, DatabaseMember}; +use registry_platform_config::{DatabaseMember, SecretError}; use registry_platform_provision::{ - provision_transport, ProductDatabase, ProvisionInput, SchemaLayout, + provision_transport, read_ca_bundle, secret_refusal, secret_refusal_code, url_not_text_refusal, + ProductDatabase, ProvisionInput, SchemaLayout, }; use registry_platform_yaml::Diagnostic; use registry_scheduling::config::{startup_report, RuntimeConfig}; @@ -33,6 +34,17 @@ fn refused(code: &str, path: &str, message: String, action: &str) -> Box Vec { + diagnostic.artifact = Some(SCHEDULING_RUNTIME_KIND.to_owned()); + vec![diagnostic] +} + +/// The shared refusal of a database member's secret or public document. +fn secret_refused(member: DatabaseMember, error: &SecretError) -> Vec { + in_runtime_file(secret_refusal("database", member, error)) +} + /// Reads the runtime file exactly as `apply` does and resolves the two /// database URLs and the CA behind `database.caBundleRef`. pub(crate) fn load( @@ -68,35 +80,22 @@ pub(crate) fn load( .resolver(config.development_witness()) .map_err(|error| { refuse( - "config.refused", + secret_refusal_code(&error), "/secretProviders", error.to_string(), - "Correct secretProviders in the runtime file, then run provision again.", + error.suggested_action(), ) })?; 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), - error.suggested_action(), - ) - }) + member + .read(&secrets, reference) + .map_err(|error| secret_refused(member, &error)) }; 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( - "config.refused", - &format!("/database/{member}"), - format!("database.{member} is not UTF-8 text"), - "Put a PostgreSQL URL in the secret, then run provision again.", - ) - }) + .map_err(|_| in_runtime_file(url_not_text_refusal("database", member))) }; let migration_url = url( DatabaseMember::MigrationUrl, @@ -107,9 +106,11 @@ pub(crate) fn load( .database .ca_bundle_ref .as_deref() - .map(|reference| resolve(DatabaseMember::CaBundle, reference)) - .transpose()? - .map(|secret| secret.expose_secret().to_vec()); + .map(|reference| { + read_ca_bundle(&secrets, "database", reference) + .map_err(|refused| in_runtime_file(*refused)) + }) + .transpose()?; Ok(ProvisionInput { product: product(), migration_url, diff --git a/crates/registry-schedulingctl/tests/provision_cli.rs b/crates/registry-schedulingctl/tests/provision_cli.rs index 05b4caea6e..ef758c90fa 100644 --- a/crates/registry-schedulingctl/tests/provision_cli.rs +++ b/crates/registry-schedulingctl/tests/provision_cli.rs @@ -289,10 +289,11 @@ fn refusal(runtime: &str) -> (Option, serde_json::Value, String) { fn assert_refused_at( (code, diagnostic, output): (Option, serde_json::Value, String), + expected: &str, path: &str, ) { assert_eq!(code, Some(1), "{output}"); - assert_eq!(diagnostic["code"], "config.refused", "{output}"); + assert_eq!(diagnostic["code"], expected, "{output}"); assert_eq!(diagnostic["path"], path, "{output}"); for secret in [MIGRATION_PASSWORD, RUNTIME_PASSWORD] { assert!(!output.contains(secret), "the refusal holds no password"); @@ -304,7 +305,11 @@ fn a_missing_runtime_url_secret_is_refused_without_a_password() { let directory = scratch(); let runtime = write_runtime(directory.path()); std::fs::remove_file(directory.path().join("secrets/runtime-database-url")).unwrap(); - assert_refused_at(refusal(&runtime), "/database/runtimeUrlRef"); + assert_refused_at( + refusal(&runtime), + "platform.provision.secret-unavailable", + "/database/runtimeUrlRef", + ); } #[test] @@ -312,7 +317,11 @@ fn a_missing_migration_url_secret_is_refused_without_a_password() { let directory = scratch(); let runtime = write_runtime(directory.path()); std::fs::remove_file(directory.path().join("secrets/migration-database-url")).unwrap(); - assert_refused_at(refusal(&runtime), "/database/migrationUrlRef"); + assert_refused_at( + refusal(&runtime), + "platform.provision.secret-unavailable", + "/database/migrationUrlRef", + ); } #[test] @@ -323,7 +332,32 @@ fn a_runtime_url_secret_that_is_not_text_is_refused_without_a_password() { let mut bytes = RUNTIME_PASSWORD.as_bytes().to_vec(); bytes.extend([0xff, 0xfe]); std::fs::write(&path, bytes).unwrap(); - assert_refused_at(refusal(&runtime), "/database/runtimeUrlRef"); + assert_refused_at( + refusal(&runtime), + "platform.provision.secret-value-invalid", + "/database/runtimeUrlRef", + ); +} + +#[test] +fn a_ca_bundle_without_a_certificate_is_refused_in_print_mode() { + let directory = scratch(); + let runtime = write_runtime(directory.path()); + let bundle = directory.path().join("secrets/postgres-ca.pem"); + std::fs::write(&bundle, "a bundle that holds no certificate\n").unwrap(); + std::fs::set_permissions(&bundle, std::fs::Permissions::from_mode(0o644)).unwrap(); + let document = std::fs::read_to_string(&runtime).unwrap(); + let with_ca = document.replace( + " migrationUrlRef: secret:file/migration-database-url\n", + " migrationUrlRef: secret:file/migration-database-url\n caBundleRef: secret:file/postgres-ca.pem\n", + ); + assert_ne!(document, with_ca, "the runtime file names the CA bundle"); + std::fs::write(&runtime, with_ca).unwrap(); + assert_refused_at( + refusal(&runtime), + "platform.provision.ca-bundle-no-certificate", + "/database/caBundleRef", + ); } #[test] @@ -337,5 +371,9 @@ fn a_missing_ca_bundle_secret_is_refused_without_a_password() { ); assert_ne!(document, with_ca, "the runtime file names the CA bundle"); std::fs::write(&runtime, with_ca).unwrap(); - assert_refused_at(refusal(&runtime), "/database/caBundleRef"); + assert_refused_at( + refusal(&runtime), + "platform.provision.secret-unavailable", + "/database/caBundleRef", + ); } diff --git a/crates/registry-session/README.md b/crates/registry-session/README.md index a301d4453a..3920e96751 100644 --- a/crates/registry-session/README.md +++ b/crates/registry-session/README.md @@ -11,7 +11,9 @@ pending sign-ins live only in memory, in one replica. A restart loses them. 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. +`rstack` does not install it. +The numbered image roster includes `ghcr.io/registrystack/registry-session` +from v0.52.0. Use the digest from the verified release manifest. ## Configuration and commands diff --git a/crates/registry-stack-client-node/casework/client.d.ts b/crates/registry-stack-client-node/casework/client.d.ts index 6056b0bcbb..baec2f4f4d 100644 --- a/crates/registry-stack-client-node/casework/client.d.ts +++ b/crates/registry-stack-client-node/casework/client.d.ts @@ -200,6 +200,7 @@ export class CaseworkClientError extends Error { */ readonly outcomeUnknown: boolean readonly code?: CaseworkProblemCode + readonly problemType?: string readonly detail?: string readonly status?: SafeInteger readonly traceId?: string diff --git a/crates/registry-stack-client-node/casework/client.js b/crates/registry-stack-client-node/casework/client.js index ddc2380134..7d60ada4f3 100644 --- a/crates/registry-stack-client-node/casework/client.js +++ b/crates/registry-stack-client-node/casework/client.js @@ -13,8 +13,19 @@ class CaseworkClientError extends Error { this.name = 'CaseworkClientError'; this.kind = envelope.kind; this.outcomeUnknown = envelope.outcomeUnknown === true; - for (const field of ['code', 'detail', 'status', 'traceId', 'validation', 'transportKind', 'protocolFailure']) { - if (envelope[field] !== undefined && envelope[field] !== null) this[field] = envelope[field]; + for (const field of ['code', 'problemType', 'detail', 'status', 'traceId', 'validation', 'transportKind', 'protocolFailure']) { + if (envelope[field] === undefined || envelope[field] === null) continue; + // Keep remote validation metadata and future identifiers available + // without putting them in default inspection or JSON output. + if (field === 'validation' || (envelope.unknownProblemCode && (field === 'code' || field === 'problemType'))) { + Object.defineProperty(this, field, { + value: envelope[field], + writable: true, + configurable: true, + }); + } else { + this[field] = envelope[field]; + } } } } diff --git a/crates/registry-stack-client-node/compatibility.json b/crates/registry-stack-client-node/compatibility.json index d75f5412ee..79181a02b3 100644 --- a/crates/registry-stack-client-node/compatibility.json +++ b/crates/registry-stack-client-node/compatibility.json @@ -10,8 +10,8 @@ "compatibleServerPatchLine": "0.51.x", "responseCompatibility": { "additiveObjectMembers": "ignored-after-duplicate-key-rejection", - "unknownProblemCodes": "http-status-only", - "proof": "registry-discovery-client::client::tests::real_client_ignores_additive_response_members_at_every_response_level" + "unknownProblemCodes": "retained-with-problem-type-when-valid", + "proof": "registry-discovery-client::client::tests::shared_raw_http_responses_preserve_the_reader_contract" } } } diff --git a/crates/registry-stack-client-node/discovery/client.d.ts b/crates/registry-stack-client-node/discovery/client.d.ts index e4fd04d0bc..a0c8e3fbef 100644 --- a/crates/registry-stack-client-node/discovery/client.d.ts +++ b/crates/registry-stack-client-node/discovery/client.d.ts @@ -128,6 +128,12 @@ export class DiscoveryClientError extends Error { readonly kind: DiscoveryClientErrorKind; readonly status?: number; readonly problem?: string; + /** The Discovery problem type of a problem this client does not recognise. */ + readonly problemType?: string; + /** A known problem's code, or the code an unrecognised problem supplied, when it supplied one. */ + readonly code?: string; + /** The validated trace identifier of an unrecognized Problem, when available. */ + readonly traceId?: string; readonly transportKind?: string; } diff --git a/crates/registry-stack-client-node/discovery/client.js b/crates/registry-stack-client-node/discovery/client.js index 8c06f7ecea..e299b23b43 100644 --- a/crates/registry-stack-client-node/discovery/client.js +++ b/crates/registry-stack-client-node/discovery/client.js @@ -15,8 +15,19 @@ class DiscoveryClientError extends Error { super(envelope.message); this.name = 'DiscoveryClientError'; this.kind = envelope.kind; - for (const field of ['status', 'problem', 'transportKind']) { - if (envelope[field] !== undefined && envelope[field] !== null) this[field] = envelope[field]; + for (const field of ['status', 'problem', 'problemType', 'code', 'traceId', 'transportKind']) { + const value = envelope[field]; + if (value === undefined || value === null) continue; + if (field === 'problemType' || (field === 'code' && envelope.problemType !== undefined)) { + Object.defineProperty(this, field, { + value, + configurable: true, + enumerable: false, + writable: true, + }); + } else { + this[field] = value; + } } } } diff --git a/crates/registry-stack-client-node/evidence/client.d.ts b/crates/registry-stack-client-node/evidence/client.d.ts index ac494defca..67fe3a317e 100644 --- a/crates/registry-stack-client-node/evidence/client.d.ts +++ b/crates/registry-stack-client-node/evidence/client.d.ts @@ -389,10 +389,11 @@ export interface EvidenceRequestBatchSpec { * * `kind` is always present. The rest are present only when the underlying * failure carries them: - * - `status`: `denied`, `invalid-request`, `unavailable`, `protocol`, and any `token` failure whose `tokenKind` - * is `protocol` - * - `code`: `denied`, `invalid-request`, `unavailable`, `protocol` (optional), `verification`, and any `token` - * failure whose `tokenKind` is `refused` + * - `status`: `denied`, `invalid-request`, `unavailable`, `protocol`, a + * `not-available` status fallback, or a `token` failure with `tokenKind` of `protocol` + * - `code`: a Problem code, a verifier failure kind, or a token refusal code + * - `problemType`: the validated type URI for a classified Problem, including + * future Problems that use status fallback * - `traceId`: `denied`, `not-available`, `invalid-request`, `unavailable`, `protocol` (all optional) * - `retryAfterSeconds`: `denied`, `protocol` (both optional) * - `transportKind`: `transport`, and any `token` failure whose `tokenKind` @@ -403,6 +404,7 @@ export declare class EvidenceClientError extends Error { readonly kind: string readonly status?: number readonly code?: string + readonly problemType?: string readonly traceId?: string readonly retryAfterSeconds?: number readonly transportKind?: string diff --git a/crates/registry-stack-client-node/evidence/client.js b/crates/registry-stack-client-node/evidence/client.js index b9c36634bf..799ce4ab1e 100644 --- a/crates/registry-stack-client-node/evidence/client.js +++ b/crates/registry-stack-client-node/evidence/client.js @@ -14,18 +14,27 @@ const native = require('./index'); * `map_client_error`), as properties on a thrown `Error` rather than as JSON * text a caller has to `JSON.parse` out of `.message`. * - * `kind` is always present; `status`, `code`, `traceId`, - * `retryAfterSeconds`, `transportKind`, and `tokenKind` are present only when - * the underlying failure carries them. + * `kind` is always present. `status`, `code`, `problemType`, `traceId`, + * `retryAfterSeconds`, `transportKind`, and `tokenKind` appear when supplied + * by the underlying failure. */ class EvidenceClientError extends Error { constructor(envelope) { super(envelope.message); this.name = 'EvidenceClientError'; this.kind = envelope.kind; + if (envelope.problemType !== undefined) { + // Problem identifiers remain accessible without including them in + // default inspection or serialization of the error. + Object.defineProperties(this, { + code: { value: envelope.code }, + problemType: { value: envelope.problemType }, + }); + } else if (envelope.code !== undefined) { + this.code = envelope.code; + } for (const field of [ 'status', - 'code', 'traceId', 'retryAfterSeconds', 'transportKind', diff --git a/crates/registry-stack-client/compatibility.json b/crates/registry-stack-client/compatibility.json index d75f5412ee..79181a02b3 100644 --- a/crates/registry-stack-client/compatibility.json +++ b/crates/registry-stack-client/compatibility.json @@ -10,8 +10,8 @@ "compatibleServerPatchLine": "0.51.x", "responseCompatibility": { "additiveObjectMembers": "ignored-after-duplicate-key-rejection", - "unknownProblemCodes": "http-status-only", - "proof": "registry-discovery-client::client::tests::real_client_ignores_additive_response_members_at_every_response_level" + "unknownProblemCodes": "retained-with-problem-type-when-valid", + "proof": "registry-discovery-client::client::tests::shared_raw_http_responses_preserve_the_reader_contract" } } } diff --git a/deploy/examples/business-registration/.gitignore b/deploy/examples/business-registration/.gitignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/deploy/examples/business-registration/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/deploy/examples/business-registration/Dockerfile b/deploy/examples/business-registration/Dockerfile index a38bf67221..2a95c99f46 100644 --- a/deploy/examples/business-registration/Dockerfile +++ b/deploy/examples/business-registration/Dockerfile @@ -3,5 +3,7 @@ WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund COPY host.mjs ./ +# Generated by tests/build-host-client.mjs from the sealed project and the pinned client. +COPY --from=host-client host-client.mjs ./ USER node ENTRYPOINT ["node", "/app/host.mjs"] diff --git a/deploy/examples/business-registration/README.md b/deploy/examples/business-registration/README.md index 09e4627685..578e08596d 100644 --- a/deploy/examples/business-registration/README.md +++ b/deploy/examples/business-registration/README.md @@ -1,7 +1,8 @@ # 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 +Registry Session, Envoy, ThunderID, BReg and PostgreSQL. The Node host serves +the function as a holder binding from `@registrystack/client/holder-function`. 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 @@ -10,10 +11,29 @@ internal Docker networks are plain HTTP, as described in 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 +The Node host checks the request against its binding and runs only the +bundle's `prepare` export, over the two registration fields. The host then +calls the existing `register-business` Action with the registrar's token, +through a client generated from the sealed project. The function never +receives the token, the Request or a product client, and its result may name +only the two fields, so it cannot choose another Action or target, or name +who registers the business. The Action declares only those two inputs. Its +plan writes the registering office, `central`, and BReg refuses a registrar +whose verified `registry_office` claim names another office. BReg also applies +its own access profile, issuer and scope rules. The Node host has read-only bundle files and no database or issuer credentials. +The binding minimises the function's arguments. It does not isolate the +function: `prepare` runs in the host's process, and the bundle's top-level +code runs when the host imports it, before the host loads its client. Such +code could read the token on its way to BReg. Serve only reviewed function +code this way. + +For each answer the host logs one line with the outcome class, the attempt key +and the HTTP status, for example +`{"event":"holder-outcome","class":"succeeded","attemptKey":"...","status":200}`. +The line carries no submitted value, Record value or token. + ## Plain HTTP issuer hops The edge terminates issuer TLS at `127.0.0.1:9443`. Behind it, two hops carry @@ -41,23 +61,94 @@ Other reach is wider than the function needs: `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. +- The gateway check for the function route is the network path, not a shared + secret. The host's function listener binds private loopback inside the + upstream namespace. From outside that namespace, only Session's Envoy + reaches it, through the owner-only relay socket. The host serves only + `POST /functions/register-business`, hands it to the binding as + `/api/functions/register-business`, and refuses every other path and method. + It checks only the token's shape: BReg verifies the token when the Action is + called, after `prepare` has run. Any host process running as `REFERENCE_UID` + can connect to the relay sockets directly and make the host run `prepare`. + The other members of the upstream namespace, `breg`, `issuer-ready` and, + with the Casework overlay, `casework` and `casework-seed`, can call the + listener directly too. BReg still verifies every token, so such a caller + gains no registry authority. Session cannot yet add a secret header on an upstream + route, which would let the host tell Envoy's requests from others. + +## Run the browser smoke on a disposable host + +Use the automated runner when you want to verify this recipe from a source +checkout. It exports the business preview with the matching client and starts +the host with the exported directory and the digest rstack prints. It runs the +BReg schema test against its own TLS-backed database, and activates the +sealed package in a second database. It generates temporary certificates and +synthetic identities, starts the reference host, checks the browser receipt, +and tears down its uniquely named Compose project and volumes. The fixed +loopback ports require you to run one profile at a time. + +Use Node.js 24, Python 3 and the Linux prerequisites below. Run the recipe as a +non-root user with passwordless sudo (`sudo -n true` must succeed). Build from +the repository root on Ubuntu 24.04 to match the native runner image. + +```bash +cargo build --locked --release --bins --features registry-breg/runtime \ + -p registry-rstack -p registry-session -p registry-breg -p registry-bregctl \ + -p registry-casework -p registry-caseworkctl +client="$PWD/clients/typescript" +npm --prefix "$client" ci --ignore-scripts --no-audit --no-fund +npm --prefix "$client" run build +node "$client/node_modules/playwright-core/cli.js" install --with-deps chromium + +recipe="$PWD/deploy/examples/business-registration" +bash "$recipe/tests/run-reference.sh" casework "$PWD/target/release" \ + "$client/node_modules/playwright-core/index.mjs" \ + "$client/node_modules/yaml/dist/index.js" "$PWD/reference-casework-receipt.json" +``` + +With `breg` as the first argument, the driver checks the original +two-registrar BReg sign-ins, exact reads, logout, and stale-cookie refusal. +With `casework`, the [Compose overlay](casework/compose.yaml) adds Casework to +the private upstream namespace with its own database roles and package. +The browser checks that a reviewer can read a newly registered business and +the exact seeded review task through one Session sign-in. It compares the +Session subject and cookie across both reads, requires Casework to refuse +the reviewer on an administrator route and the BReg-only citizen on a staff +route, and checks browser requests for Authorization headers. A separate +administrator staffs the queue and a machine client seeds the synthetic work. -## Prepare the deployment inputs +The runner writes only the checked receipt to the path you supply. On a +failure it prints the disposable scratch directory for diagnosis. Keep that +directory private because it holds the fixture credentials and TLS keys. + +## Prepare the BReg deployment inputs manually + +Use the automated runner above for the Casework profile. These manual steps +cover BReg. 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. +`jq` and root access through `sudo` for the ownership step. Exporting the +preview and generating the host client require Node.js 24 with npm. 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. +Use Registry Stack v0.52.0 or later. Stage `breg`, `bregctl` and the +standalone `registry-session` executable from the same release in +`REFERENCE_ARTIFACTS`, and verify each against the release manifest. The +standalone Session executable generates and checks the Envoy configuration. + +Set `REFERENCE_SESSION_DIGEST` to the Session image digest from the same +verified release manifest. To extract the digest, run +`jq -er '.images[] | select(.name == "registry-session") | .digest' < "$RELEASE_MANIFEST"`, +where `RELEASE_MANIFEST` points to the verified release manifest JSON. +Compose requires the digest and uses it to pull the image. + +For development with a locally built Session executable, add +`--file "$RECIPE/compose.local.yaml"` after `compose.yaml` in the Compose +command below. For this overlay, set `REFERENCE_SESSION_DIGEST` to +`sha256:` followed by 64 zeros to satisfy interpolation and prevent the base +recipe from pulling a real image if the overlay is omitted. 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 @@ -68,38 +159,67 @@ per host: the host ports 8443 and 9443 are fixed. | --- | --- | | `REFERENCE_CONFIG` | Private directory with the layout below | | `REFERENCE_ARTIFACTS` | Directory with the verified executables | +| `REFERENCE_SESSION_DIGEST` | `sha256:` digest of the `registry-session` image in the verified release manifest | | `BUSINESS_BUNDLE` | Build output of the business-registration preview | -| `BUSINESS_BUNDLE_SHA256` | Runtime file digest of the reviewed preview build | +| `BUSINESS_BUNDLE_SHA256` | Bundle digest `rstack dev export-preview` printed for the reviewed export | +| `REFERENCE_HOST_CLIENT` | Generated `host-client.mjs` and its `host-client.json` record | + +Export the preview bundle with `rstack dev export-preview`. Set `PREVIEW` to the +`products/platform/examples/service-previews/business-registration` directory +of the release source. Place the matching client archive pinned by the +preview's `package-lock.json` there as `registry-preview-client.tgz`. Set +`BUSINESS_BUNDLE` to a path that does not exist yet. Set `RSTACK_BREGCTL_BIN` +to `$REFERENCE_ARTIFACTS/bregctl` when running without a managed rstack +installation. The command checks and builds the preview without starting a +service, and refuses an existing output path. -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 +npm --prefix "$PREVIEW" ci +rstack --format json dev export-preview "$PREVIEW" --output "$BUSINESS_BUNDLE" \ + | tee export.json +BUSINESS_BUNDLE_SHA256=$(jq -r .bundleDigest export.json) +``` + +Generate the host's `register-business` client. The host image copies it in, +so the image digest binds its bytes, but it never comes from the function +bundle. `tests/build-host-client.mjs` runs `registry-generate` from the +`@registrystack/client` package the preview's `package-lock.json` pins, over +the sealed project in `$PREVIEW/project`, using `bregctl` from the same release +as the serving BReg. It bundles the server client and the holder binding into +`host-client.mjs`. It writes `host-client.json` beside it. The record holds +the client version with the lock's source and integrity, a digest of the +installed client files that ran, the project's file-tree digest, the +`bregctl --version` line and the output digest. Set `REFERENCE_HOST_CLIENT` to +a new private directory. ```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" +export RSTACK_BREGCTL_BIN="$REFERENCE_ARTIFACTS/bregctl" +node "$RECIPE/tests/build-host-client.mjs" "$PREVIEW" "$REFERENCE_HOST_CLIENT" +node "$RECIPE/tests/build-host-client.mjs" --check "$PREVIEW" "$REFERENCE_HOST_CLIENT" ``` -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. +The `--check` run regenerates into a scratch directory and refuses a missing or +stale `host-client.mjs` or `host-client.json`. It proves the client is what +this install, project and `bregctl` generate now. It does not prove where the +install came from beyond the lock's integrity check at `npm ci`, and nothing +compares the image's copy with the record. Run the check again immediately +before every image build. Compose passes the directory to the image build as +the `host-client` build context. + +The bundle holds exactly the preview's `manifest.json`, the compiled +`functions/register-business.mjs` and every file of the manifest's +`staticOutput` directory, including `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. Two exports of the same source give the same +bytes. The bundle digest is the SHA-256 of a compact UTF-8 JSON array of +`["path","sha256"]` pairs, one per bundle file, sorted by the bytes of the path, +and the manifest carries the `declarationDigest` of the checked `service.yaml`. +Derive the digest once from the reviewed export, then include that value in +the instance's input file. The host recomputes the same digest and refuses a +bundle that differs from it: ```bash -bundle_host=$(docker build --quiet "$RECIPE") +bundle_host=$(docker build --quiet --build-context host-client="$REFERENCE_HOST_CLIENT" "$RECIPE") docker run --rm --network none \ --mount "type=bind,source=$BUSINESS_BUNDLE,target=/run/bundle,readonly" \ "$bundle_host" --digest /run/bundle @@ -204,7 +324,7 @@ 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/` | +| `/api/functions/register-business` | `functions=127.0.0.1:8300` | `/functions/register-business` | | `/apply/` | `pages=127.0.0.1:8200` | `/` | ```bash @@ -219,6 +339,21 @@ session=("$REFERENCE_ARTIFACTS/registry-session" --runtime-config "$RECIPE/sessi --route-inventory-out "$REFERENCE_CONFIG/gateway/route-inventory.json" --checked-route businesses ``` +The gateway forwards only the browser function the preview declares: the +`functions` module carries exactly `register-business`, the list in the +preview's `dev.yaml` that the development gateway relays. +`tests/prepare-inputs.mjs` refuses to stage a `session.yaml` that forwards any +other function, and `tests/routes.test.mjs` checks the two files against each +other. An undeclared function path answers 404. + +The `businesses` module stays at the BReg product root (`/registry/businesses/` +rewritten to `/`), so it forwards more BReg routes than the browser uses (the +two record reads the preview declares). Session's checked product-client +binding requires a BReg module that rewrites to the product root, and Session +modules match path prefixes, not methods or exact routes. BReg still decides +every request through the registrar's access profile. The module narrows to +the declared reads when Session can carry exact routes on a checked module. + 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 @@ -337,8 +472,29 @@ 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`. +`BUSINESS_BUNDLE` and the identity work directory. + +To replay the BReg or Casework proof with an attested candidate, follow the +[candidate reference-host replay](../../../release/OPERATIONS.md#replay-the-candidate-reference-host-locally). + +## Check browser route parity + +The preview CI check probes the declared development gateway routes. It compares +them with the browser API contract mounted through the checked Session and Envoy +configuration. Session and Envoy supply the modules, prefixes and rewrites. +The test's upstream fixtures supply methods, path templates and parameter names. +After Session authorises the caller, Envoy forwards requests that match each +module's prefix. The function module uses the declared registration path as +its prefix. The host accepts POST on the exact relayed path. + +Run the check from the repository root: + +```bash +npm --prefix clients/typescript ci +cargo build --locked -p registry-session +node --test clients/typescript/preview/tests/route-parity.mjs +``` -Release-candidate smoke wiring, published Session and Coordinator images, -and the `rstack dev` route-parity gate are v0.52 work. +The check uses `target/debug/registry-session` by default. Set +`REGISTRY_SESSION_BIN` to an absolute path to use a matching binary from another +build directory. diff --git a/deploy/examples/business-registration/casework/compose.yaml b/deploy/examples/business-registration/casework/compose.yaml new file mode 100644 index 0000000000..3982b800b2 --- /dev/null +++ b/deploy/examples/business-registration/casework/compose.yaml @@ -0,0 +1,64 @@ +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] + +services: + edge: + volumes: + - ${REFERENCE_CONFIG}/casework/edge.yaml:/run/reference/edge.yaml:ro + upstreams: + volumes: + - ${REFERENCE_CONFIG}/casework/upstreams.yaml:/run/reference/upstreams.yaml:ro + gateway-check: + volumes: + - ${REFERENCE_CONFIG}/session.yaml:/run/reference/session.yaml:ro + session: + volumes: + - ${REFERENCE_CONFIG}/session.yaml:/run/reference/session.yaml:ro + + casework: + <<: *native + network_mode: service:upstreams + entrypoint: [/opt/native/casework] + command: [--runtime-config, /run/casework/runtime.yaml, --posture, production, serve] + environment: + SSL_CERT_FILE: /run/trust/https-ca.pem + volumes: + - ${REFERENCE_ARTIFACTS}/casework:/opt/native/casework:ro + - ${REFERENCE_CONFIG}/casework/runtime:/run/casework:ro + - ${REFERENCE_CONFIG}/casework/audit:/var/lib/casework + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + depends_on: + postgres: {condition: service_healthy} + issuer-ready: {condition: service_completed_successfully} + + casework-admin: + <<: *native + profiles: [setup] + networks: [database] + entrypoint: [/opt/native/caseworkctl] + volumes: + - ${REFERENCE_ARTIFACTS}/caseworkctl:/opt/native/caseworkctl:ro + - ${REFERENCE_CONFIG}/casework/admin:/run/casework:ro + - ${REFERENCE_CONFIG}/casework/audit:/var/lib/casework + depends_on: + postgres: {condition: service_healthy} + + casework-seed: + image: node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 + user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + profiles: [setup] + network_mode: service:upstreams + entrypoint: [node, /run/reference/seed-task.mjs, /run/producer/key.json] + environment: + NODE_EXTRA_CA_CERTS: /run/trust/https-ca.pem + volumes: + - ./casework/seed-task.mjs:/run/reference/seed-task.mjs:ro + - ${REFERENCE_CONFIG}/casework/producer.jwk.json:/run/producer/key.json:ro + - ${REFERENCE_CONFIG}/trust:/run/trust:ro diff --git a/deploy/examples/business-registration/casework/runtime.yaml b/deploy/examples/business-registration/casework/runtime.yaml new file mode 100644 index 0000000000..6686f6e68c --- /dev/null +++ b/deploy/examples/business-registration/casework/runtime.yaml @@ -0,0 +1,28 @@ +apiVersion: id.registrystack.org/formats/casework/runtime/v1alpha1 +kind: CaseworkRuntimeConfig +identity: + databaseId: reference-casework +package: + root: /run/casework/package +listener: + bind: 127.0.0.1:8500 + tlsTermination: operator-controlled-upstream + networkExposure: private-address +secretProviders: + file: + root: /run/casework/secrets +database: + transport: verified-tls + runtimeUrlRef: secret:file/runtime-database-url + migrationUrlRef: secret:file/migration-database-url + caBundleRef: secret:file/database-ca +authentication: + oidc: + issuers: + thunderid: + issuer: https://identity.reference.test:9443 + audience: urn:example:standalone-decision + allowedClients: [business-registrar, casework-admin, casework-fixture-requester] +audit: + path: /var/lib/casework/audit.jsonl + hashKeyRef: secret:file/audit-key diff --git a/deploy/examples/business-registration/casework/seed-task.mjs b/deploy/examples/business-registration/casework/seed-task.mjs new file mode 100644 index 0000000000..d9033480be --- /dev/null +++ b/deploy/examples/business-registration/casework/seed-task.mjs @@ -0,0 +1,92 @@ +import { createPrivateKey, randomUUID, sign } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { isAbsolute } from 'node:path' + +const issuer = 'https://identity.reference.test:9443' +const client = 'casework-fixture-requester' +const audience = 'urn:example:standalone-decision' +const casework = 'http://127.0.0.1:8500/v1/review-requests?accessProfile=requester' + +// Keep this submission aligned with standalone-decision/dev-journeys.yaml. +const reference = 'synthetic-batch-0042' +const submission = { + policy: { id: 'decision' }, + subject: { + source: 'standalone', + type: 'batch', + id: reference, + version: '1', + digest: 'sha256:54cb59dbbbc61ee50ade6b89a3e961156b6a2ff1a584b485ede786b1becfc7c3', + }, + requesterReference: reference, + context: { + mode: 'submitted', + snapshot: { summary: 'Confirm the prepared synthetic batch', reference }, + }, +} + +function base64urlJson(value) { + return Buffer.from(JSON.stringify(value)).toString('base64url') +} + +let stage = 'load the synthetic producer JWK' +let status +try { + const [path, ...extra] = process.argv.slice(2) + if (!path || !isAbsolute(path) || extra.length > 0) throw new Error() + const jwk = JSON.parse(await readFile(path, 'utf8')) + if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || (jwk.alg ?? 'ES256') !== 'ES256' + || typeof jwk.kid !== 'string' || !jwk.kid) throw new Error() + + stage = 'request an access token for the Casework audience' + const now = Math.floor(Date.now() / 1000) + const header = base64urlJson({ alg: 'ES256', kid: jwk.kid, typ: 'JWT' }) + const claims = base64urlJson({ iss: client, sub: client, aud: issuer, iat: now, exp: now + 60, jti: randomUUID() }) + const signedInput = header + '.' + claims + const signature = sign('sha256', Buffer.from(signedInput), { + key: createPrivateKey({ key: jwk, format: 'jwk' }), + dsaEncoding: 'ieee-p1363', + }).toString('base64url') + const tokenResponse = await fetch(issuer + '/oauth2/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + client_id: client, + client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', + client_assertion: signedInput + '.' + signature, + resource: audience, + scope: 'casework:request', + }), + redirect: 'error', + signal: AbortSignal.timeout(10_000), + }) + status = tokenResponse.status + if (status !== 200) throw new Error() + const token = await tokenResponse.json() + if (token.token_type !== 'Bearer' || typeof token.access_token !== 'string' || !token.access_token) throw new Error() + + stage = 'submit the synthetic Casework review request' + status = undefined + const response = await fetch(casework, { + method: 'POST', + headers: { + Authorization: 'Bearer ' + token.access_token, + 'Content-Type': 'application/json', + 'Idempotency-Key': 'request-a-decision', + }, + body: JSON.stringify(submission), + redirect: 'error', + signal: AbortSignal.timeout(10_000), + }) + status = response.status + if (status !== 201) throw new Error() + const { requestId } = await response.json() + if (typeof requestId !== 'string' || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(requestId)) { + throw new Error() + } + console.log(JSON.stringify({ requestId })) +} catch { + console.error('Could not ' + stage + (status === undefined ? '.' : ' (HTTP ' + status + ').')) + process.exitCode = 1 +} diff --git a/deploy/examples/business-registration/compose.local.yaml b/deploy/examples/business-registration/compose.local.yaml new file mode 100644 index 0000000000..4f8a392cd0 --- /dev/null +++ b/deploy/examples/business-registration/compose.local.yaml @@ -0,0 +1,6 @@ +services: + session: + image: ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8 + entrypoint: [/opt/native/registry-session] + volumes: + - ${REFERENCE_ARTIFACTS:?Set REFERENCE_ARTIFACTS}/registry-session:/opt/native/registry-session:ro diff --git a/deploy/examples/business-registration/compose.yaml b/deploy/examples/business-registration/compose.yaml index 777591157f..c122388c62 100644 --- a/deploy/examples/business-registration/compose.yaml +++ b/deploy/examples/business-registration/compose.yaml @@ -77,20 +77,26 @@ services: session: <<: *native + # The Session service holds people's tokens, so it runs only the image digest + # recorded in the verified release manifest, never a tag resolved at pull time. + image: ghcr.io/registrystack/registry-session@${REFERENCE_SESSION_DIGEST:?Set REFERENCE_SESSION_DIGEST to the registry-session image digest (sha256:...) in the verified release manifest} network_mode: service:edge - entrypoint: [/opt/native/registry-session] + working_dir: / 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: . + build: + context: . + # The register-business client the recipe step generated, never the function bundle. + additional_contexts: + host-client: ${REFERENCE_HOST_CLIENT:?Set REFERENCE_HOST_CLIENT} user: "${REFERENCE_UID:-1000}:${REFERENCE_GID:-1000}" network_mode: service:upstreams read_only: true diff --git a/deploy/examples/business-registration/host.mjs b/deploy/examples/business-registration/host.mjs index 069c4f6330..a2ec458678 100644 --- a/deploy/examples/business-registration/host.mjs +++ b/deploy/examples/business-registration/host.mjs @@ -1,30 +1,40 @@ import { createHash } from 'node:crypto' -import { readFile, realpath } from 'node:fs/promises' +import { constants } from 'node:fs' +import { open, readdir, 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 +// The Session gateway relays the browser's /api/functions/ to this path on the host. +const relayedPath = '/functions/' + functionName +const bindingPath = '/api/functions/' + functionName +const bregOrigin = 'http://127.0.0.1:8100' +const preparationTimeoutMs = 2_000 +// register-business takes exactly these two fields, within the Record type's limits. +const registrationLimits = { legalName: 160, registrationNumber: 32 } 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.') +// Every bundle path below the root, files and links alike, sorted by bytes. +async function bundlePaths(root, directory = '') { + const paths = [] + for (const entry of await readdir(join(root, directory), { withFileTypes: true })) { + const path = join(directory, entry.name) + paths.push(...entry.isDirectory() ? await bundlePaths(root, path) : [path]) } - return readFile(resolved) + return paths.sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))) } 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 paths = await bundlePaths(root) + const manifestPath = 'manifest.json' + const manifestBytes = await withBundleFile(root, manifestPath, file => file.readFile()) 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 @@ -32,16 +42,50 @@ async function readBundle(directory) { 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 assetPaths = Array.from(pages.keys(), name => [name, join(manifest.staticOutput, name)]) + const retained = new Map() + const required = new Set([modulePath, ...assetPaths.map(([, path]) => path)]) + // Use only the bytes hashed here for the manifest, module and served assets. + const hashes = [] + for (const path of paths) { + const hash = createHash('sha256') + if (path === manifestPath) { + hash.update(manifestBytes) + } else if (required.delete(path)) { + const bytes = await withBundleFile(root, path, file => file.readFile()) + retained.set(path, bytes) + hash.update(bytes) + } else { + await withBundleFile(root, path, async file => { + for await (const chunk of file.createReadStream({ autoClose: false })) hash.update(chunk) + }) + } + hashes.push([path, hash.digest('hex')]) + } + if (required.size || !paths.includes(manifestPath)) { + throw Object.assign(new Error('The preview bundle is missing a required file.'), { code: 'ENOENT' }) } - const hashes = Array.from(files, ([path, bytes]) => [path, createHash('sha256').update(bytes).digest('hex')]) + // The digest rstack dev export-preview prints: every bundle file, sorted by path. 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))])), + module: retained.get(modulePath), + assets: new Map(assetPaths.map(([name, path]) => [name, retained.get(path)])), + } +} + +async function withBundleFile(root, path, read) { + 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.') + } + const file = await open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK) + try { + if (!(await file.stat()).isFile()) throw new Error('A preview bundle holds only regular files.') + return await read(file) + } finally { + await file.close() } } @@ -49,17 +93,89 @@ export async function bundleDigest(directory) { return (await readBundle(directory)).digest } -async function requestFunction(request, handle) { +// Exactly the two register-business fields as nonblank strings within their limits, or +// undefined. A value naming anything else, such as an owner or an applicant, is refused: the +// Action declares only these two inputs. Each field is read once, so the value checked is the +// value returned. +function registration(value) { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined + const names = Object.keys(value) + if (names.length !== 2 || !names.every(name => Object.hasOwn(registrationLimits, name))) return undefined + const checked = {} + for (const [name, limit] of Object.entries(registrationLimits)) { + const field = value[name] + if (typeof field !== 'string' || !field.trim() || field.length > limit) return undefined + checked[name] = field + } + return checked +} + +// The host owns the binding: what the page may submit, what the function may return, and the +// one Action call, made with the caller's credential through the generated client. +function registrationBinding(createRegistryServerClient) { + return { + kind: 'create', + path: bindingPath, + preparationTimeoutMs, + parseSubmission: value => { + const preparation = registration(value) + return preparation && { preparation } + }, + parsePreparation: registration, + async invoke(credential, { idempotencyKey, input, signal }) { + const { businesses } = createRegistryServerClient({ baseUrl: bregOrigin, token: () => credential }) + const result = await businesses.invoke(functionName, input, { + accessProfile: 'business-registrar', + idempotencyKey, + signal, + }) + const business = result?.data?.results?.business + return { recordId: business?.recordId, revision: business?.revision } + }, + } +} + +// One line per answer for the operator: the failure class, the attempt key and the status. +// The binding gives it no submitted or prepared value and no credential. +function logOutcome(outcome) { + console.log(JSON.stringify({ event: 'holder-outcome', ...outcome })) +} + +// The host's own answers report like the binding's: a hook that throws or rejects is logged and +// leaves the answer unchanged. +function hostReporter(report) { + const failed = () => { console.error('The holder outcome hook failed.') } + return (status, outcomeClass = 'request-refused') => { + try { + const returned = report({ class: outcomeClass, attemptKey: undefined, status }) + if (typeof returned?.then === 'function') Promise.resolve(returned).catch(failed) + } catch { + failed() + } + } +} + +function requestFunction(request, handle, reportHost) { 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 })) + if (url.pathname !== relayedPath || url.search) { + reportHost(404) + return new Response(null, { status: 404, headers: { 'cache-control': 'no-store' } }) + } + // Before a Request is built: the Fetch constructor refuses methods such as TRACE. + if (request.method !== 'POST') { + reportHost(405) + return new Response(null, { status: 405, headers: { allow: 'POST', 'cache-control': 'no-store' } }) + } + // This listener is private loopback inside the upstream namespace. Only Session's Envoy + // reaches it, through the owner-only relay socket, and the gateway supplies the caller's + // bearer. The binding checks the browser-facing path, so hand it that path. + return handle(new Request(new URL(bindingPath, url), { + method: request.method, + headers: request.headers, + body: request.body, + duplex: 'half', + signal: request.signal, + })) } function requestPage(request, assets) { @@ -80,23 +196,34 @@ function requestPage(request, assets) { }) } -export async function startHost(directory, expectedDigest, { functionsPort = 8300, pagesPort = 8200 } = {}) { +export async function startHost(directory, expectedDigest, { + functionsPort = 8300, pagesPort = 8200, client, report = logOutcome, +} = {}) { 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.') + // Import the bytes that were checked, and use only the function's prepare export. The host + // keeps the caller's credential and the product client; the function never receives either. + const { prepare } = await import('data:text/javascript;base64,' + bundle.module.toString('base64')) + if (typeof prepare !== 'function') throw new TypeError('The compiled registration module must export prepare.') + // The client generated from the sealed project at the recipe step, never from the bundle. + const { createRegistryServerClient, createHolderActionHandler } = client ?? await import('./host-client.mjs') + const handle = createHolderActionHandler(registrationBinding(createRegistryServerClient), prepare, { onOutcome: report }) + const reportHost = hostReporter(report) 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), + // An outer bound only: the binding answers 413 itself past 32 KiB. + maxRequestBodySize: 65_536, + fetch: request => requestFunction(request, handle, reportHost), error(error) { - if (error?.code === 'ERR_BODY_TOO_LARGE') return new Response(null, { status: 413 }) + if (error?.code === 'ERR_BODY_TOO_LARGE') { + reportHost(413) + return new Response(null, { status: 413 }) + } console.error('The registration function could not complete its request.') + reportHost(500, 'unresolved') return new Response(null, { status: 500 }) }, }) diff --git a/deploy/examples/business-registration/session.yaml b/deploy/examples/business-registration/session.yaml index 8e9d433af8..1a7a67f393 100644 --- a/deploy/examples/business-registration/session.yaml +++ b/deploy/examples/business-registration/session.yaml @@ -32,12 +32,12 @@ modules: prefixRewrite: / - id: functions product: breg - prefix: /api/functions/ + prefix: /api/functions/register-business audience: person signIns: [registrar] upstream: cluster: functions - prefixRewrite: /functions/ + prefixRewrite: /functions/register-business pages: - prefix: /apply/ signIn: registrar diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs index e2a7a5a043..0f58c0e840 100644 --- a/deploy/examples/business-registration/tests/browser.mjs +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -1,57 +1,55 @@ import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' import { createHash, randomUUID, X509Certificate } from 'node:crypto' import { readFile } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import { pathToFileURL } from 'node:url' +import { assertReceipt } from './receipt.mjs' -const [playwright, config, passwords, bundle] = process.argv.slice(2) +const [playwright, config, passwords, bundle, profile = 'breg', ...compose] = 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) { +async function signIn(person, path = '/apply/', expectedSignIn = 'registrar') { 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')) + const authorizations = new Map() + const starts = [] + context.on('request', request => { + const url = new URL(request.url()) + authorizationHeaders.push(request.headerValue('authorization')) + if (url.origin === origin && url.pathname === '/session/sign-in') starts.push(request) + if (request.method() === 'GET' && url.origin === issuer && url.pathname === '/oauth2/authorize' + && url.searchParams.get('redirect_uri') === origin + '/session/callback') { + // The issuer can revisit the authorize URL within the same OIDC state. + const state = url.searchParams.get('state') + if (state) authorizations.set(state, url.searchParams.getAll('resource')) + } }) - await page.goto(apply) + await page.goto(origin + path) 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) + await page.waitForURL(origin + path) const { signIn, claims } = await sessionIdentity(page) - assert.equal(signIn, 'registrar') + assert.equal(signIn, expectedSignIn) 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 } + return { context, page, subject: claims.sub, authorizations, starts } } async function sessionIdentity(page) { @@ -129,10 +127,11 @@ async function assertOwnRecord(page, expected) { const { recordId, domainData } = body.data const { legalName, registrationNumber, registeringOffice } = domainData assert.deepEqual({ recordId, legalName, registrationNumber, registeringOffice }, expected) + return status } async function signOut(page) { - stage = 'submit the first registrar sign-out form' + startStage('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. @@ -147,34 +146,89 @@ async function signOut(page) { }) 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' + startStage('return from the issuer to the signed-out page') await page.waitForURL(origin + '/session/signed-out') } -let stage = 'sign in two registrars' +let stage +function startStage(name) { + stage = name + console.error('Reference browser phase: ' + stage) +} + +function reportFailure(error) { + const kind = ['AssertionError', 'TimeoutError'].includes(error?.name) ? error.name : 'Error' + console.error('Reference browser test stopped at ' + stage + ' (' + kind + ').') + process.exitCode = 1 +} + +let identity +let browser let report try { - const first = await startRegistrar(registrars[0]) - const second = await startRegistrar(registrars[1]) + startStage('read browser inputs and load Playwright') + 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)) + startStage('launch Chromium') + 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(','), + ], + }) + if (profile === 'casework') { + report = await checkCasework() + } else { + report = await checkBaseline() + } + startStage('validate browser report') + assertReceipt(profile, report) +} catch (error) { + reportFailure(error) +} finally { + if (browser) { + startStage('close Chromium') + try { + await browser.close() + startStage('Chromium closed') + } catch (error) { + reportFailure(error) + } + } +} +if (report && !process.exitCode) console.log(JSON.stringify(report, null, 2)) + +async function checkBaseline() { + startStage('sign in the first registrar') + const first = await signIn(registrars[0]) + startStage('sign in the second registrar') + const second = await signIn(registrars[1]) assert.notEqual(first.subject, second.subject) - stage = 'verify assets and register both businesses' + startStage('verify frozen browser assets') const assetSha256 = await checkAssets(first.page) + startStage('register both businesses') 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' + startStage('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' + startStage('check the first registrar session cookie') 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' + startStage('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' + startStage('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') @@ -182,26 +236,110 @@ try { 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) + startStage('require a new issuer sign-in for the protected page') + await first.page.goto(origin + '/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' + startStage('verify that the second registrar is still signed in') assert.equal((await sessionIdentity(second.page)).claims?.sub, second.subject) await assertOwnRecord(second.page, secondRecord) + startStage('check browser authorization headers') assert.ok((await Promise.all(authorizationHeaders)).every(value => value === null)) - report = { + return { 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)) + +async function caseworkJson(page, path, options = {}) { + return page.evaluate(async ({ path, options }) => { + const response = await fetch('/casework/v1/' + path, { + ...options, + cache: 'no-store', + headers: { 'Registry-Client': 'page', ...options.headers }, + }) + return { status: response.status, body: await response.json() } + }, { path, options }) +} + +async function checkCasework() { + startStage('sign in the Casework administrator and staff the queue') + const admin = await signIn({ + username: 'reference-review-admin', password: 'ADMIN_REVIEW_PASSWORD', + }, '/admin/', 'casework-admin') + const reviewerSubject = identity.users[registrars[0].username].sub + const bootstrap = { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'If-Match': '"0"', 'Idempotency-Key': 'staff-the-queue' }, + body: JSON.stringify({ teamId: 'decisions-team', staff: [{ issuer, subject: reviewerSubject }], + supervisors: [], queueId: 'decisions' }), + } + const directory = await caseworkJson(admin.page, 'directory/bootstrap?accessProfile=administrator', bootstrap) + assert.equal(directory.status, 200) + assert.equal(directory.body.revision, 1) + const team = directory.body.teams.find(item => item.id === 'decisions-team') + assert.deepEqual(team?.servedQueues, ['decisions']) + assert.deepEqual(team.members.map(({ issuer, subject }) => ({ issuer, subject })), [{ issuer, subject: reviewerSubject }]) + + startStage('seed one review request with the independent machine producer') + const args = [...compose, 'run', '-T', '--rm', '--no-deps', '--pull', 'never', 'casework-seed'] + const { stdout } = await promisify(execFile)('docker', args, { timeout: 60_000 }) + const { requestId } = JSON.parse(stdout) + assert.match(requestId, /^[0-9a-f-]{36}$/iu) + + startStage('sign in once and read both products as the reviewer') + const reviewer = await signIn(registrars[0]) + const { page } = reviewer + const firstCookie = (await reviewer.context.cookies(origin)).find(cookie => cookie.name === cookieName) + assert.ok(firstCookie?.secure && firstCookie.httpOnly) + const audiences = [...reviewer.authorizations.values()] + assert.deepEqual(audiences, [['urn:example:business-register'], ['urn:example:standalone-decision']]) + await checkAssets(page) + const record = await register(page, registrars[0].username) + const businessRead = await assertOwnRecord(page, record) + const businessSubject = (await sessionIdentity(page)).claims?.sub + + const taskListPath = 'review-tasks?queue=decisions&accessProfile=staff' + const list = await caseworkJson(page, taskListPath) + assert.equal(list.status, 200) + assert.equal(list.body.status, 'complete') + assert.equal(list.body.items.length, 1) + const [task] = list.body.items + assert.match(task.taskId, /^[0-9a-f-]{36}$/iu) + assert.equal(task.requestId, requestId) + assert.equal(task.subject.id, 'synthetic-batch-0042') + assert.equal(task.queue, 'decisions') + assert.deepEqual(task.eligibleProfiles, ['staff']) + const taskPath = 'review-tasks/' + encodeURIComponent(task.taskId) + '?accessProfile=staff' + const read = await caseworkJson(page, taskPath) + assert.equal(read.status, 200) + assert.equal(read.body.taskId, task.taskId) + assert.equal(read.body.requestId, requestId) + const caseworkSubject = (await sessionIdentity(page)).claims?.sub + const lastCookie = (await reviewer.context.cookies(origin)).find(cookie => cookie.name === cookieName) + assert.ok(lastCookie?.value === firstCookie.value) + assert.equal(reviewer.authorizations.size, 2) + + startStage('refuse the reviewer on a Casework administrator route') + const adminRefusal = await caseworkJson(page, 'directory/bootstrap?accessProfile=administrator', bootstrap) + startStage('refuse the BReg-only citizen on a Casework staff route') + const citizen = await signIn(registrars[1]) + assert.notEqual(citizen.subject, reviewer.subject) + const citizenRefusal = await caseworkJson(citizen.page, taskPath) + startStage('check browser authorization headers') + const browserHeaders = await Promise.all(authorizationHeaders) + return { + reviewerSignIns: reviewer.starts.length, + authorizedAudiences: audiences.flat(), + sameReviewerSubject: businessSubject === reviewerSubject && caseworkSubject === reviewerSubject, + businessRead, + caseworkRead: read.status, + reviewerAdminRefusal: { status: adminRefusal.status, code: adminRefusal.body.code }, + citizenCaseworkRefusal: { status: citizenRefusal.status, code: citizenRefusal.body.code }, + noBrowserAuthorizationHeader: browserHeaders.every(value => value === null), + } +} diff --git a/deploy/examples/business-registration/tests/build-host-client.mjs b/deploy/examples/business-registration/tests/build-host-client.mjs new file mode 100644 index 0000000000..162ad79b9e --- /dev/null +++ b/deploy/examples/business-registration/tests/build-host-client.mjs @@ -0,0 +1,150 @@ +// Generate the reference host's register-business client from the sealed preview project, +// with the pinned @registrystack/client the preview installed, and bundle it with the holder +// binding into one ESM file the host image copies. Never from the function bundle. +// +// node build-host-client.mjs write +// node build-host-client.mjs --check refuse stale +// +// RSTACK_BREGCTL_BIN names the bregctl that compiles the project, the same one the stack runs. +import { spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { chmod, mkdtemp, mkdir, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { isAbsolute, join, relative } from 'node:path' +import { pathToFileURL } from 'node:url' + +export const outputFile = 'host-client.mjs' +export const provenanceFile = 'host-client.json' +// The project starts no Proposals, so the client takes no author profile. +const member = 'businesses' + +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex') + +async function treeDigest(root) { + const entries = [] + async function walk(directory) { + for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : 1)) { + const path = join(directory, entry.name) + if (entry.isDirectory()) await walk(path) + else if (entry.isFile()) entries.push([relative(root, path), sha256(await readFile(path))]) + else throw new Error('The sealed project holds an entry that is not a file or directory: ' + relative(root, path)) + } + } + await walk(root) + return sha256(JSON.stringify(entries)) +} + +/** Generate and bundle into `output`, and return the provenance record. */ +export async function buildHostClient(preview, output) { + if (!isAbsolute(preview) || !isAbsolute(output)) throw new Error('Use absolute preview and output directories.') + const project = join(preview, 'project') + const clientRoot = join(preview, 'node_modules', '@registrystack', 'client') + const clientPackage = JSON.parse(await readFile(join(clientRoot, 'package.json'), 'utf8')) + if (clientPackage.name !== '@registrystack/client') throw new Error('The preview did not install @registrystack/client.') + // The preview's lock pins the client package by its source and integrity. + const lock = JSON.parse(await readFile(join(preview, 'package-lock.json'), 'utf8')) + const locked = lock.packages?.['node_modules/@registrystack/client'] + if (locked?.version !== clientPackage.version || typeof locked.integrity !== 'string') { + throw new Error('The preview lock does not pin the installed @registrystack/client by integrity.') + } + + const work = await mkdtemp(join(tmpdir(), 'reference-host-client-')) + try { + return await generateInto(preview, output, { project, clientRoot, clientPackage, locked, work }) + } finally { + await rm(work, { recursive: true, force: true }) + } +} + +// The version line of the bregctl that compiles the project, recorded beside the client. +function bregctlVersion() { + const bregctl = process.env.RSTACK_BREGCTL_BIN || 'bregctl' + const result = spawnSync(bregctl, ['--version'], { encoding: 'utf8' }) + if (result.error) throw new Error('Cannot run the bregctl named by RSTACK_BREGCTL_BIN.', { cause: result.error }) + return result.stdout.trim() +} + +async function generateInto(preview, output, { project, clientRoot, clientPackage, locked, work }) { + // The generator and esbuild both resolve the client from the scratch directory. + await symlink(join(preview, 'node_modules'), join(work, 'node_modules'), 'dir') + const generator = spawnSync(process.execPath, [ + join(clientRoot, 'registry-generate.js'), + '--register', member + '=' + project, + '--output', join(work, 'service.ts'), + ], { encoding: 'utf8', env: process.env }) + if (generator.status !== 0) { + throw new Error('registry-generate could not generate the host client: ' + (generator.stderr.trim() || generator.status)) + } + const entry = join(work, 'entry.ts') + await writeFile(entry, [ + "export { createRegistryServerClient } from './service.ts'", + "export { createHolderActionHandler } from '@registrystack/client/holder-function'", + '', + ].join('\n')) + const { build } = await import(pathToFileURL(join(preview, 'node_modules', 'esbuild', 'lib', 'main.js')).href) + const bundled = await build({ + // Paths in the output stay relative to the scratch directory, through the node_modules + // link, so a regeneration is byte-identical. + absWorkingDir: work, preserveSymlinks: true, + entryPoints: [entry], bundle: true, write: false, format: 'esm', platform: 'node', target: 'node24', + logLevel: 'silent', legalComments: 'none', + }) + const bytes = bundled.outputFiles[0].contents + // The lock's source and integrity name the package npm installed. The installed tree digest + // covers the files that actually ran, so a later edit to node_modules makes the check fail. + const provenance = { + client: { + name: clientPackage.name, version: clientPackage.version, resolved: locked.resolved, integrity: locked.integrity, + installedTreeSha256: await treeDigest(clientRoot), + }, + project: { treeSha256: await treeDigest(project) }, + bregctl: bregctlVersion(), + output: { file: outputFile, sha256: sha256(bytes) }, + } + await mkdir(output, { recursive: true, mode: 0o700 }) + // The image runs as a nonroot user and Docker keeps these modes, so set them past the umask. + for (const [name, content] of [[outputFile, bytes], [provenanceFile, JSON.stringify(provenance, null, 2) + '\n']]) { + await writeFile(join(output, name), content) + await chmod(join(output, name), 0o644) + } + return provenance +} + +/** Regenerate into scratch and refuse unless `output` holds the same bytes and provenance. */ +export async function checkHostClient(preview, output) { + const fresh = await mkdtemp(join(tmpdir(), 'reference-host-client-check-')) + try { + await buildHostClient(preview, fresh) + for (const name of [outputFile, provenanceFile]) { + let current + try { + current = await readFile(join(output, name)) + } catch (error) { + throw new Error(`The generated host client is missing ${name}. Run build-host-client.mjs first.`, { cause: error }) + } + if (!current.equals(await readFile(join(fresh, name)))) { + throw new Error(`The generated host client is stale: ${name} differs from a fresh generation.`) + } + } + } finally { + await rm(fresh, { recursive: true, force: true }) + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const args = process.argv.slice(2) + const check = args[0] === '--check' + const [preview, output] = check ? args.slice(1) : args + try { + if (check) { + await checkHostClient(preview, output) + console.error('The generated host client matches a fresh generation.') + } else { + const { client, output: written } = await buildHostClient(preview, output) + console.error(`Generated the host client from ${client.name}@${client.version}: ${written.sha256}`) + } + } catch (error) { + console.error(error.message) + process.exitCode = 1 + } +} diff --git a/deploy/examples/business-registration/tests/build-host-client.test.mjs b/deploy/examples/business-registration/tests/build-host-client.test.mjs new file mode 100644 index 0000000000..4c127871f7 --- /dev/null +++ b/deploy/examples/business-registration/tests/build-host-client.test.mjs @@ -0,0 +1,168 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import { chmod, mkdtemp, mkdir, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { pathToFileURL } from 'node:url' +import { buildHostClient, checkHostClient } from './build-host-client.mjs' + +// REFERENCE_ESBUILD_PACKAGE names an installed esbuild package directory, such as the client's. +const esbuildPackage = process.env.REFERENCE_ESBUILD_PACKAGE +if (!esbuildPackage) throw new Error('Set REFERENCE_ESBUILD_PACKAGE to an installed esbuild package directory.') + +// A preview with a stand-in client and bregctl. Like the real generator, the stand-in refuses +// unless the client resolves from its output path. With embedProject, its output carries the +// project's registry.yaml, so a changed project changes the generated bytes; without it, the +// output is the same for any project. +async function preview(t, { embedProject = true } = {}) { + const root = await mkdtemp(join(tmpdir(), 'reference-host-client-test-')) + t.after(() => rm(root, { recursive: true })) + const client = join(root, 'node_modules/@registrystack/client') + await mkdir(join(client, 'dist'), { recursive: true }) + await mkdir(join(root, 'project')) + await writeFile(join(root, 'project/registry.yaml'), 'id: business-registration\n') + await writeFile(join(client, 'package.json'), JSON.stringify({ + name: '@registrystack/client', version: '0.52.0-test', type: 'module', + exports: { './holder-function': './dist/holder-function.js' }, + })) + await writeFile(join(client, 'dist/holder-function.js'), 'export const createHolderActionHandler = () => "binding"\n') + await writeFile(join(client, 'registry-generate.js'), ` + import { readFileSync, writeFileSync } from 'node:fs' + import { findPackageJSON } from 'node:module' + import { join } from 'node:path' + import { pathToFileURL } from 'node:url' + const args = process.argv.slice(2) + const value = name => args[args.indexOf(name) + 1] + try { + findPackageJSON('@registrystack/client', pathToFileURL(value('--output'))) + } catch { + console.error('Install @registrystack/client in the application before generating clients.') + process.exit(6) + } + if (value('--register') !== 'businesses=' + join(${JSON.stringify(root)}, 'project')) process.exit(3) + // The project starts no Proposals, so the real generator refuses an author profile. + if (args.includes('--author-profile')) process.exit(4) + if (process.env.RSTACK_BREGCTL_BIN !== ${JSON.stringify(join(root, 'bregctl'))}) process.exit(5) + const project = ${embedProject} ? readFileSync(join(${JSON.stringify(root)}, 'project/registry.yaml'), 'utf8') : 'any' + writeFileSync(value('--output'), 'export const createRegistryServerClient = () => ' + JSON.stringify(project) + '\\n') + `) + await writeFile(join(root, 'bregctl'), '#!/bin/sh\necho "bregctl 0.52.0-test"\n') + await chmod(join(root, 'bregctl'), 0o755) + await symlink(esbuildPackage, join(root, 'node_modules/esbuild'), 'dir') + await lock(root, '0.52.0-test') + return root +} + +function lock(root, version) { + return writeFile(join(root, 'package-lock.json'), JSON.stringify({ + packages: { + 'node_modules/@registrystack/client': { + version, resolved: 'file:registry-preview-client.tgz', integrity: 'sha512-stand-in-' + version, + }, + }, + })) +} + +function withBregctl(t, path) { + const previous = process.env.RSTACK_BREGCTL_BIN + process.env.RSTACK_BREGCTL_BIN = path + t.after(() => { + if (previous === undefined) delete process.env.RSTACK_BREGCTL_BIN + else process.env.RSTACK_BREGCTL_BIN = previous + }) +} + +async function output(t) { + const root = await mkdtemp(join(tmpdir(), 'reference-host-client-output-')) + t.after(() => rm(root, { recursive: true })) + return join(root, 'client') +} + +test('generates one module with the server client and the binding, and records its sources', async t => { + const source = await preview(t) + withBregctl(t, join(source, 'bregctl')) + const written = await output(t) + const provenance = await buildHostClient(source, written) + + const bytes = await readFile(join(written, 'host-client.mjs')) + const module = await import(pathToFileURL(join(written, 'host-client.mjs')).href) + assert.equal(module.createRegistryServerClient(), 'id: business-registration\n') + assert.equal(module.createHolderActionHandler(), 'binding') + assert.deepEqual(Object.keys(provenance.client), ['name', 'version', 'resolved', 'integrity', 'installedTreeSha256']) + assert.equal(provenance.client.version, '0.52.0-test') + assert.equal(provenance.client.integrity, 'sha512-stand-in-0.52.0-test') + assert.match(provenance.client.installedTreeSha256, /^[0-9a-f]{64}$/u) + assert.match(provenance.project.treeSha256, /^[0-9a-f]{64}$/u) + assert.equal(provenance.bregctl, 'bregctl 0.52.0-test') + assert.equal(provenance.output.sha256, createHash('sha256').update(bytes).digest('hex')) + assert.deepEqual(JSON.parse(await readFile(join(written, 'host-client.json'), 'utf8')), provenance) + await checkHostClient(source, written) +}) + +test('the generated files are readable by the image user under a private umask', async t => { + const source = await preview(t) + withBregctl(t, join(source, 'bregctl')) + const written = await output(t) + const previous = process.umask(0o077) + try { + await buildHostClient(source, written) + } finally { + process.umask(previous) + } + for (const name of ['host-client.mjs', 'host-client.json']) { + assert.equal((await stat(join(written, name))).mode & 0o777, 0o644, name) + } +}) + +test('the check refuses a missing, edited or stale generated client', async t => { + const source = await preview(t) + withBregctl(t, join(source, 'bregctl')) + const written = await output(t) + await assert.rejects(checkHostClient(source, written), /missing host-client\.mjs/) + + await buildHostClient(source, written) + await writeFile(join(written, 'host-client.mjs'), '// edited\n', { flag: 'a' }) + await assert.rejects(checkHostClient(source, written), /stale: host-client\.mjs/) + + await buildHostClient(source, written) + await writeFile(join(written, 'host-client.json'), '\n', { flag: 'a' }) + await assert.rejects(checkHostClient(source, written), /stale: host-client\.json/) + + await buildHostClient(source, written) + await writeFile(join(source, 'project/registry.yaml'), 'id: another-project\n') + await assert.rejects(checkHostClient(source, written), /stale: host-client\.mjs/) +}) + +test('the check refuses a changed project, client or install that leaves the output bytes equal', async t => { + const source = await preview(t, { embedProject: false }) + withBregctl(t, join(source, 'bregctl')) + const written = await output(t) + + await buildHostClient(source, written) + await writeFile(join(source, 'project/registry.yaml'), 'id: another-project\n') + await assert.rejects(checkHostClient(source, written), /stale: host-client\.json/) + + await buildHostClient(source, written) + const manifest = join(source, 'node_modules/@registrystack/client/package.json') + await writeFile(manifest, (await readFile(manifest, 'utf8')).replace('0.52.0-test', '0.52.1-test')) + await lock(source, '0.52.1-test') + await assert.rejects(checkHostClient(source, written), /stale: host-client\.json/) + + await buildHostClient(source, written) + await writeFile(join(source, 'node_modules/@registrystack/client/dist/unused.js'), '// added after install\n') + await assert.rejects(checkHostClient(source, written), /stale: host-client\.json/) +}) + +test('refuses a client the preview lock does not pin by integrity', async t => { + const source = await preview(t) + withBregctl(t, join(source, 'bregctl')) + await writeFile(join(source, 'package-lock.json'), JSON.stringify({ packages: {} })) + await assert.rejects(buildHostClient(source, await output(t)), /does not pin/) +}) + +test('reports a generator failure', async t => { + const source = await preview(t) + withBregctl(t, '/bin/true') + await assert.rejects(buildHostClient(source, await output(t)), /could not generate the host client/) +}) diff --git a/deploy/examples/business-registration/tests/bundle/functions/register-business.mjs b/deploy/examples/business-registration/tests/bundle/functions/register-business.mjs new file mode 100644 index 0000000000..34cd8faf87 --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/functions/register-business.mjs @@ -0,0 +1,4 @@ +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' }) +} diff --git a/deploy/examples/business-registration/tests/bundle/manifest.json b/deploy/examples/business-registration/tests/bundle/manifest.json new file mode 100644 index 0000000000..55b5cbd5f1 --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/manifest.json @@ -0,0 +1 @@ +{"version":"registry-preview test","declarationDigest":"0000000000000000000000000000000000000000000000000000000000000000","product":{"id":"businesses","member":"businesses","audience":"urn:example:businesses","profile":"business-registrar"},"routeProducts":[],"preview":{"page":"/","functions":["register-business"]},"functions":["register-business"],"staticOutput":"project/web/dist"} diff --git a/deploy/examples/business-registration/tests/bundle/project/web/dist/app.js b/deploy/examples/business-registration/tests/bundle/project/web/dist/app.js new file mode 100644 index 0000000000..9085aa8b6a --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/project/web/dist/app.js @@ -0,0 +1 @@ +document.title = "Register a business" diff --git a/deploy/examples/business-registration/tests/bundle/project/web/dist/assets.json b/deploy/examples/business-registration/tests/bundle/project/web/dist/assets.json new file mode 100644 index 0000000000..65c178afbf --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/project/web/dist/assets.json @@ -0,0 +1 @@ +{"synthetic": true} diff --git a/deploy/examples/business-registration/tests/bundle/project/web/dist/assets/note.txt b/deploy/examples/business-registration/tests/bundle/project/web/dist/assets/note.txt new file mode 100644 index 0000000000..e497d4a3f7 --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/project/web/dist/assets/note.txt @@ -0,0 +1 @@ +synthetic asset diff --git "a/deploy/examples/business-registration/tests/bundle/project/web/dist/caf\303\251.txt" "b/deploy/examples/business-registration/tests/bundle/project/web/dist/caf\303\251.txt" new file mode 100644 index 0000000000..06ac679bc1 --- /dev/null +++ "b/deploy/examples/business-registration/tests/bundle/project/web/dist/caf\303\251.txt" @@ -0,0 +1 @@ +synthetic non-ASCII name diff --git a/deploy/examples/business-registration/tests/bundle/project/web/dist/index.html b/deploy/examples/business-registration/tests/bundle/project/web/dist/index.html new file mode 100644 index 0000000000..81e5c14d58 --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/project/web/dist/index.html @@ -0,0 +1,3 @@ + +Register a business + diff --git a/deploy/examples/business-registration/tests/bundle/project/web/dist/service.css b/deploy/examples/business-registration/tests/bundle/project/web/dist/service.css new file mode 100644 index 0000000000..693ce9b840 --- /dev/null +++ b/deploy/examples/business-registration/tests/bundle/project/web/dist/service.css @@ -0,0 +1 @@ +body { font-family: sans-serif; } diff --git a/deploy/examples/business-registration/tests/cleanup-preview.sh b/deploy/examples/business-registration/tests/cleanup-preview.sh new file mode 100644 index 0000000000..683f7e5c6e --- /dev/null +++ b/deploy/examples/business-registration/tests/cleanup-preview.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +state=${1:?Pass the disposable rstack development state directory} +[[ "$state" == /* && "$state" != / ]] || { + printf 'Pass an absolute preview state directory.\n' >&2 + exit 2 +} + +# The driver creates a fresh state root for every run. rstack labels its +# managed PostgreSQL volume with that root before it starts a container. +volume_scope="label=org.registrystack.rstack.state-root=$state" +volumes=$(docker volume ls -q --filter "$volume_scope") +if [[ -z "$volumes" ]]; then exit 0; fi +while IFS= read -r volume; do + container_filter=(--filter label=org.registrystack.rstack.dev-run --filter "volume=$volume") + containers=$(docker ps -aq "${container_filter[@]}") + if [[ -n "$containers" ]]; then + mapfile -t ids <<<"$containers" + if ! docker rm --force "${ids[@]}"; then + printf 'Could not remove the disposable preview container.\n' >&2 + exit 1 + fi + fi + remaining=$(docker ps -aq "${container_filter[@]}") + if [[ -n "$remaining" ]]; then + printf 'A disposable preview container survived cleanup.\n' >&2 + exit 1 + fi + docker volume rm "$volume" +done <<<"$volumes" +remaining=$(docker volume ls -q --filter "$volume_scope") +if [[ -n "$remaining" ]]; then + printf 'A disposable preview volume survived cleanup.\n' >&2 + exit 1 +fi diff --git a/deploy/examples/business-registration/tests/host.test.mjs b/deploy/examples/business-registration/tests/host.test.mjs index 4accdddacc..7d4b90746e 100644 --- a/deploy/examples/business-registration/tests/host.test.mjs +++ b/deploy/examples/business-registration/tests/host.test.mjs @@ -1,11 +1,42 @@ import assert from 'node:assert/strict' import { mkdtemp, mkdir, writeFile, rm, symlink } from 'node:fs/promises' import { tmpdir } from 'node:os' +import { request as httpRequest } from 'node:http' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' import { test } from 'node:test' +import { pathToFileURL } from 'node:url' import { bundleDigest, startHost } from '../host.mjs' -async function fixture(t) { +// REFERENCE_HOLDER_MODULE names the client's holder-function module, such as the repository's +// clients/typescript/holder-function.ts, standing in for the generated host client's copy. +if (!process.env.REFERENCE_HOLDER_MODULE) throw new Error('Set REFERENCE_HOLDER_MODULE to the holder-function module.') +const { createHolderActionHandler } = await import(pathToFileURL(process.env.REFERENCE_HOLDER_MODULE).href) + +const route = '/functions/register-business' +const attemptKey = '00000000-0000-4000-8000-000000000052' +const recordId = '00000000-0000-4000-8000-000000000001' +const submission = { legalName: ' Harbour Bicycle Cooperative ', registrationNumber: ' BR-2026-001' } + +// The bundle's function: prepare trims, and records what it received. Its default export +// is the rstack dev wiring, which the reference host must never call. +const registrationModule = ` + export function prepare(value, options) { + globalThis.referencePrepareCalls?.push({ value, keys: Object.keys(options ?? {}) }) + if (value.legalName === 'name an owner') return { ...value, owner: 'someone-else' } + if (value.legalName === 'change on reread') { + let reads = 0 + return { + get legalName() { return ++reads === 1 ? 'Checked Name' : 'x'.repeat(500) }, + registrationNumber: 'BR-1', + } + } + return { legalName: value.legalName.trim(), registrationNumber: value.registrationNumber.trim() } + } + export default () => { globalThis.referenceDefaultCalled = true; throw new Error('never call the preview wiring') } +` + +async function fixture(t, module = registrationModule) { const root = await mkdtemp(join(tmpdir(), 'reference-host-test-')) t.after(() => rm(root, { recursive: true })) await mkdir(join(root, 'functions')) @@ -16,32 +47,186 @@ async function fixture(t) { 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' }) - } - `) + await writeFile(join(root, 'functions/register-business.mjs'), module) 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 => { +// The generated server client, standing in for the one the recipe step generates. +function generatedClient() { + const calls = [] + return { + calls, + client: { + createHolderActionHandler, + createRegistryServerClient({ baseUrl, token }) { + return { + businesses: { + async invoke(action, input, options) { + calls.push({ baseUrl, credential: token(), action, input, options: { ...options, signal: !!options.signal } }) + return { data: { results: { business: { recordId, revision: 1 } } } } + }, + }, + } + }, + }, + } +} + +async function start(t, root, generated = generatedClient()) { + const outcomes = [] + globalThis.referencePrepareCalls = [] + globalThis.referenceDefaultCalled = false + const host = await startHost(root, await bundleDigest(root), { + functionsPort: 0, pagesPort: 0, client: generated.client, report: outcome => outcomes.push(outcome), + }) + t.after(host.close) + return { host, outcomes, calls: generated.calls } +} + +function post(origin, { path = route, body = submission, authorization = 'Bearer synthetic.caller.token', key = attemptKey, type = 'application/json' } = {}) { + const headers = { 'content-type': type, 'idempotency-key': key } + if (authorization) headers.authorization = authorization + return fetch(origin + path, { method: 'POST', headers, body: typeof body === 'string' ? body : JSON.stringify(body) }) +} + +test('the host prepares with the bundle and invokes register-business with the caller credential', async t => { + const { host, outcomes, calls } = await start(t, await fixture(t)) + const response = await post(host.functionsOrigin) + assert.equal(response.status, 200) + assert.deepEqual(await response.json(), { recordId }) + assert.deepEqual(calls, [{ + baseUrl: 'http://127.0.0.1:8100', + credential: 'synthetic.caller.token', + action: 'register-business', + input: { legalName: 'Harbour Bicycle Cooperative', registrationNumber: 'BR-2026-001' }, + options: { accessProfile: 'business-registrar', idempotencyKey: attemptKey, signal: true }, + }]) + // The function saw the projected value and a signal, never the request or the credential. + assert.deepEqual(globalThis.referencePrepareCalls, [{ value: submission, keys: ['signal'] }]) + assert.equal(globalThis.referenceDefaultCalled, false) + assert.deepEqual(outcomes, [{ class: 'succeeded', attemptKey, status: 200 }]) +}) + +test('the host serves only the relayed function path', async t => { + const { host, outcomes, calls } = await start(t, await fixture(t)) + for (const path of ['/api/functions/register-business', route + '?unexpected=true', '/functions/other', route + '/']) { + assert.equal((await post(host.functionsOrigin, { path })).status, 404, path) + } + assert.equal(calls.length, 0) + assert.equal(globalThis.referencePrepareCalls.length, 0) + assert.deepEqual(outcomes, Array(4).fill({ class: 'request-refused', attemptKey: undefined, status: 404 })) +}) + +function send(origin, method, path = route) { + return new Promise((resolve, reject) => { + const sent = httpRequest(origin + path, { method }, response => { + response.resume() + response.on('end', () => resolve(response.statusCode)) + }) + sent.on('error', reject) + sent.end() + }) +} + +test('the host answers any other method with 405 and one outcome', async t => { + const { host, outcomes, calls } = await start(t, await fixture(t)) + for (const method of ['GET', 'PUT', 'TRACE']) { + assert.equal(await send(host.functionsOrigin, method), 405, method) + } + assert.equal(calls.length, 0) + assert.equal(globalThis.referencePrepareCalls.length, 0) + assert.deepEqual(outcomes, Array(3).fill({ class: 'request-refused', attemptKey: undefined, status: 405 })) +}) + +test('a body past the binding limit answers 413 with one outcome', async t => { + const { host, outcomes, calls } = await start(t, await fixture(t)) + assert.equal((await post(host.functionsOrigin, { body: 'x'.repeat(70_000) })).status, 413) + assert.equal(calls.length, 0) + assert.deepEqual(outcomes, [{ class: 'request-refused', attemptKey, status: 413 }]) +}) + +test('a failing outcome hook on the host leaves its own answer unchanged', async t => { + const logged = t.mock.method(console, 'error', () => {}) + const root = await fixture(t) + const host = await startHost(root, await bundleDigest(root), { + functionsPort: 0, pagesPort: 0, client: generatedClient().client, + report: () => { throw new Error('synthetic hook failure') }, + }) + t.after(host.close) + assert.equal((await post(host.functionsOrigin, { path: '/functions/other' })).status, 404) + assert.equal(await send(host.functionsOrigin, 'TRACE'), 405) + assert.deepEqual(logged.mock.calls.map(call => call.arguments), [ + ['The holder outcome hook failed.'], ['The holder outcome hook failed.'], + ]) +}) + +test('a prepared value is read once, so it cannot change after its check', async t => { + const { host, calls } = await start(t, await fixture(t)) + const response = await post(host.functionsOrigin, { body: { ...submission, legalName: 'change on reread' } }) + assert.equal(response.status, 200) + assert.deepEqual(calls[0].input, { legalName: 'Checked Name', registrationNumber: 'BR-1' }) +}) + +test('the host refuses requests outside the binding before preparation', async t => { + const { host, calls } = await start(t, await fixture(t)) + for (const [name, options, status] of [ + ['no bearer', { authorization: null }, 401], + ['two bearers', { authorization: 'Bearer a, Bearer b' }, 401], + ['no attempt key', { key: '' }, 400], + ['not JSON', { type: 'text/plain' }, 400], + ['extra member', { body: { ...submission, note: 'dropped' } }, 400], + ['owner member', { body: { ...submission, owner: 'someone-else' } }, 400], + ['name too long', { body: { ...submission, legalName: 'x'.repeat(161) } }, 400], + ['blank number', { body: { ...submission, registrationNumber: ' ' } }, 400], + ['too large', { body: 'x'.repeat(32_769) }, 413], + ]) { + assert.equal((await post(host.functionsOrigin, options)).status, status, name) + } + assert.equal(calls.length, 0) + assert.equal(globalThis.referencePrepareCalls.length, 0) +}) + +test('a preparation that names an owner is refused before BReg', async t => { + const { host, outcomes, calls } = await start(t, await fixture(t)) + const response = await post(host.functionsOrigin, { body: { ...submission, legalName: 'name an owner' } }) + assert.equal(response.status, 502) + assert.equal(calls.length, 0) + assert.deepEqual(outcomes, [{ class: 'preparation-refused', attemptKey, status: 502 }]) +}) + +test('the outcome log carries no submitted value and no credential', async t => { + const lines = [] + t.mock.method(console, 'log', line => lines.push(line)) + t.mock.method(console, 'error', line => lines.push(line)) const root = await fixture(t) - const host = await startHost(root, await bundleDigest(root), { functionsPort: 0, pagesPort: 0 }) + globalThis.referencePrepareCalls = [] + const generated = generatedClient() + const host = await startHost(root, await bundleDigest(root), { functionsPort: 0, pagesPort: 0, client: generated.client }) t.after(host.close) - const route = host.functionsOrigin + '/functions/register-business' - const headers = { authorization: 'Bearer synthetic.caller.token' } + await post(host.functionsOrigin) + await post(host.functionsOrigin, { authorization: null }) + assert.deepEqual(lines.map(line => JSON.parse(line)), [ + { event: 'holder-outcome', class: 'succeeded', attemptKey, status: 200 }, + { event: 'holder-outcome', class: 'unauthenticated', status: 401 }, + ]) + for (const value of ['synthetic.caller.token', 'Harbour', 'BR-2026-001', recordId]) { + assert.ok(!lines.join('\n').includes(value), value) + } +}) - 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) +test('a bundle without prepare is refused at start', async t => { + const root = await fixture(t, 'export default () => request => new Response(null)') + await assert.rejects( + startHost(root, await bundleDigest(root), { functionsPort: 0, pagesPort: 0, client: generatedClient().client }), + /must export prepare/, + ) +}) +test('the host serves only the page assets', async t => { + const { host } = await start(t, await fixture(t)) 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') @@ -61,7 +246,41 @@ 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/) + await assert.rejects(startHost(root, expected, { client: generatedClient().client }), /bundle digest differs/) +}) + +test('pins the digest rstack dev export-preview prints for the same bundle', async () => { + // crates/registry-rstack-dev/src/preview_export.rs pins the same value for this fixture. + const fixture = fileURLToPath(new URL('./bundle', import.meta.url)) + assert.equal(await bundleDigest(fixture), '4156a7e44cde4dbb78af14ee722dffcdfd9388f7b70400bdd124ad935f44e2a4') +}) + +test('covers every file in the bundle, not only the files the host serves', async t => { + const root = await fixture(t) + const path = join(root, 'project/web/dist/extra.txt') + const bytes = Buffer.alloc(256 * 1024 + 1, 0x61) + await writeFile(path, bytes) + const expected = await bundleDigest(root) + bytes[bytes.length - 1] = 0x62 + await writeFile(path, bytes) + assert.notEqual(await bundleDigest(root), expected) +}) + +test('serves the page bytes verified at startup after the file changes', async t => { + const root = await fixture(t) + const expected = await bundleDigest(root) + const host = await startHost(root, expected, { functionsPort: 0, pagesPort: 0, client: generatedClient().client }) + t.after(() => host.close()) + await writeFile(join(root, 'project/web/dist/index.html'), 'replacement') + assert.equal(await (await fetch(host.pagesOrigin)).text(), 'index.html') +}) + +test('refuses a bundle without a file the host serves', async t => { + for (const missing of ['functions/register-business.mjs', 'project/web/dist/index.html']) { + const root = await fixture(t) + await rm(join(root, missing)) + await assert.rejects(bundleDigest(root), { code: 'ENOENT' }, missing) + } }) test('refuses files that resolve outside the bundle', async t => { diff --git a/deploy/examples/business-registration/tests/prepare-inputs.mjs b/deploy/examples/business-registration/tests/prepare-inputs.mjs new file mode 100644 index 0000000000..53a7e4c257 --- /dev/null +++ b/deploy/examples/business-registration/tests/prepare-inputs.mjs @@ -0,0 +1,190 @@ +import { generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto' +import { chmod, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { functionRouteDifferences } from './routes.mjs' + +const [profile, root, yamlPath, previewProject] = process.argv.slice(2) +const { parse, stringify } = await import(pathToFileURL(yamlPath)) +const recipe = new URL('../', import.meta.url) +const read = async file => parse(await readFile(file, 'utf8')) +const write = async (path, value) => writeFile(join(root, path), value, { mode: 0o600 }) +const yaml = (path, value) => write(path, stringify(value, { aliasDuplicateObjects: false })) +const random = () => randomBytes(32).toString('hex') +const issuer = 'https://identity.reference.test:9443' +const app = 'https://127.0.0.1:8443' +const reviewAudience = 'urn:example:standalone-decision' +const producer = 'casework-fixture-requester' + +const bootstrap = random() +const databasePassword = random() +const admin = random() +const secretFiles = { + DB_CONFIG_PASSWORD: databasePassword, + REGISTRAR_CLIENT_SECRET: random(), + REGISTRAR_PASSWORD: random(), + SECOND_REGISTRAR_PASSWORD: random(), +} +if (profile === 'casework') { + secretFiles.CASEWORK_ADMIN_CLIENT_SECRET = random() + secretFiles.ADMIN_REVIEW_PASSWORD = random() +} +await write('postgres/bootstrap-password', bootstrap) +await write('postgres/thunderid-password', databasePassword) +await write('thunderid/bootstrap-secrets/DB_CONFIG_PASSWORD', databasePassword) +await write('thunderid/bootstrap-secrets/ADMIN_PASSWORD', admin) +for (const [name, value] of Object.entries(secretFiles)) { + await write('thunderid/secrets/' + name, value) + if (name.endsWith('_PASSWORD') && name !== 'DB_CONFIG_PASSWORD') await write('browser-passwords/' + name, value) +} +await write('session/secrets/registrar-client', secretFiles.REGISTRAR_CLIENT_SECRET) +await write('session/secrets/audit-key', random()) +await copyFile(new URL('thunderid.yaml', recipe), join(root, 'thunderid/bootstrap.yaml')) + +const databaseUrl = (user, password, database) => `postgresql://${user}:${password}@postgres:5432/${database}` +async function runtimeFiles(product, area, database, runtime, localFiles = true) { + const relative = `${product}/${area}` + const secrets = relative + '/secrets' + const role = database.replaceAll('-', '_') + await mkdir(join(root, secrets), { recursive: true }) + await write(secrets + '/runtime-database-url', databaseUrl(role + '_runtime', random(), database)) + await write(secrets + '/migration-database-url', databaseUrl(role + '_migration', random(), database)) + await write(secrets + '/admin-database-url', databaseUrl('postgres', bootstrap, 'postgres')) + await write(secrets + '/audit-key', random()) + const ca = join(root, secrets, 'database-ca') + await copyFile(join(root, 'trust/postgres-ca.pem'), ca) + await chmod(ca, 0o600) + if (product === 'breg') { + await write(secrets + '/cursor-key', random()) + runtime.database.roles = { runtime: role + '_runtime', migration: role + '_migration' } + } + await yaml(relative + '/runtime.yaml', runtime) + if (localFiles) { + const host = structuredClone(runtime) + host.package.root = join(root, relative, 'package') + host.secretProviders.file.root = join(root, secrets) + await yaml(product + '/identity-runtime.yaml', host) + } +} + +const breg = await read(new URL('breg-runtime.yaml', recipe)) +await runtimeFiles('breg', 'admin', 'business', breg) +const rehearsal = structuredClone(breg) +rehearsal.identity.databaseId = 'business-schema-test' +rehearsal.listener.bind = '127.0.0.1:0' +rehearsal.audit.path = '/run/rehearsal/audit.jsonl' +rehearsal.authentication.oidc.issuers.thunderid.jwksSource = { type: 'static', documentRef: 'secret:file/oidc-jwks' } +await runtimeFiles('breg', 'rehearsal', 'business_schema_test', rehearsal, false) +await mkdir(join(root, 'breg/rehearsal/package')) + +const jwtPart = value => Buffer.from(JSON.stringify(value)).toString('base64url') +const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }) +const kid = 'schema-test' +const jwk = { ...publicKey.export({ format: 'jwk' }), alg: 'RS256', use: 'sig', kid } +const now = Math.floor(Date.now() / 1000) +const claims = { + iss: issuer, aud: 'urn:example:business-register', + sub: '00000000-0000-4000-8000-000000000201', iat: now, exp: now + 1800, + jti: randomUUID(), client_id: 'business-registrar', azp: 'business-registrar', + registry_actor_kind: 'human', registry_office: 'central', scope: 'registry:business:register', +} +const unsigned = jwtPart({ alg: 'RS256', kid, typ: 'at+jwt' }) + '.' + jwtPart(claims) +await write('breg/rehearsal/secrets/oidc-jwks', JSON.stringify({ keys: [jwk] })) +await write('breg/rehearsal/secrets/test-token', unsigned + '.' + sign('sha256', Buffer.from(unsigned), privateKey).toString('base64url')) +const journeys = await read(join(previewProject, 'tests/journeys.yaml')) +await yaml('breg/rehearsal/credentials.yaml', { + apiVersion: 'id.registrystack.org/formats/breg/schema-test-credentials/v1', + kind: 'BRegSchemaTestCredentials', + bindings: journeys.journeys.flatMap(journey => journey.steps.map(step => ({ + journeyId: journey.id, stepId: step.id, credential: { type: 'bearer', tokenRef: 'secret:file/test-token' }, + }))), +}) + +const identity = await read(new URL('identity-deployment.yaml', recipe)) +const service = await read(new URL('service.yaml', recipe)) +const session = await read(new URL('session.yaml', recipe)) +const routeDifferences = functionRouteDifferences(session, await read(join(previewProject, '..', 'dev.yaml'))) +if (routeDifferences.length) { + throw new Error('session.yaml must forward exactly the declared browser functions: ' + routeDifferences.join('; ')) +} +if (profile === 'casework') { + const runtime = await read(new URL('casework/runtime.yaml', recipe)) + await runtimeFiles('casework', 'admin', 'reference_casework', runtime) + const managed = await read(new URL('../../../products/casework/examples/standalone-decision/casework.yaml', recipe)) + Object.assign(managed.trustedProducers.requester, { issuer, subject: producer }) + await yaml('casework/project/casework.yaml', managed) + + for (const [accessProfile, actorKind] of [['staff', 'human'], ['administrator', 'human'], ['requester', 'service']]) { + service.roles['casework-' + accessProfile] = { actorKind, accessProfiles: { casework: [accessProfile] } } + } + identity.sessionApps[0].products.push('casework') + identity.sessionApps[0].roles.push('casework-staff') + identity.users[0].roles.push('casework-staff') + identity.sessionApps.push({ + id: 'casework-admin', clientSecretRef: 'secret:env/CASEWORK_ADMIN_CLIENT_SECRET', origin: app, + redirectUris: [app + '/session/callback'], postLogoutRedirectUris: [app + '/session/signed-out'], + products: ['casework'], tokenAttributes: ['registry_actor_kind'], roles: ['casework-administrator'], + }) + identity.users.push({ + id: 'reference-review-admin', username: 'reference-review-admin', + email: 'reference-review-admin@example.invalid', passwordRef: 'secret:env/ADMIN_REVIEW_PASSWORD', + roles: ['casework-administrator'], + }) + identity.clients = [{ + id: producer, publicJwksFile: 'casework/producer.jwks.json', + roles: ['casework-requester'], + }] + const producerKey = generateKeyPairSync('ec', { namedCurve: 'P-256' }) + const metadata = { kid: 'reference-producer', alg: 'ES256', use: 'sig' } + await write('casework/producer.jwks.json', JSON.stringify({ + keys: [{ ...producerKey.publicKey.export({ format: 'jwk' }), ...metadata }], + })) + await write('casework/producer.jwk.json', JSON.stringify({ + ...producerKey.privateKey.export({ format: 'jwk' }), ...metadata, + })) + + session.modules.push({ + id: 'reviewer-tasks', product: 'casework', prefix: '/casework/', audience: reviewAudience, + signIns: ['registrar', 'casework-admin'], upstream: { cluster: 'reviewer-tasks', prefixRewrite: '/' }, + }) + session.signIns.registrar.scopes.push('casework:staff') + session.signIns['casework-admin'] = { + clientId: 'casework-admin', clientSecretRef: 'secret:file/admin-client', scopes: ['casework:admin'], + } + session.pages.push({ + prefix: '/admin/', signIn: 'casework-admin', upstream: { cluster: 'admin-pages', prefixRewrite: '/' }, + }) + await write('session/secrets/admin-client', secretFiles.CASEWORK_ADMIN_CLIENT_SECRET) +} +await yaml('service.yaml', service) +await yaml('identity-deployment.yaml', identity) +await yaml('session.yaml', session) + +if (profile === 'casework') { + const edge = await read(new URL('edge.yaml', recipe)) + const upstreams = await read(new URL('upstreams.yaml', recipe)) + const loopback = port_value => ({ socket_address: { address: '127.0.0.1', port_value } }) + function addRelay(config, name, listen, target) { + config.static_resources.listeners.push({ + name, address: listen, + 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: name, cluster: name, + }, + }] }], + }) + config.static_resources.clusters.push({ + name, type: 'STATIC', connect_timeout: '2s', + load_assignment: { cluster_name: name, endpoints: [{ lb_endpoints: [{ endpoint: { address: target } }] }] }, + }) + } + for (const [name, front, target] of [['reviewer-tasks', 8500, 8500], ['admin-pages', 8501, 8200]]) { + const path = '/run/relay/' + name + '.sock' + addRelay(edge, name, loopback(front), { pipe: { path } }) + addRelay(upstreams, name, { pipe: { path, mode: 0o600 } }, loopback(target)) + } + await yaml('casework/edge.yaml', edge) + await yaml('casework/upstreams.yaml', upstreams) +} diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs new file mode 100644 index 0000000000..938df732a3 --- /dev/null +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict' +import { realpathSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' + +const refusal = { status: 403, code: 'profile.not-authorized' } + +export function assertReceipt(profile, receipt) { + assert.equal(receipt.noBrowserAuthorizationHeader, true) + if (profile === 'casework') { + assert.equal(receipt.reviewerSignIns, 1) + assert.deepEqual(receipt.authorizedAudiences, [ + 'urn:example:business-register', + 'urn:example:standalone-decision', + ]) + assert.equal(receipt.sameReviewerSubject, true) + assert.equal(receipt.businessRead, 200) + assert.equal(receipt.caseworkRead, 200) + assert.deepEqual(receipt.reviewerAdminRefusal, refusal) + assert.deepEqual(receipt.citizenCaseworkRefusal, refusal) + return + } + assert.equal(profile, 'breg') + assert.equal(receipt.distinctSubjects, true) + assert.equal(receipt.separateContexts, true) + for (const asset of ['index.html', 'app.js', 'service.css']) { + assert.match(receipt.assetSha256[asset], /^[a-f0-9]{64}$/u) + } + assert.deepEqual(receipt.formSubmissions, [200, 200]) + assert.deepEqual(receipt.owningRecordReads, [200, 200]) + assert.deepEqual(receipt.first, { + signOut: 303, recordAfterSignOut: 401, staleCookieSent: true, staleCookie: 401, signInRequired: true, + }) + assert.deepEqual(receipt.second, { sameSubjectAfterFirstSignOut: true, owningRead: 200 }) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) { + const [profile, path] = process.argv.slice(2) + assertReceipt(profile, JSON.parse(await readFile(path, 'utf8'))) +} diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs new file mode 100644 index 0000000000..70170f28a2 --- /dev/null +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { assertReceipt } from './receipt.mjs' + +const baseline = { + distinctSubjects: true, + separateContexts: true, + assetSha256: Object.fromEntries(['index.html', 'app.js', 'service.css'].map(name => [name, 'a'.repeat(64)])), + formSubmissions: [200, 200], + owningRecordReads: [200, 200], + first: { signOut: 303, recordAfterSignOut: 401, staleCookieSent: true, staleCookie: 401, signInRequired: true }, + second: { sameSubjectAfterFirstSignOut: true, owningRead: 200 }, + noBrowserAuthorizationHeader: true, +} + +const casework = { + reviewerSignIns: 1, + authorizedAudiences: ['urn:example:business-register', 'urn:example:standalone-decision'], + sameReviewerSubject: true, + businessRead: 200, + caseworkRead: 200, + reviewerAdminRefusal: { status: 403, code: 'profile.not-authorized' }, + citizenCaseworkRefusal: { status: 403, code: 'profile.not-authorized' }, + noBrowserAuthorizationHeader: true, +} + +test('baseline receipt pins the two registrar sessions and logout', () => { + assertReceipt('breg', baseline) + assert.throws(() => assertReceipt('unknown', baseline)) + for (const [key, value] of Object.entries({ + distinctSubjects: false, + separateContexts: false, + assetSha256: { ...baseline.assetSha256, 'app.js': 'unverified' }, + formSubmissions: [200, 400], + owningRecordReads: [200, 403], + first: { ...baseline.first, staleCookie: 200 }, + second: { ...baseline.second, owningRead: 401 }, + noBrowserAuthorizationHeader: false, + })) { + assert.throws(() => assertReceipt('breg', { ...baseline, [key]: value }), key) + } +}) + +test('the receipt command checks files when invoked through a symlink', () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-receipt-')) + try { + const link = join(scratch, 'receipt.mjs') + const report = join(scratch, 'report.json') + symlinkSync(fileURLToPath(new URL('./receipt.mjs', import.meta.url)), link) + writeFileSync(report, JSON.stringify(casework)) + assert.equal(spawnSync(process.execPath, [link, 'casework', report]).status, 0) + writeFileSync(report, '{}') + assert.equal(spawnSync(process.execPath, [link, 'casework', report]).status, 1) + } finally { + rmSync(scratch, { recursive: true }) + } +}) + +test('Casework receipt pins both positive reads and product refusals', () => { + assertReceipt('casework', casework) + for (const [key, value] of Object.entries({ + reviewerSignIns: 2, + authorizedAudiences: ['urn:example:business-register'], + sameReviewerSubject: false, + businessRead: 401, + caseworkRead: 401, + reviewerAdminRefusal: { status: 403, code: 'session.forbidden' }, + citizenCaseworkRefusal: { status: 403, code: 'session.forbidden' }, + noBrowserAuthorizationHeader: false, + })) { + assert.throws(() => assertReceipt('casework', { ...casework, [key]: value }), key) + } +}) diff --git a/deploy/examples/business-registration/tests/routes.mjs b/deploy/examples/business-registration/tests/routes.mjs new file mode 100644 index 0000000000..5d15236b53 --- /dev/null +++ b/deploy/examples/business-registration/tests/routes.mjs @@ -0,0 +1,34 @@ +// The reference host forwards a browser function route only when the preview +// declaration names that function, the same list the development gateway +// relays. BReg's own module stays at the product root: Session's checked +// product-client binding requires a module that rewrites to `/`. + +const PUBLIC_MOUNT = '/api/functions/' +const HOST_MOUNT = '/functions/' +const CLUSTER = 'functions' +const NAME = /^[a-z][a-z0-9-]*$/ + +const describe = route => `${route.prefix} -> ${route.rewrite}` + +export function declaredFunctionRoutes(declaration) { + const names = declaration?.preview?.functions + if (!Array.isArray(names) || names.length === 0 || !names.every(name => NAME.test(name))) { + throw new Error('The preview declaration must name its browser functions in preview.functions.') + } + if (names.length > 1) { + // Checked routes need one exclusive cluster each; the reference has one. + throw new Error('Give each further function its own cluster: checked routes need one exclusive cluster per route.') + } + return names.map(name => ({ prefix: PUBLIC_MOUNT + name, rewrite: HOST_MOUNT + name })) +} + +export function functionRouteDifferences(session, declaration) { + const declared = declaredFunctionRoutes(declaration).map(describe) + const forwarded = (session?.modules ?? []) + .filter(module => module?.upstream?.cluster === CLUSTER) + .map(module => describe({ prefix: module.prefix, rewrite: module.upstream.prefixRewrite })) + return [ + ...forwarded.filter(route => !declared.includes(route)).map(route => 'forwarded but not declared: ' + route), + ...declared.filter(route => !forwarded.includes(route)).map(route => 'declared but not forwarded: ' + route), + ] +} diff --git a/deploy/examples/business-registration/tests/routes.test.mjs b/deploy/examples/business-registration/tests/routes.test.mjs new file mode 100644 index 0000000000..7513a738f8 --- /dev/null +++ b/deploy/examples/business-registration/tests/routes.test.mjs @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { test } from 'node:test' +import { pathToFileURL } from 'node:url' +import { declaredFunctionRoutes, functionRouteDifferences } from './routes.mjs' + +const declaration = { preview: { functions: ['register-business'] } } +const narrowed = { + modules: [ + { + id: 'businesses', product: 'breg', prefix: '/registry/businesses/', + upstream: { cluster: 'registry', prefixRewrite: '/' }, + }, + { + id: 'functions', product: 'breg', prefix: '/api/functions/register-business', + upstream: { cluster: 'functions', prefixRewrite: '/functions/register-business' }, + }, + ], +} +const withModule = (change) => ({ + modules: narrowed.modules.map(module => module.id === 'functions' ? change(structuredClone(module)) : module), +}) + +test('each declared function becomes one exact function route', () => { + assert.deepEqual(declaredFunctionRoutes(declaration), [ + { prefix: '/api/functions/register-business', rewrite: '/functions/register-business' }, + ]) +}) + +test('the narrowed reference matches its declaration', () => { + assert.deepEqual(functionRouteDifferences(narrowed, declaration), []) +}) + +test('a whole functions prefix is a difference', () => { + const wide = withModule(module => ({ + ...module, prefix: '/api/functions/', upstream: { ...module.upstream, prefixRewrite: '/functions/' }, + })) + assert.deepEqual(functionRouteDifferences(wide, declaration), [ + 'forwarded but not declared: /api/functions/ -> /functions/', + 'declared but not forwarded: /api/functions/register-business -> /functions/register-business', + ]) +}) + +test('an undeclared or missing function route is a difference', () => { + const other = withModule(module => ({ + ...module, prefix: '/api/functions/close-business', + upstream: { ...module.upstream, prefixRewrite: '/functions/close-business' }, + })) + assert.equal(functionRouteDifferences(other, declaration).length, 2) + const none = { modules: narrowed.modules.filter(module => module.id !== 'functions') } + assert.deepEqual(functionRouteDifferences(none, declaration), [ + 'declared but not forwarded: /api/functions/register-business -> /functions/register-business', + ]) +}) + +test('a rewrite to another function is a difference', () => { + const crossed = withModule(module => ({ + ...module, upstream: { ...module.upstream, prefixRewrite: '/functions/close-business' }, + })) + assert.equal(functionRouteDifferences(crossed, declaration).length, 2) +}) + +test('the declaration must name its functions', () => { + for (const broken of [{}, { preview: {} }, { preview: { functions: [] } }, { preview: { functions: ['Bad Name'] } }]) { + assert.throws(() => declaredFunctionRoutes(broken), /function/) + } + // Checked routes need one exclusive cluster each, so a second function needs + // its own cluster before the reference can forward it. + assert.throws( + () => declaredFunctionRoutes({ preview: { functions: ['register-business', 'close-business'] } }), + /one exclusive cluster/, + ) +}) + +test('the reference session forwards exactly the preview declaration', async t => { + const module = process.env.REFERENCE_YAML_MODULE + if (!module) { + t.skip('Set REFERENCE_YAML_MODULE to a yaml package entry to check the shipped files.') + return + } + const { parse } = await import(pathToFileURL(module)) + const read = async url => parse(await readFile(url, 'utf8')) + const session = await read(new URL('../session.yaml', import.meta.url)) + const dev = await read(new URL( + '../../../../products/platform/examples/service-previews/business-registration/dev.yaml', + import.meta.url, + )) + assert.deepEqual(functionRouteDifferences(session, dev), []) +}) diff --git a/deploy/examples/business-registration/tests/run-reference.sh b/deploy/examples/business-registration/tests/run-reference.sh new file mode 100644 index 0000000000..e64018640d --- /dev/null +++ b/deploy/examples/business-registration/tests/run-reference.sh @@ -0,0 +1,459 @@ +#!/usr/bin/env bash +set -euo pipefail + +refuse() { + printf 'Reference host proof refused. %s\n' "$1" >&2 + exit 1 +} + +phase() { + printf 'Reference host phase: %s\n' "$1" >&2 +} + +candidate=false +chromium_options=() +if [[ ${1:-} == --candidate ]]; then + candidate=true + export REFERENCE_ARTIFACTS=${2:?Pass the absolute verified candidate stage directory} + receipt=${3:?Pass an absolute path for the proof receipt} + if [[ $# == 4 && $4 == --with-deps ]]; then + chromium_options+=(--with-deps) + elif [[ $# != 3 ]]; then + refuse 'Pass the stage and receipt paths, followed by optional --with-deps.' + fi + [[ "$REFERENCE_ARTIFACTS" == /* ]] || refuse 'Pass an absolute stage path.' + [[ "$(uname -s):$(uname -m)" == Linux:x86_64 ]] || refuse 'Use a Linux amd64 host.' + [[ "$(node --version)" == v24.* ]] || refuse 'Use Node.js 24.' + binding="$REFERENCE_ARTIFACTS/inputs.json" + profile=$(jq -er '.profile' "$binding") + unset REFERENCE_TEST_CHROMIUM + unset GH_TOKEN GITHUB_TOKEN GH_ENTERPRISE_TOKEN GITHUB_ENTERPRISE_TOKEN +else + profile=${1:?Pass breg or casework} + export REFERENCE_ARTIFACTS=${2:?Pass the absolute directory containing the CI-profile or release-profile binaries} + playwright=${3:?Pass the absolute Playwright module path} + yaml=${4:?Pass the absolute YAML module path} + receipt=${5:?Pass an absolute path for the browser receipt} + [[ "$playwright" == /* && "$yaml" == /* ]] || refuse 'Pass absolute module paths.' +fi +case "$profile" in + breg | casework) ;; + *) refuse 'Choose breg or casework.' ;; +esac +[[ "$REFERENCE_ARTIFACTS" == /* && "$receipt" == /* && ! -e "$receipt" && ! -L "$receipt" ]] || + refuse 'Use an absolute input directory and a new absolute receipt path.' + +binaries=(rstack breg bregctl registry-session) +if [[ "$profile" == casework ]]; then binaries+=(casework caseworkctl); fi +for bin in "${binaries[@]}"; do + [[ -x "$REFERENCE_ARTIFACTS/$bin" ]] || refuse "Missing executable $bin." +done + +recipe=$(realpath -- "$(dirname -- "${BASH_SOURCE[0]}")/..") +repo=$(realpath -- "$recipe/../../..") +client="$repo/clients/typescript" +export REFERENCE_UID REFERENCE_GID +REFERENCE_UID=$(id -u) +REFERENCE_GID=$(id -g) +[[ "$REFERENCE_UID" != 0 ]] || refuse 'Run as a nonroot operator with sudo for disposable input ownership.' +umask 077 + +image_id() { + local name=$1 ref=$2 + [[ "$ref" =~ ^ghcr\.io/registrystack/${name}-candidate@sha256:[a-f0-9]{64}$ && + "${ref##*@sha256:}" != "$(printf '%064d' 0)" ]] || + refuse "Expected a real private digest for $name." + docker image inspect "$ref" | + jq -er --arg ref "$ref" --arg source "$source" --arg version "$version" ' + .[0] | select(.Os == "linux" and .Architecture == "amd64" and + (.RepoDigests | index($ref))) | + .Config.Labels as $labels | + select($labels["org.opencontainers.image.source"] == "https://github.com/registrystack/registry-stack" and + $labels["org.opencontainers.image.revision"] == $source and + $labels["org.opencontainers.image.version"] == $version) | .Id' +} + +declare -A verified_images=() +export REFERENCE_SESSION_DIGEST +if "$candidate"; then + version=$(jq -er '.release.version' "$binding") + source=$(jq -er '.release.source_sha' "$binding") + for name in "${binaries[@]}" client.tgz; do + sha=$(jq -er --arg name "$name" '.assets[$name].sha256 | select(test("^[a-f0-9]{64}$"))' "$binding") + printf '%s %s\n' "$sha" "$REFERENCE_ARTIFACTS/$name" | sha256sum --check --strict --quiet + done + image_names=(breg registry-session) + if [[ "$profile" == casework ]]; then image_names+=(casework); fi + for name in "${image_names[@]}"; do + ref=$(jq -er --arg name "$name" '.images[$name]' "$binding") + verified_images[$name]=$(image_id "$name" "$ref") || + refuse "The local $name image differs from the candidate digest, platform, or OCI provenance." + case "$name" in + breg) export CANDIDATE_BREG_IMAGE="$ref" ;; + registry-session) export CANDIDATE_SESSION_IMAGE="$ref" ;; + casework) export CANDIDATE_CASEWORK_IMAGE="$ref" ;; + esac + done + REFERENCE_SESSION_DIGEST=${CANDIDATE_SESSION_IMAGE##*@} +else + # The local overlay runs the same shared CI-profile Session executable. + REFERENCE_SESSION_DIGEST="sha256:$(printf '%064d' 0)" +fi + +scratch=$(realpath -- "$(mktemp -d)") +project=reference-${profile}-$(openssl rand -hex 8) +export REFERENCE_CONFIG="$scratch/input" +export REFERENCE_HOST_CLIENT="$scratch/host-client" +export BUSINESS_BUNDLE="$scratch/bundle" +export BUSINESS_BUNDLE_SHA256=preparing +export RSTACK_BREG_BIN="$REFERENCE_ARTIFACTS/breg" +export RSTACK_BREGCTL_BIN="$REFERENCE_ARTIFACTS/bregctl" +export RSTACK_CASEWORKCTL_BIN="$REFERENCE_ARTIFACTS/caseworkctl" +export RSTACK_DEV_STATE_DIR="$scratch/dev-state" +unset RSTACK_DEV_DATABASE_URL RSTACK_DEV_DATABASE_CA RSTACK_PREVIEW_CONFIG COMPOSE_PROFILES +rstack="$REFERENCE_ARTIFACTS/rstack" +compose_files=("$recipe/compose.yaml") +if ! "$candidate"; then compose_files+=("$recipe/compose.local.yaml"); fi +if [[ "$profile" == casework ]]; then compose_files+=("$recipe/casework/compose.yaml"); fi +if "$candidate"; then + export REFERENCE_HOST="$REFERENCE_HOST_CLIENT" + export CANDIDATE_BREG_ADMIN_DIR="$REFERENCE_CONFIG/breg/admin" + export PLAYWRIGHT_BROWSERS_PATH="$scratch/chromium" + compose_files+=("$repo/release/scripts/candidate-host.compose.yaml") + if [[ "$profile" == casework ]]; then + compose_files+=("$repo/release/scripts/candidate-host-casework.compose.yaml") + fi +fi +compose=(docker compose --env-file /dev/null --project-name "$project") +for path in "${compose_files[@]}"; do + compose+=(--file "$path") +done +run=("${compose[@]}" run -T --rm) +up=("${compose[@]}" up --wait --wait-timeout 60 --no-build) +down=("${compose[@]}" --profile setup down --volumes --remove-orphans) +if "$candidate"; then + run+=(--pull never) + up+=(--pull never) +else + down+=(--rmi local) +fi + +proof_path="$scratch/browser-receipt.json" +cleanup() { + local status=$? containers volumes networks proof + trap - EXIT + phase 'clean up preview resources' + bash "$recipe/tests/cleanup-preview.sh" "$RSTACK_DEV_STATE_DIR" || status=1 + phase 'tear down Compose project' + "${down[@]}" || status=1 + phase 'verify Compose teardown' + if ! containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || + ! volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || + ! networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project"); then + printf 'Could not verify teardown of Compose project %s.\n' "$project" >&2 + status=1 + elif [[ -n "$containers$volumes$networks" ]]; then + printf 'Compose project %s still has resources.\n' "$project" >&2 + status=1 + fi + if ((status == 0)); then + phase 'finalize checked receipt' + proof=$(<"$proof_path") && + sudo -n chown -R --no-dereference "$REFERENCE_UID:$REFERENCE_GID" "$scratch" && + python3 -c 'import shutil, sys; shutil.rmtree(sys.argv[1])' "$scratch" && + (set -C && printf '%s\n' "$proof" >"$receipt") || status=1 + fi + if ((status == 0)) && ! "$candidate"; then cat "$receipt" || status=1; fi + if ((status == 0)); then phase 'complete'; fi + if ((status != 0)); then + printf 'Reference host proof failed. Inspect private inputs and logs in %s if retained.\n' "$scratch" >&2 + fi + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +printf 'Reference project %s, scratch directory %s\n' "$project" "$scratch" >&2 + +preview="$scratch/preview" +cp -R "$repo/products/platform/examples/service-previews/business-registration" "$preview" +if "$candidate"; then + # The exact private candidate references are already present. The rendered + # model may add only public, digest-pinned support images. + model=$("${compose[@]}" --profile setup config --format json) + jq -e --arg breg "$CANDIDATE_BREG_IMAGE" --arg session "$CANDIDATE_SESSION_IMAGE" \ + --arg profile "$profile" --arg casework "${CANDIDATE_CASEWORK_IMAGE:-}" ' + .services.breg.image == $breg and .services["breg-admin"].image == $breg and + .services.session.image == $session and + (if $profile == "casework" then + .services.casework.image == $casework and .services["casework-admin"].image == $casework + else (.services | has("casework") | not) end) and + ([.services[] | has("build") | not] | all) and + ([.services[].image | test("@sha256:[a-f0-9]{64}$")] | all)' <<<"$model" >/dev/null + image_refs=$(jq -er '.services[].image' <<<"$model" | sort -u) + while IFS= read -r image; do + if [[ "$image" != "$CANDIDATE_BREG_IMAGE" && "$image" != "$CANDIDATE_SESSION_IMAGE" && + "$image" != "${CANDIDATE_CASEWORK_IMAGE:-}" ]]; then + docker pull --platform linux/amd64 "$image" + fi + done <<<"$image_refs" + + dependencies="$scratch/client" + install -d "$REFERENCE_HOST" "$dependencies" + cp "$recipe/"{package.json,package-lock.json,host.mjs} "$REFERENCE_HOST/" + cp "$client/"{package.json,package-lock.json} "$dependencies/" + npm --prefix "$REFERENCE_HOST" ci --omit=dev --ignore-scripts --no-audit --no-fund + npm --prefix "$dependencies" ci --ignore-scripts --no-audit --no-fund + node "$dependencies/node_modules/playwright-core/cli.js" install "${chromium_options[@]}" chromium + playwright="$dependencies/node_modules/playwright-core/index.mjs" + yaml="$dependencies/node_modules/yaml/dist/index.js" + archive="$REFERENCE_ARTIFACTS/client.tgz" +else + archive=$(npm pack "$client" --ignore-scripts --silent --pack-destination "$scratch") + archive="$scratch/$archive" +fi +node --input-type=module - "$repo" "$preview" "$archive" "${version:-}" <<'JS' +import assert from 'node:assert/strict' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +const [repo, preview, path, version] = process.argv.slice(2) +const { previewClientArchive, stagePreviewClient } = await import(pathToFileURL( + join(repo, 'products/platform/scripts/prepare-service-preview-locks.mjs'))) +const client = await previewClientArchive(path) +if (version) assert.equal(client.version, version) +await stagePreviewClient(preview, client, { pin: true }) +JS +npm ci --prefix "$preview" --ignore-scripts --no-audit --no-fund +if ! "$rstack" dev export-preview "$preview" --output "$BUSINESS_BUNDLE" --format json >"$scratch/export.json"; then + jq -r '.error.message // "Preview export failed."' "$scratch/export.json" >&2 + exit 1 +fi +BUSINESS_BUNDLE_SHA256=$(jq -er 'select(.status == "exported") | .bundleDigest | select(test("^[0-9a-f]{64}$"))' "$scratch/export.json") + +install -d "$REFERENCE_CONFIG"/{app-tls,issuer-tls,postgres/schema,trust,browser-passwords} +install -d "$REFERENCE_CONFIG"/{session/secrets,session/audit,breg/audit,breg/runtime,casework/audit,casework/runtime,casework/project} +install -d "$REFERENCE_CONFIG"/{thunderid/bootstrap-secrets,thunderid/secrets,gateway,gateway-checked,relay} +ca="$scratch/reference-ca" +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 2 -subj '/CN=Business registration smoke CA' -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign,cRLSign -keyout "$ca.key" -out "$ca.pem" 2>"$scratch/tls.log" +issue() { + local directory=$1 name=$2 san=$3 + openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj "/CN=$name" -keyout "$directory/$name.key" -out "$scratch/$name.csr" 2>>"$scratch/tls.log" + openssl x509 -req -in "$scratch/$name.csr" -CA "$ca.pem" -CAkey "$ca.key" -days 2 -extfile <(printf 'subjectAltName=%s\nextendedKeyUsage=serverAuth\nbasicConstraints=critical,CA:FALSE\n' "$san") -out "$directory/$name.crt" 2>>"$scratch/tls.log" +} +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" +fixture="$recipe/tests/prepare-inputs.mjs" +node "$fixture" "$profile" "$REFERENCE_CONFIG" "$yaml" "$preview/project" +# The host's register-business client, generated from the sealed project with the same bregctl. +node "$recipe/tests/build-host-client.mjs" "$preview" "$REFERENCE_HOST_CLIENT" +node "$recipe/tests/build-host-client.mjs" --check "$preview" "$REFERENCE_HOST_CLIENT" + +if "$candidate"; then + node_image=$(jq -er '.services.application.image' <<<"$model") + host_bundle_digest=$(docker run --rm --pull never --network none \ + --user "$REFERENCE_UID:$REFERENCE_GID" \ + --mount "type=bind,source=$REFERENCE_HOST,target=/app,readonly" \ + --mount "type=bind,source=$BUSINESS_BUNDLE,target=/run/bundle,readonly" \ + "$node_image" node /app/host.mjs --digest /run/bundle) + [[ "$host_bundle_digest" == "$BUSINESS_BUNDLE_SHA256" ]] || + refuse 'The host bundle digest differs from the preview export.' +else + "${compose[@]}" build application +fi + +for schema in config:configdb entity:entitydb runtime_transient:runtime_transient runtime_persistent:runtime_persistent; do + "${run[@]}" --no-deps --entrypoint cat thunderid-setup "dbscripts/${schema#*:}/postgres.sql" >"$REFERENCE_CONFIG/postgres/schema/${schema%%:*}.sql" +done +sudo -n chown -R 999:999 "$REFERENCE_CONFIG/postgres" +sudo -n chmod -R u=rwX,go= "$REFERENCE_CONFIG/postgres" +"${up[@]}" postgres +# Build the serving package from a separate TLS-backed schema-test database. +rehearse() ( + local -a rehearse_command=("${run[@]}") + if "$candidate"; then + export CANDIDATE_BREG_ADMIN_DIR="$REFERENCE_CONFIG/breg/rehearsal" + else + rehearse_command+=(--volume "$REFERENCE_CONFIG/breg/rehearsal:/run/breg:ro") + fi + "${rehearse_command[@]}" --volume "$scratch/rehearsal:/run/rehearsal" \ + --volume "$preview/project:/run/project:ro" breg-admin "$@" +) +install -d "$scratch/rehearsal" +rehearse provision --posture production --runtime-config /run/breg/runtime.yaml --admin-url-file /run/breg/secrets/admin-database-url +rehearse test /run/project --posture production --runtime-config /run/breg/runtime.yaml --credentials /run/breg/credentials.yaml --output /run/rehearsal/receipt.json +rehearse package /run/project --posture production --test-receipt /run/rehearsal/receipt.json --output /run/rehearsal/build --format json >"$scratch/package.json" +digest=$(jq -er '.packageDigest | select(test("^sha256:[a-f0-9]{64}$"))' "$scratch/package.json") +cp -R "$scratch/rehearsal/build/package" "$REFERENCE_CONFIG/breg/admin/package" + +identity_extra=() +upstreams=(--upstream registry=127.0.0.1:8100 --upstream pages=127.0.0.1:8200 --upstream functions=127.0.0.1:8300) +if [[ "$profile" == casework ]]; then + identity_extra=(--casework-project "$REFERENCE_CONFIG/casework/project" --casework-runtime-config "$REFERENCE_CONFIG/casework/identity-runtime.yaml") + upstreams+=(--upstream reviewer-tasks=127.0.0.1:8500 --upstream admin-pages=127.0.0.1:8501) +fi +generated="$scratch/identity" +"$rstack" identity generate thunderid --deployment "$REFERENCE_CONFIG/identity-deployment.yaml" --breg-project "$preview/project" --breg-runtime-config "$REFERENCE_CONFIG/breg/identity-runtime.yaml" --breg-production --expected-issuer https://identity.reference.test:9443 "${identity_extra[@]}" --output "$generated" +install -d "$REFERENCE_CONFIG/thunderid/"{resources,front-gateway} +install -m 0600 "$generated/resources/resources.yaml" "$REFERENCE_CONFIG/thunderid/resources/" +install -m 0600 "$generated/front-gateway/envoy.yaml" "$REFERENCE_CONFIG/thunderid/front-gateway/" +install -m 0600 "$generated/identity-receipt.json" "$REFERENCE_CONFIG/thunderid/" +node --input-type=module - "$yaml" "$REFERENCE_CONFIG" "$generated" "$profile" <<'JS' +import { readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +const [yaml, config, generated, profile] = process.argv.slice(2) +const { parse, stringify } = await import(pathToFileURL(yaml)) +const read = async path => parse(await readFile(path, 'utf8')) +const base = await read(join(config, 'thunderid/bootstrap.yaml')) +const deployment = await read(join(generated, 'deployment.yaml')) +await writeFile(join(config, 'thunderid/deployment.yaml'), stringify({ ...base, ...deployment, server: { ...base.server, ...deployment.server } })) +if (profile === 'casework') { + const policyPath = join(config, 'casework/project/casework.yaml') + const policy = await read(policyPath) + const receipt = await read(join(generated, 'identity-receipt.json')) + const producer = receipt.clients['casework-fixture-requester'] + if (producer?.kind !== 'machine' || typeof producer.sub !== 'string' || !producer.sub) { + throw new Error('The identity generator did not bind the synthetic Casework producer.') + } + policy.trustedProducers.requester.subject = producer.sub + await writeFile(policyPath, stringify(policy)) +} +JS +session_file="$recipe/session.yaml" +if [[ "$profile" == casework ]]; then + session_file="$REFERENCE_CONFIG/session.yaml" +fi +session=("$REFERENCE_ARTIFACTS/registry-session" --runtime-config "$session_file") +"${session[@]}" gateway envoy --posture production \ + --standalone-out "$REFERENCE_CONFIG/gateway/envoy.json" --listen 127.0.0.1:8443 \ + "${upstreams[@]}" --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 + +sudo -n chown -R 10001:10001 "$REFERENCE_CONFIG/thunderid/"{bootstrap.yaml,deployment.yaml,resources,secrets,bootstrap-secrets} +sudo -n chmod -R u=rwX,go= "$REFERENCE_CONFIG/thunderid/"{bootstrap.yaml,deployment.yaml,resources,secrets,bootstrap-secrets} +"${run[@]}" thunderid-setup + +if [[ "$profile" == casework ]]; then + # The stock first bootstrap creates the password flow. A second setup admits + # only this recipe's generated agent and its exact public key. + install -d "$REFERENCE_CONFIG/thunderid/agent-secrets" + sudo -n cp "$REFERENCE_CONFIG/thunderid/bootstrap-secrets/ADMIN_PASSWORD" \ + "$REFERENCE_CONFIG/thunderid/secrets/"{DB_CONFIG_PASSWORD,REGISTRAR_CLIENT_SECRET,REGISTRAR_PASSWORD,SECOND_REGISTRAR_PASSWORD,CASEWORK_ADMIN_CLIENT_SECRET,ADMIN_REVIEW_PASSWORD} \ + "$REFERENCE_CONFIG/thunderid/agent-secrets/" + sudo -n chown -R 10001:10001 "$REFERENCE_CONFIG/thunderid/agent-secrets" + sudo -n chmod -R u=rwX,go= "$REFERENCE_CONFIG/thunderid/agent-secrets" + agents=("$generated/registry-schema/agents/"*.yaml) + [[ ${#agents[@]} == 1 && -f "${agents[0]}" ]] + sudo -n chown 10001:10001 "$generated/registry-schema/agent-type.yaml" "${agents[0]}" + "${run[@]}" --volume "$REFERENCE_CONFIG/thunderid/deployment.yaml:/opt/thunderid/deployment.yaml:ro" --volume "$REFERENCE_CONFIG/thunderid/resources:/opt/thunderid/config/resources:ro" --volume "$REFERENCE_CONFIG/thunderid/agent-secrets:/run/identity-secrets:ro" --volume "$generated/registry-schema/agent-type.yaml:/opt/thunderid/bootstrap/70-registry-agent-type.yaml:ro" --volume "${agents[0]}:/opt/thunderid/bootstrap/80-registry-agent.yaml:ro" thunderid-setup setup-casework + "$REFERENCE_ARTIFACTS/caseworkctl" package "$REFERENCE_CONFIG/casework/project" --posture production --output "$REFERENCE_CONFIG/casework/admin/package" + "${run[@]}" casework-admin provision --posture production --runtime-config /run/casework/runtime.yaml --admin-url-file /run/casework/secrets/admin-database-url + "${run[@]}" casework-admin apply --posture production --runtime-config /run/casework/runtime.yaml +fi +"${run[@]}" breg-admin provision --posture production --runtime-config /run/breg/runtime.yaml --admin-url-file /run/breg/secrets/admin-database-url +"${run[@]}" breg-admin apply --posture production --initial --runtime-config /run/breg/runtime.yaml --package /run/breg/package --expected-digest "$digest" +stage_runtime() { + local product=$1 root="$REFERENCE_CONFIG/$1" + install -d "$root/runtime/secrets" + cp -R "$root/admin/package" "$root/runtime/package" + install -m 0600 "$root/admin/runtime.yaml" "$root/runtime/" + for name in runtime-database-url database-ca audit-key; do + install -m 0600 "$root/admin/secrets/$name" "$root/runtime/secrets/" + done + if [[ "$product" == breg ]]; then + install -m 0600 "$root/admin/secrets/cursor-key" "$root/runtime/secrets/" + fi +} +stage_runtime breg +if [[ "$profile" == casework ]]; then stage_runtime casework; fi +if ! "${up[@]}"; then + "${compose[@]}" ps --all + "${compose[@]}" logs --no-log-prefix issuer-ready gateway-check + exit 1 +fi +if "$candidate"; then + for name in "${image_names[@]}"; do + svc=$name + if [[ "$name" == registry-session ]]; then svc=session; fi + container=$("${compose[@]}" ps --status running -q "$svc") + [[ -n "$container" ]] || refuse "The $svc container is not running." + [[ "$(docker inspect --format '{{.Image}}' "$container")" == "${verified_images[$name]}" ]] || + refuse "The running $svc container differs from the verified image." + done +fi +cmp "$REFERENCE_CONFIG/gateway/envoy.json" "$REFERENCE_CONFIG/gateway-checked/envoy.json" + +# TLS requests through the published gateway reach both Session listeners. +# The application shares the private loopback used by BReg and Casework. +serving_ready() { + local status + local -a https=(curl --disable --silent --noproxy '*' --cacert "$REFERENCE_CONFIG/trust/https-ca.pem" + --max-time 2 --output /dev/null --write-out '%{http_code}') + status=$("${https[@]}" https://127.0.0.1:8443/session/me) && [[ "$status" == 401 ]] || return 1 + status=$("${https[@]}" https://127.0.0.1:8443/apply/) && [[ "$status" == 302 ]] || return 1 + timeout --kill-after=1s 4s "${compose[@]}" exec -T application node --input-type=module - "$profile" <<'JS' +const endpoints = [ + ['http://127.0.0.1:8100/ready', 200], + ['http://127.0.0.1:8200/', 200], + ['http://127.0.0.1:8300/functions/register-business', 405], +] +if (process.argv[2] === 'casework') endpoints.push(['http://127.0.0.1:8500/ready', 200]) +const ready = await Promise.all(endpoints.map(async ([url, expected]) => { + try { + const response = await fetch(url, { + method: 'HEAD', redirect: 'manual', signal: AbortSignal.timeout(1500), + }) + return response.status === expected + } catch { + return false + } +})) +if (!ready.every(Boolean)) process.exitCode = 1 +JS +} +wait_for_serving() { + local deadline=$((SECONDS + 45)) + while ((SECONDS < deadline)); do + if serving_ready; then + return 0 + fi + sleep 1 + done + return 1 +} +wait_for_serving || refuse "The $profile reference host did not become ready." + +bash "$recipe/tests/smoke.sh" "$REFERENCE_CONFIG/trust/https-ca.pem" +phase 'run browser proof' +browser_command=(node "$recipe/tests/browser.mjs" "$playwright" "$REFERENCE_CONFIG" "$REFERENCE_CONFIG/browser-passwords" + "$BUSINESS_BUNDLE" "$profile" "${compose[@]:1}") +if [[ "$profile" == breg ]] && ! "$candidate"; then + # Bound the browser phase within the reference-host step's 15-minute budget. + browser_command=(timeout --kill-after=10s 180s "${browser_command[@]}") +fi +if "${browser_command[@]}" >"$proof_path"; then + phase 'validate browser receipt' +else + status=$? + printf 'Reference browser command failed (exit %d).\n' "$status" >&2 + exit "$status" +fi +node "$recipe/tests/receipt.mjs" "$profile" "$scratch/browser-receipt.json" +phase 'browser receipt validated' +if "$candidate"; then + phase 'assemble candidate receipt' + gateway=$(sha256sum "$REFERENCE_CONFIG/gateway-checked/envoy.json" | cut -d' ' -f1) + schema_receipt=$(sha256sum "$scratch/rehearsal/receipt.json" | cut -d' ' -f1) + proof_path="$scratch/proof.json" + jq --arg digest "$digest" --arg schema_receipt "$schema_receipt" --arg gateway "$gateway" \ + --arg bundle "$BUSINESS_BUNDLE_SHA256" --slurpfile browser "$scratch/browser-receipt.json" ' + . + {package_digest:$digest, schema_test_receipt_sha256:$schema_receipt, + gateway_sha256:$gateway, preview_bundle_sha256:$bundle, browser:$browser[0]}' \ + "$binding" >"$proof_path" +fi diff --git a/deploy/examples/business-registration/tests/smoke.sh b/deploy/examples/business-registration/tests/smoke.sh index e23a23bc9c..0c10acd461 100755 --- a/deploy/examples/business-registration/tests/smoke.sh +++ b/deploy/examples/business-registration/tests/smoke.sh @@ -30,4 +30,6 @@ expect_status 401 "${function_call[@]}" 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' +expect_status 404 "${http[@]}" -X POST -H 'Registry-Client: page' -H "Origin: $app" \ + "$app/api/functions/undeclared-function" +printf 'HTTPS issuer, private routes, signed-in page redirect, session refusals and undeclared function refusal passed.\n' diff --git a/deploy/examples/business-registration/tests/test_casework_compose.py b/deploy/examples/business-registration/tests/test_casework_compose.py new file mode 100644 index 0000000000..e45b24d7a7 --- /dev/null +++ b/deploy/examples/business-registration/tests/test_casework_compose.py @@ -0,0 +1,40 @@ +"""Check the Casework overlay retains the reference host's private hops.""" + +from pathlib import Path +import json +import os +import subprocess +import unittest + + +RECIPE = Path(__file__).resolve().parents[1] + + +class CaseworkOverlay(unittest.TestCase): + def test_only_edge_publishes_and_provisioning_is_separate(self): + rendered = subprocess.run( + ["docker", "compose", "--env-file", "/dev/null", "-f", str(RECIPE / "compose.yaml"), + "-f", str(RECIPE / "compose.local.yaml"), "-f", str(RECIPE / "casework/compose.yaml"), + "--profile", "setup", "config", "--format", "json"], + env=dict(os.environ, REFERENCE_CONFIG="/reference/config", REFERENCE_ARTIFACTS="/reference/bin", + REFERENCE_SESSION_DIGEST="sha256:" + "0" * 64, + BUSINESS_BUNDLE="/reference/bundle", BUSINESS_BUNDLE_SHA256="0" * 64, + REFERENCE_HOST_CLIENT="/reference/host-client"), + capture_output=True, check=True, text=True, + ) + services = json.loads(rendered.stdout)["services"] + self.assertEqual(services["session"]["entrypoint"], ["/opt/native/registry-session"]) + self.assertIn("/opt/native/registry-session", + [mount["target"] for mount in services["session"]["volumes"]]) + self.assertEqual([name for name, service in services.items() if service.get("ports")], ["edge"]) + self.assertEqual(services["casework"]["network_mode"], "service:upstreams") + self.assertEqual(services["casework-admin"]["profiles"], ["setup"]) + self.assertTrue(all("/casework/admin" not in mount["source"] + for mount in services["casework"]["volumes"])) + self.assertEqual(services["casework-seed"]["profiles"], ["setup"]) + self.assertTrue(all(mount["read_only"] for mount in services["casework-seed"]["volumes"])) + self.assertEqual(services["gateway-check"]["network_mode"], "none") + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/examples/business-registration/tests/test_compose.py b/deploy/examples/business-registration/tests/test_compose.py index e27d87d98a..5a837e9521 100644 --- a/deploy/examples/business-registration/tests/test_compose.py +++ b/deploy/examples/business-registration/tests/test_compose.py @@ -10,6 +10,7 @@ EXAMPLE = Path(__file__).resolve().parents[1] DOCKER = shutil.which("docker") +SESSION_DIGEST = "sha256:" + "a" * 64 @unittest.skipUnless(DOCKER, "Docker Compose is needed to render the reference") @@ -18,14 +19,56 @@ class ComposeReference(unittest.TestCase): def setUpClass(cls): if subprocess.run([DOCKER, "compose", "version"], capture_output=True).returncode: raise unittest.SkipTest("The Docker Compose plugin is unavailable") + cls.compose = cls.render() + cls.services = cls.compose["services"] + + @staticmethod + def run_config(*overlays, session_digest=SESSION_DIGEST): 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, + BUSINESS_BUNDLE="/reference/bundle", BUSINESS_BUNDLE_SHA256="0" * 64, + REFERENCE_HOST_CLIENT="/reference/host-client") + env.pop("REFERENCE_SESSION_IMAGE", None) + env.pop("REFERENCE_SESSION_DIGEST", None) + if session_digest is not None: + env["REFERENCE_SESSION_DIGEST"] = session_digest + files = [arg for path in ("compose.yaml", *overlays) for arg in ("-f", str(EXAMPLE / path))] + return subprocess.run( + [DOCKER, "compose", *files, "--profile", "setup", "config", "--format", "json"], + env=env, capture_output=True, text=True, ) - cls.compose = json.loads(rendered.stdout) - cls.services = cls.compose["services"] + + @classmethod + def render(cls, *overlays, session_digest=SESSION_DIGEST): + rendered = cls.run_config(*overlays, session_digest=session_digest) + if rendered.returncode: + raise AssertionError(rendered.stderr) + return json.loads(rendered.stdout) + + def test_session_runs_the_published_image_by_digest_without_a_binary_mount(self): + session = self.services["session"] + self.assertEqual(session["image"], "ghcr.io/registrystack/registry-session@" + SESSION_DIGEST) + self.assertIsNone(session.get("entrypoint")) + self.assertEqual(session["working_dir"], "/") + self.assertNotIn("/opt/native/registry-session", {mount["target"] for mount in session["volumes"]}) + self.assertNotIn("coordinator", self.services) + + def test_session_image_has_no_floating_tag_default(self): + unset = self.run_config(session_digest=None) + self.assertNotEqual(0, unset.returncode) + self.assertIn("REFERENCE_SESSION_DIGEST", unset.stderr) + self.assertIn("verified release manifest", unset.stderr) + # A tag supplied in place of the digest renders only behind "@", where + # Docker refuses it as an invalid reference instead of resolving it. + tag = self.render(session_digest="v0.52.0")["services"]["session"]["image"] + self.assertEqual("ghcr.io/registrystack/registry-session@v0.52.0", tag) + + def test_local_overlay_uses_the_staged_session_executable(self): + session = self.render("compose.local.yaml")["services"]["session"] + self.assertTrue(session["image"].startswith("ubuntu:24.04@sha256:")) + self.assertEqual(session["entrypoint"], ["/opt/native/registry-session"]) + binary = next(mount for mount in session["volumes"] if mount["target"] == "/opt/native/registry-session") + self.assertEqual(binary["source"], "/reference/bin/registry-session") + self.assertTrue(binary["read_only"]) def test_only_the_loopback_edge_publishes_ports(self): bindings = {name: service["ports"] for name, service in self.services.items() if service.get("ports")} @@ -64,6 +107,8 @@ def test_checked_snapshot_and_bundle_are_read_only_in_consumers(self): 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) + # The image takes the generated register-business client from its own build context. + self.assertEqual(app["build"]["additional_contexts"], {"host-client": "/reference/host-client"}) def test_one_shots_keep_bootstrap_authority_out_of_serving_mounts(self): for name in ("breg-admin", "thunderid-setup"): diff --git a/deploy/examples/business-registration/tests/test_host_node.py b/deploy/examples/business-registration/tests/test_host_node.py index 2130488aa2..4a37d3a92b 100644 --- a/deploy/examples/business-registration/tests/test_host_node.py +++ b/deploy/examples/business-registration/tests/test_host_node.py @@ -1,5 +1,6 @@ """Run the Node reference host's own tests from the deployment suite.""" +import os from pathlib import Path import shutil import subprocess @@ -8,6 +9,8 @@ EXAMPLE = Path(__file__).resolve().parents[1] +# The host tests take the binding from the client source, as the generated host client bundles it. +HOLDER_MODULE = EXAMPLE.parents[2] / "clients" / "typescript" / "holder-function.ts" NODE = shutil.which("node") NPM = shutil.which("npm") @@ -25,7 +28,10 @@ def test_host_node_suite_passes(self): [NPM, "ci", "--ignore-scripts", "--no-audit", "--no-fund"], [NPM, "test"], ): - result = subprocess.run(command, cwd=work, capture_output=True, text=True) + result = subprocess.run( + command, cwd=work, capture_output=True, text=True, + env=dict(os.environ, REFERENCE_HOLDER_MODULE=str(HOLDER_MODULE)), + ) self.assertEqual( result.returncode, 0, f"{' '.join(command[1:])} failed:\n{result.stdout}\n{result.stderr}" ) diff --git a/deploy/examples/business-registration/tests/test_preview_cleanup.py b/deploy/examples/business-registration/tests/test_preview_cleanup.py new file mode 100644 index 0000000000..64b00e694a --- /dev/null +++ b/deploy/examples/business-registration/tests/test_preview_cleanup.py @@ -0,0 +1,74 @@ +"""A failed preview start can leave a container attached to its project volume.""" + +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +RECIPE = Path(__file__).resolve().parents[1] +DOCKER = """#!/usr/bin/env bash +set -euo pipefail +case "$*" in + "volume ls -q --filter label=org.registrystack.rstack.state-root=$PREVIEW_STATE") + if [[ -f "$TEST_ROOT/preview-volume" ]]; then printf '%s\n' preview-volume; fi ;; + "ps -aq --filter label=org.registrystack.rstack.dev-run --filter volume=preview-volume") + if [[ -f "$TEST_ROOT/preview-container" ]]; then printf '%s\n' preview-container; fi ;; + "ps -aq" | "ps -aq --filter label=org.registrystack.rstack.dev-run") + for name in preview-container another-container; do + if [[ -f "$TEST_ROOT/$name" ]]; then printf '%s\n' "$name"; fi + done ;; + "rm --force "*) + if [[ -f "$TEST_ROOT/refuse-removal" ]]; then exit 1; fi + shift 2 + for name in "$@"; do + case "$name" in + preview-container | another-container) rm -- "$TEST_ROOT/$name" ;; + *) printf 'Unexpected container: %s\n' "$name" >&2; exit 2 ;; + esac + done ;; + "volume rm preview-volume") + [[ ! -f "$TEST_ROOT/preview-container" ]] + rm -- "$TEST_ROOT/preview-volume" ;; + *) printf 'Unexpected Docker command: %s\n' "$*" >&2; exit 2 ;; +esac +""" + + +class PreviewCleanup(unittest.TestCase): + def run_cleanup(self, root, refuse=False): + for name in ("preview-volume", "preview-container", "another-container"): + (root / name).touch() + if refuse: + (root / "refuse-removal").touch() + docker = root / "docker" + docker.write_text(DOCKER) + docker.chmod(0o700) + state = str(root / "dev-state") + return subprocess.run( + ["bash", str(RECIPE / "tests/cleanup-preview.sh"), state], + env=dict(os.environ, PATH=f"{root}:{os.environ['PATH']}", TEST_ROOT=str(root), PREVIEW_STATE=state), + capture_output=True, text=True, + ) + + def test_removes_only_the_disposable_preview_resources(self): + with tempfile.TemporaryDirectory() as scratch: + root = Path(scratch) + result = self.run_cleanup(root) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((root / "preview-container").exists()) + self.assertFalse((root / "preview-volume").exists()) + self.assertTrue((root / "another-container").exists()) + + def test_cleanup_refuses_to_pass_if_the_container_survives(self): + with tempfile.TemporaryDirectory() as scratch: + root = Path(scratch) + result = self.run_cleanup(root, refuse=True) + self.assertNotEqual(result.returncode, 0) + self.assertTrue((root / "preview-container").exists()) + self.assertIn("preview container", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/examples/business-registration/thunderid.sh b/deploy/examples/business-registration/thunderid.sh index 2383b04cea..92b075eb83 100644 --- a/deploy/examples/business-registration/thunderid.sh +++ b/deploy/examples/business-registration/thunderid.sh @@ -17,15 +17,29 @@ export DB_RUNTIME_TRANSIENT_PASSWORD="$DB_CONFIG_PASSWORD" export DB_ENTITY_PASSWORD="$DB_CONFIG_PASSWORD" export DB_RUNTIME_PERSISTENT_PASSWORD="$DB_CONFIG_PASSWORD" +read_casework_secrets() { + read_secret CASEWORK_ADMIN_CLIENT_SECRET + read_secret ADMIN_REVIEW_PASSWORD +} + case "${1:-}" in serve) read_secret REGISTRAR_CLIENT_SECRET read_secret REGISTRAR_PASSWORD read_secret SECOND_REGISTRAR_PASSWORD + if [[ -f /run/identity-secrets/CASEWORK_ADMIN_CLIENT_SECRET ]]; then + read_casework_secrets + fi exec ./start.sh ;; - setup) + setup | setup-casework) read_secret ADMIN_PASSWORD + if [[ "$1" == setup-casework ]]; then + read_secret REGISTRAR_CLIENT_SECRET + read_secret REGISTRAR_PASSWORD + read_secret SECOND_REGISTRAR_PASSWORD + read_casework_secrets + fi # Suppress the upstream bootstrap's credential notices. if ./setup.sh >/dev/null 2>&1; then printf 'ThunderID bootstrap completed.\n' diff --git a/docs/site/scripts/evidence-problems.test.mjs b/docs/site/scripts/evidence-problems.test.mjs index c9993a1a7e..79f3bcc0f8 100644 --- a/docs/site/scripts/evidence-problems.test.mjs +++ b/docs/site/scripts/evidence-problems.test.mjs @@ -72,20 +72,23 @@ function pageKinds() { // the general client-error and server-error ranges. function clientKindOf() { const source = read('../../../crates/registry-evidence-client/src/problem.rs'); - const denied = source.match(/\(([\d |]+), code\) => EvidenceClientError::Denied/); + const denied = source.match(/^\s*([\d |]+) => EvidenceClientError::Denied \{/m); assert.ok(denied, 'problem.rs map_problem() should carry the Denied arm this test reads'); const deniedStatuses = new Set(denied[1].split('|').map((status) => Number(status.trim()))); - const notAvailable = source.match(/\((\d{3}), Some\(EVIDENCE_NOT_AVAILABLE\)\) => EvidenceClientError::NotAvailable/); + const notAvailable = source.match(/^\s*(\d{3}) if code == EVIDENCE_NOT_AVAILABLE => EvidenceClientError::NotAvailable \{/m); assert.ok(notAvailable, 'problem.rs map_problem() should carry the NotAvailable arm this test reads'); const notAvailableCode = source.match(/const EVIDENCE_NOT_AVAILABLE: &str = "([^"]+)";/)?.[1]; assert.ok(notAvailableCode, 'problem.rs should declare EVIDENCE_NOT_AVAILABLE'); - const invalid = source.match(/\((\d{3})\.\.=(\d{3}), code\) => EvidenceClientError::InvalidRequest/); + const notAvailableStatus = source.match(/^\s*(\d{3}) => EvidenceClientError::NotAvailableStatus \{/m); + assert.ok(notAvailableStatus, 'problem.rs should classify the not-available status fallback'); + const invalid = source.match(/^\s*(\d{3})\.\.=(\d{3}) => EvidenceClientError::InvalidRequest \{/m); assert.ok(invalid, 'problem.rs should classify the client-error status range'); - const unavailable = source.match(/\((\d{3})\.\.=(\d{3}), code\) => EvidenceClientError::Unavailable/); + const unavailable = source.match(/^\s*(\d{3})\.\.=(\d{3}) => EvidenceClientError::Unavailable \{/m); assert.ok(unavailable, 'problem.rs should classify the server-error status range'); return (code, status) => { if (deniedStatuses.has(status)) return 'denied'; if (status === Number(notAvailable[1]) && code === notAvailableCode) return 'not-available'; + if (status === Number(notAvailableStatus[1])) return 'not-available'; if (status >= Number(invalid[1]) && status <= Number(invalid[2])) return 'invalid-request'; if (status >= Number(unavailable[1]) && status <= Number(unavailable[2])) return 'unavailable'; return 'protocol'; diff --git a/docs/site/src/content/docs/configure/breg-actions.mdx b/docs/site/src/content/docs/configure/breg-actions.mdx index 540f192d72..fefb7f83ea 100644 --- a/docs/site/src/content/docs/configure/breg-actions.mdx +++ b/docs/site/src/content/docs/configure/breg-actions.mdx @@ -585,13 +585,17 @@ A safely disclosed field guard that fails at commit answers `412 action.guard-fa The code confirms that blocker; effect application, proposed-value authorisation, and database constraints run only after guards pass. An earlier refusal retains its normal response. Stale conditions and guard failures that cannot be disclosed remain `412 precondition.failed`. +BReg checks the caller's target row boundaries early when the Plan produces a valid Create from the request alone. +BReg can build that Create before any other effect runs, using the request, Plan values, and the reserved Record ID. +If a target row predicate that BReg can evaluate at that point fails, Invoke returns `403 write.outside-boundary` before reading target Records, evaluating guards, or acquiring Evidence. Invoke rechecks the guard during commit. If it fails, BReg rolls back and re-observes disclosure before returning `guardReason`; advisory `guardReason` is neither authority nor a reservation. {/* Evidence: crates/registry-breg/src/api/actions/availability.rs guard-not-satisfied; crates/registry-breg/src/api/actions/availability.rs not-disclosed; crates/registry-breg/tests/postgres_immediate_action_requirements.rs input-required; - crates/registry-breg/tests/postgres_immediate_action_requirements.rs guardReason. */} + crates/registry-breg/tests/postgres_immediate_action_requirements.rs guardReason; + crates/registry-breg/tests/postgres_immediate_actions.rs an_action_create_outside_the_boundary_is_refused_before_targets_and_guards. */} ## Test a scripted Action Plan offline diff --git a/docs/site/src/content/docs/configure/breg-proposals.mdx b/docs/site/src/content/docs/configure/breg-proposals.mdx index b5c1bbab57..4ee975bbe1 100644 --- a/docs/site/src/content/docs/configure/breg-proposals.mdx +++ b/docs/site/src/content/docs/configure/breg-proposals.mdx @@ -323,6 +323,7 @@ Under required Review it reads `awaiting-review` until an approved result exists Its `application-refused` reason means an executor refused the frozen effects; a review outcome never appears there. {/* Evidence: crates/registry-breg/src/mutation.rs ApplicationRefusal; + crates/registry-breg/src/mutation/proposal.rs check_proposal_document(), apply_frozen_proposal(); crates/registry-breg/tests/postgres_proposal.rs manual_apply_unique_conflict_and_stale_revision_offer_party_recovery, admitted_apply_outside_the_callers_write_boundary_persists_nothing; crates/registry-breg/tests/postgres_proposal_guard_failure.rs apply_names_a_failed_field_guard_and_keeps_stale_revisions_generic. */} @@ -330,8 +331,10 @@ A unique-constraint failure during manual Apply returns `409 mutation.conflict` Subsequent reads report `applicationStatus.state: blocked`, `reason: application-refused`, and `recovery: revise`. Apply is unavailable. Revise can correct the input, and Rebase can inspect the current target and prepare a fresh submission. A stale Record revision returns `412 precondition.failed` and records the same application block with `recovery: rebase`. -A failed frozen field guard also needs Rebase. A frozen write that would leave the applying caller's row boundary answers `403 write.outside-boundary` and records nothing. -The boundary belongs to that caller, so the Proposal stays as it was and a caller whose boundary covers the result can still Apply. +A failed frozen field guard also needs Rebase. +A frozen Create outside the applying caller's row boundary fails admission with `412 precondition.failed`. +If Apply admits a Patch target and the resulting row crosses that caller's boundary, it returns `403 write.outside-boundary`. +These row-boundary refusals leave the Proposal unchanged, so a caller whose boundary covers the result can still Apply. Read the current Proposal before choosing the next authorised operation. Submit and Apply check the Action's field commit guards against the current target Record. diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index 35703533cb..9aa60f1c2b 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -25,8 +25,7 @@ Use the checksum-verifying installer from the published release you deploy; it k FIPS libraries beside the executables. The [install and package](../../operate/coordinator/#install-and-package) section covers that installer and source builds. Coordinator is one of the products the -[API stability promise](../../reference/api-stability/#promised-products) covers at 1.0, and its -container image is held out of releases. +[API stability promise](../../reference/api-stability/#promised-products) covers at 1.0. {/* Evidence: release/scripts/release_roster.py, COORDINATOR_BINARY_FIRST_RELEASE and COORDINATOR_FIRST_RELEASE. */} diff --git a/docs/site/src/content/docs/configure/discovery.mdx b/docs/site/src/content/docs/configure/discovery.mdx index 6b762247a1..a443168429 100644 --- a/docs/site/src/content/docs/configure/discovery.mdx +++ b/docs/site/src/content/docs/configure/discovery.mdx @@ -71,7 +71,7 @@ discoveryctl check --project discovery-project --posture production ```text test-expect discoveryctl check refused the input. error[discovery.posture.loopback-catalog-url] discovery-project/origins.yaml:5:17 /origins/tutorial-evidence/catalogUrl - the index advertises an address on the reader's own machine; it is accepted only when the process declares development + The index advertises an address on the reader's own machine; it is accepted only when the process declares development next: Publish HTTPS URLs on non-loopback hosts. For a laptop or test run, start it with `rstack dev`, or declare development with REGISTRY_STACK_POSTURE=development or --posture development. 1 error, 0 warnings in 3 files ``` @@ -126,10 +126,10 @@ discoveryctl package \ ```text test-expect packaged packageDigest=sha256: catalogRevision=sha256:7e0799f2c5fd24957e4d1372f757c40abef694110eb70fc260a0abdc312ca963 mappingRevision=sha256:332004ca3920c498539180946e8f2637e9998ba7e49cd98f31e19d6f818857ac warning[discovery.posture.loopback-catalog-url] discovery-project/package-2/discovery-index.json /origins/0/catalogUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. warning[discovery.posture.loopback-catalog-url] discovery-project/package-2/discovery-index.json /services/0/originUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. ``` @@ -147,10 +147,10 @@ discoveryctl check --posture development --index discovery-project/package-2/dis ```text test-expect valid index origins=1 services=1 mappings=1 catalogRevision=sha256:7e0799f2c5fd24957e4d1372f757c40abef694110eb70fc260a0abdc312ca963 mappingRevision=sha256:332004ca3920c498539180946e8f2637e9998ba7e49cd98f31e19d6f818857ac warning[discovery.posture.loopback-catalog-url] discovery-project/package-2/discovery-index.json /origins/0/catalogUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. warning[discovery.posture.loopback-catalog-url] discovery-project/package-2/discovery-index.json /services/0/originUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. 0 errors, 2 warnings in 1 file ``` @@ -188,10 +188,10 @@ discoveryctl check --runtime-config "$PWD/discovery-project/runtime.yaml" --envi ```text test-expect warning[discovery.posture.loopback-catalog-url] /origins/0/catalogUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. warning[discovery.posture.loopback-catalog-url] /services/0/originUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. 0 errors, 2 warnings in 1 file ``` 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 8f760f3734..aef4af0183 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 @@ -71,7 +71,7 @@ rstack evidence check . --target local-target.yaml ```text test-excerpt warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile - local assurance permits locally held signing keys; production refuses it + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file ``` @@ -130,9 +130,9 @@ 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. This issuer entry 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 + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file ``` 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 f6d8f93ba7..cfc56d651a 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 @@ -46,12 +46,16 @@ The `--clean` flag permanently removes that example's managed development data. Write the inventory in `service.yaml` and select the test actor, initial page, BReg routes, and functions in `dev.yaml` under `preview`. Key `audiences` by project ID and set -`issuer: run`. The preview accepts one BReg project with a UI and TypeScript functions. +`issuer: run`. The preview accepts one BReg project with a UI and optional TypeScript functions. Stack typechecks and bundles `ui.project/src/page.ts`, copies `ui.project/public/`, and writes `app.js` into `ui.output` in the run's staging directory. Your HTML loads that bundle. Each `functions//index.ts` exports its handler through the generated server binding. Start again after changing a page or function to build from the updated source. +If your page only calls declared BReg routes, omit `functions` from `service.yaml` +and set `functions: []` under `preview` in `dev.yaml`. You can omit the +`functions/` directory. The gateway serves the page and relays the declared BReg routes. + Use `rstack service check FILE` to check the inventory and `rstack service plan FILE --format json` to inspect resolved paths. Use `rstack dev check PROJECT` to check the development plan and native product inputs. @@ -65,8 +69,8 @@ access profile and Action rules. The numeric loopback listener is local to the host. Other processes and operating system users on the same host can reach it. The gateway's headers enforce browser 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. +When the page calls a function, the gateway uses a private handoff to a separate +listener. The listener returns 401 to an anonymous request for a selected function. 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 @@ -80,7 +84,7 @@ sign-in: the terminal prints it on a `Substitution` line, and the JSON report li 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, +Every actor has a BReg grant, so functions in `preview.functions` are 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, @@ -105,28 +109,66 @@ preview: 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 +A Coordinator `service-function` connection calls a preview function directly. +The run reserves a loopback port and writes an owner-only host key. +Coordinator presents that key as its bearer. The host validates it, removes it +from the Web Request headers, and passes the authenticated caller kind to the +binding inside the process. +Use the third argument to your `defineFunction` handler to read `page` or +`coordinator`. The binding removes `Authorization`, `Cookie` and +`Proxy-Authorization` from the handler's request. The page actor's client carries that actor's credential. +These protections apply to the binding's handler arguments. A custom handler +that bypasses `defineFunction` receives the page actor's bearer, and the raw +Node request can still contain the run host key. +The Coordinator caller's client has no credential and refuses registry operations +before network dispatch. If the handler lets that error escape, the binding +returns HTTP 403 with code `preview.coordinator-registry-authority-denied`. +Let the operation's response schema accept that status and JSON body, and +handle the refusal in its interpretation Transform. + +List functions in `preview.functions` to make them callable by both the page +and Coordinator. Use `preview.coordinatorFunctions` for functions that only +Coordinator may call. Each selection names a function declared in `service.yaml`. +Each name can appear in one list. Use `functions: []` when you only need +Coordinator functions. The gateway omits Coordinator-only routes from the page, +and the function host refuses a gateway handoff for those routes. + +The function runs with the function host process's permissions. Its code can read +the run host key and the actor credential files. The run key admits Coordinator +to every selected preview function. +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. +To serve the compiled page and functions outside `rstack dev`, export the bundle into a new +directory. The command checks and builds the preview as `start` does, starts no service, and +refuses an existing output path or a project without `preview`. + +```sh +rstack dev export-preview . --output ../preview-bundle +``` + +The bundle holds the preview's `manifest.json`, each compiled function under `functions/`, and +every file of the manifest's `staticOutput` directory. The report gives the bundle digest and +the manifest's `declarationDigest` of the checked `service.yaml`. The bundle digest is the +lowercase hex SHA-256 of a compact UTF-8 JSON array with one `["path","sha256"]` pair per file: +the path relative to the bundle with `/` separators, and the file's lowercase hex SHA-256. The +pairs are sorted by the bytes of the path. Two exports of the same source give the same bytes, +wherever the project and the state directory are, so a deployment can pin the bundle digest. The +[business registration reference host](https://github.com/registrystack/registry-stack/tree/main/deploy/examples/business-registration) +serves an exported bundle under that pin. + {/* Evidence: crates/registry-rstack/src/cli.rs; crates/registry-rstack-dev/src/preview.rs; + crates/registry-rstack-dev/src/preview_export.rs; + deploy/examples/business-registration/host.mjs, bundleDigest; 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/preview/host.mjs, functionHostAuthorizer, startFunctionHost; + clients/typescript/preview/run.mjs; + clients/typescript/generate-service.ts, generatePreviewFunctionBinding; clients/typescript/tests/generate-preview.test.ts; products/platform/examples/service-previews/README.md; products/platform/scripts/test-service-previews.mjs. */} @@ -645,7 +687,8 @@ 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` accepts `require`, `verify-ca`, and `verify-full`. Each verifies the certificate and host name, as does the default TLS mode. +- Use `sslmode=verify-full` or `sslmode=require` for verified TLS. Both check the server + certificate chain and hostname. The URL parser refuses `sslmode=verify-ca`. The default TLS mode performs the same checks. `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. diff --git a/docs/site/src/content/docs/configure/session.mdx b/docs/site/src/content/docs/configure/session.mdx index 8d4b57a09f..409d769506 100644 --- a/docs/site/src/content/docs/configure/session.mdx +++ b/docs/site/src/content/docs/configure/session.mdx @@ -27,12 +27,18 @@ The provider must return JWT access tokens with a readable audience, a lifetime 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`. +For v0.52.0 and later, you can also use +`ghcr.io/registrystack/registry-session` pinned to the digest in your verified +release manifest. Mount your runtime configuration at +`/etc/registry-session/runtime.yaml`, provide the referenced credentials and +mount the audit directory writable by UID 65532. Use `registry-session --help` for its command tree. {/* Evidence: crates/registry-session/src/signin.rs authorization_location, complete; crates/registry-session/src/issuer.rs access_token_accepted, redeem; crates/registry-session/Cargo.toml; - release/scripts/release_roster.py SESSION_FIRST_RELEASE. */} + release/scripts/release_roster.py SESSION_IMAGE_FIRST_RELEASE; + release/docker/Dockerfile.registry-session. */} Run one replica. Sessions live only in memory, so a restart requires people to sign in again. diff --git a/docs/site/src/content/docs/operate/adapter.mdx b/docs/site/src/content/docs/operate/adapter.mdx index c66ee643fa..13d12f204e 100644 --- a/docs/site/src/content/docs/operate/adapter.mdx +++ b/docs/site/src/content/docs/operate/adapter.mdx @@ -86,6 +86,8 @@ The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a su To pass the URL in an environment variable instead, use `--admin-url-env NAME`. By default the connection requires TLS and verifies the server certificate against `database.caBundleRef` or the platform roots. +Use `sslmode=verify-full` or `sslmode=require` for verified TLS. Both check the server +certificate chain and hostname. The URL parser refuses `sslmode=verify-ca`. When the runtime file sets `database.transport: loopback-plaintext`, `provision` connects in plaintext to a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback) with `sslmode` omitted or `disable`. @@ -148,6 +150,13 @@ When the certificate comes from a private CA, name that CA with `adapter serve` migrates through `database.migrationUrlRef` and serves through `database.runtimeUrlRef`. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} The migration role owns the tables. After it migrates and before it grants anything, `adapter serve` connects as the runtime role and reads that session's role name. @@ -373,7 +382,13 @@ The commands that follow use these placeholders: Use a dedicated PostgreSQL database for the job store. Set `store.migrationUrlRef` and `store.runtimeUrlRef` to secret references for distinct login roles -on that database. Run the command with an administrator who can create roles and databases. +on that database. +With `store.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. +Run the command with an administrator who can create roles and databases. ```sh adapterctl job provision --runtime-config "" --admin-url-file "" diff --git a/docs/site/src/content/docs/operate/breg.mdx b/docs/site/src/content/docs/operate/breg.mdx index 4eb9ce1780..54853e086b 100644 --- a/docs/site/src/content/docs/operate/breg.mdx +++ b/docs/site/src/content/docs/operate/breg.mdx @@ -250,7 +250,14 @@ install -d -m 0700 /etc/breg/secrets The audit key and the cursor secret each need at least 32 bytes. Percent-encode a password that carries reserved characters. The user in each URL must equal the role the file names under -`database.roles`. The URL needs no `sslmode` parameter: the runtime requires TLS itself. +`database.roles`. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} In a container platform that injects secrets as environment variables, declare `secretProviders.environment` and write `secret:env/` instead. diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index ab06100ac5..4baea187c8 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -200,6 +200,16 @@ Keep earlier package directories for recovery, and plan every activation, rollba {/* Evidence: crates/registry-casework/src/config.rs, verify_casework_package() and expected_digest; crates/registry-casework/src/config.rs, RuntimePackageConfig. */} +The URLs in `database.runtimeUrlRef` and `database.migrationUrlRef` follow the +transport in the runtime file. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} + ## Provision PostgreSQL Use a new database. Your runtime file names the roles, their passwords, and the database: they are @@ -217,7 +227,11 @@ The `admin-url` file holds one PostgreSQL URL for that administrator, for exampl `postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, use `--admin-url-env NAME`. By default the connection requires TLS and verifies the server -certificate against `database.caBundleRef` or the platform roots. When the runtime file sets +certificate against `database.caBundleRef` or the platform roots. +For the administrator URL with verified TLS, omit `sslmode` or set it to `verify-full` or +`require`. Both check the server +certificate chain and hostname. The URL parser refuses `sslmode=verify-ca`. +When the runtime file sets `database.transport: loopback-plaintext`, `provision` connects in plaintext to a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback) with `sslmode` omitted or `disable`. The command never prints the administrator URL or a password. diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 11b173bb17..a078e06c91 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -56,7 +56,14 @@ curl -fsSL "https://github.com/registrystack/registry-stack/releases/download/${ ``` The installer keeps the macOS FIPS libraries beside their executables. -The binary release does not imply that the Coordinator container image has been released; its image-specific security evidence is a separate gate. +For v0.52.0 and later, use `ghcr.io/registrystack/coordinator` pinned to the +digest in your verified release manifest. Mount your runtime configuration at +`/etc/registry-coordinator/runtime.yaml`, supply its referenced secrets and +packages, and mount the audit directory writable by UID 65532. The image +includes `coordinatorctl`, available by overriding the entrypoint. + +{/* Evidence: release/scripts/release_roster.py COORDINATOR_FIRST_RELEASE; + release/docker/Dockerfile.coordinator. */} Install `coordinator` and `coordinatorctl` from one source version, at absolute paths. {/* Evidence: release/scripts/release_roster.py COORDINATOR_BINARY_FIRST_RELEASE; @@ -215,7 +222,13 @@ Back up each key file under custody separate from the database. The database URLs are secrets too. `database.runtimeUrlRef` names the runtime role's URL and `database.migrationUrlRef` the migration role's URL; only `apply` resolves the migration URL. -Institutional connections use `sslmode=require`. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} Coordinator verifies the database certificate against the system roots, or against `database.caBundleRef` for a private root. Enter each URL at a hidden prompt, so its password stays out of shell history. @@ -267,7 +280,7 @@ Without a `deployment` block, `provision` creates the role the runtime URL names Run it as a PostgreSQL administrator that can create roles and databases (`CREATEROLE` and `CREATEDB`). It needs no superuser. Put the administrator URL in a file or an environment variable, never on the command line. -By default the connection uses verified TLS: it trusts the certificate authority behind `database.caBundleRef` when the runtime file names one, and the system roots otherwise, with `sslmode` omitted or set to `require`, `verify-ca`, or `verify-full`. +By default the connection uses verified TLS: it trusts the certificate authority behind `database.caBundleRef` when the runtime file names one, and the system roots otherwise, with `sslmode` omitted or set to `require` or `verify-full`. When the runtime file sets `database.transport: loopback-plaintext`, `provision` connects in plaintext to a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback) with `sslmode` omitted or set to `disable`. The administrator URL must name the same host and port as the two product URLs, or `provision` refuses it as `platform.provision.target-mismatch`. It must also name a database other than the product database, such as `postgres`, or `provision` refuses it as `platform.provision.target-invalid`. diff --git a/docs/site/src/content/docs/operate/documents.mdx b/docs/site/src/content/docs/operate/documents.mdx index 6cacd2fb92..c6db0ca572 100644 --- a/docs/site/src/content/docs/operate/documents.mdx +++ b/docs/site/src/content/docs/operate/documents.mdx @@ -39,6 +39,16 @@ checkout, as the [overview](../../start/documents/#status) explains. crates/registry-documents/src/verification.rs, activate_verifier; crates/registry-platform-objectstore/src/verifier.rs, HttpVerifier. */} +The URLs in `database.runtimeUrlRef` and `database.migrationUrlRef` follow the +transport in the runtime file. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} + ## Provision PostgreSQL Your runtime file already names the roles, their passwords, and the database. They are the URLs in @@ -53,7 +63,11 @@ The `admin-url` file holds one PostgreSQL URL for that administrator, for exampl `postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, use `--admin-url-env NAME`. By default the connection requires TLS and verifies the server -certificate against `database.caBundleRef` or the platform roots. When the runtime file sets +certificate against `database.caBundleRef` or the platform roots. +For the administrator URL with verified TLS, omit `sslmode` or set it to `verify-full` or +`require`. Both check the server +certificate chain and hostname. The URL parser refuses `sslmode=verify-ca`. +When the runtime file sets `database.transport: loopback-plaintext`, `provision` connects in plaintext to a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback) with `sslmode` omitted or `disable`. The administrator URL must name the diff --git a/docs/site/src/content/docs/operate/messaging.mdx b/docs/site/src/content/docs/operate/messaging.mdx index e883c02eb0..128c83992a 100644 --- a/docs/site/src/content/docs/operate/messaging.mdx +++ b/docs/site/src/content/docs/operate/messaging.mdx @@ -379,6 +379,16 @@ reaching a database. {/* Evidence: crates/registry-messagingctl/src/lib.rs, check(); observed with messagingctl 0.42.0-dev on 2026-10-19, paths replaced. */} +The URLs in `database.runtimeUrlRef` and `database.migrationUrlRef` follow the +transport in the runtime file. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} + ## Provision PostgreSQL Your runtime file already names the roles, their passwords, and the database. They are the URLs in @@ -395,7 +405,11 @@ The `admin-url` file holds one PostgreSQL URL for that administrator, for exampl `postgresql://admin:PASSWORD@db.example.org:5432/postgres`. The administrator needs `CREATEROLE` and `CREATEDB` and does not need to be a superuser. To pass the URL in an environment variable instead, use `--admin-url-env NAME`. By default the connection requires TLS and verifies the server -certificate against `database.caBundleRef` or the platform roots. When the runtime file sets +certificate against `database.caBundleRef` or the platform roots. +For the administrator URL with verified TLS, omit `sslmode` or set it to `verify-full` or +`require`. Both check the server +certificate chain and hostname. The URL parser refuses `sslmode=verify-ca`. +When the runtime file sets `database.transport: loopback-plaintext`, `provision` connects in plaintext to a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback) with `sslmode` omitted or `disable`. The command never prints the administrator URL or a password. diff --git a/docs/site/src/content/docs/operate/registry-render.mdx b/docs/site/src/content/docs/operate/registry-render.mdx index a4ac2189f7..ee131db3bb 100644 --- a/docs/site/src/content/docs/operate/registry-render.mdx +++ b/docs/site/src/content/docs/operate/registry-render.mdx @@ -15,7 +15,7 @@ import ConfigurationFormatChecks from '../../../components/ConfigurationFormatCh You have a package built with `registry-render package` and callers that need PDFs. When you are done, one `registry-render serve` process serves that package on a private address behind your -TLS proxy, under API-key authentication, with an audit file you ship to append-only storage. +TLS proxy, under OIDC authentication, with an audit file you ship to append-only storage. [Render your first document](../../tutorials/first-render-document/) builds a package. Registry Render is pre-1.0 and an @@ -28,9 +28,8 @@ compatibility promise. - **One package directory, mounted read-only.** Serve verifies it at startup and in the worker on every request, and refuses a package that changes while it runs. -- **Either OIDC issuer settings or one shared API key in an owner-only file.** A shared API key is - at least 32 bytes of ASCII. Serve trims one trailing line ending and refuses any other whitespace, - because a mis-read key would reject every caller while health stays green. +- **OIDC issuer settings and an allowed client list.** Each production caller needs an access token + for the Render resource. - **A writable audit directory, or a log collector on standard output.** Serve refuses a directory that group or others can write. - **A TLS proxy in front.** The listener serves plain HTTP, reads no forwarded header, and accepts @@ -75,8 +74,8 @@ does; the workspace lockfile is part of Render's byte contract, so always build The same release publishes the image `ghcr.io/registrystack/registry-render:`. It runs `registry-render serve` with `/etc/registry-render/runtime.yaml` from Distroless `cc-debian13` as the `nonroot` user (UID 65532), with `/var/lib/registry-render` as its working directory, and holds -no package. Mount the runtime file and the package read-only. Keep the API key owned by UID 65532 -with mode `0400` or `0600`, and the audit directory owned by UID 65532 with mode `0700`. Deploy by +no package. Mount the runtime file and the package read-only. Keep the audit directory owned by +UID 65532 with mode `0700`. Deploy by the digest `release/VERIFY.md` authenticates. A proxy in another container reaches Render on its private container address, so set `listener.bind` to that address; `0.0.0.0` is refused. @@ -99,11 +98,13 @@ listener: package: root: /var/lib/registry-render/package expectedDigest: sha256: -secretProviders: - file: - root: /run/secrets/registry-render authentication: - apiKeyRef: secret:file/render-api-key + oidc: + issuers: + main: + issuer: https://issuer.example.invalid + audience: urn:example:render + allowedClients: [portal] limits: renderTimeoutSeconds: 20 maximumConcurrentRenders: 4 @@ -273,9 +274,8 @@ and `audit-failed` (503). ### Authenticate callers with OIDC tokens -Choose exactly one non-null authentication mode: `authentication.oidc` or the shared API key in -`authentication.apiKeyRef`, which keeps its secret-provider and entropy checks. Do not configure both, -and do not use null as an absent member. For OIDC, the block is: +Production requires `authentication.oidc`. Choose an issuer, a Render resource audience and the +clients allowed to call it: ```yaml authentication: @@ -316,6 +316,20 @@ bytes. crates/registry-render/tests/serve.rs, maintained_sdk_uses_the_real_oidc_adapter_for_render_and_typed_refusals and unauthorized_requests_are_refused_and_audited. */} +### Migrate a shared API key deployment to OIDC + +1. Register a Render resource audience with your issuer. Authorize each calling client to obtain an + access token for that audience with `render:render`. +2. Replace `authentication.apiKeyRef` with `authentication.oidc` as shown above. List the intended + client IDs in `allowedClients`. +3. Configure each caller to acquire and refresh its Render access token. Keep the existing + `Authorization: Bearer` header and supply the token as its value. +4. Check the deployment file, restart `serve`, and confirm readiness and an authenticated render. + Retire the shared key from deployment and caller configuration after cutover. + +For local exercises, declare `--posture development` on both `check` and `serve` and use a +loopback `listener.bind`. The tutorial shows this mode with an owner-only key file. + ## Seal documents Sealing is optional. Without a `signing` block, Render loads no key, makes no timestamp call, and diff --git a/docs/site/src/content/docs/operate/scheduling.mdx b/docs/site/src/content/docs/operate/scheduling.mdx index dde5ad4ca3..03487f5312 100644 --- a/docs/site/src/content/docs/operate/scheduling.mdx +++ b/docs/site/src/content/docs/operate/scheduling.mdx @@ -198,6 +198,16 @@ secretsIncluded: false `SHA256SUMS` file. Set `package.expectedDigest` to the digest if the runtime must refuse any other package. +The URLs in `database.runtimeUrlRef` and `database.migrationUrlRef` follow the +transport in the runtime file. +With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or +set it to `verify-full` or `require`. The runtime verifies the server certificate chain and +hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. +Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep +the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} + ## Provision PostgreSQL Your runtime file already names the roles, their passwords, and the database. They are the URLs in @@ -219,7 +229,11 @@ database other than the product database, such as `postgres`, or `provision` ref database, `provision` cannot run: add `--print-sql` and give the script to the person who administers the server. To pass the URL in an environment variable instead, use `--admin-url-env NAME`. By default the connection requires TLS -and verifies the server certificate against `database.caBundleRef` or the platform roots. When the +and verifies the server certificate against `database.caBundleRef` or the platform roots. +For the administrator URL with verified TLS, omit `sslmode` or set it to `verify-full` or +`require`. Both check the server +certificate chain and hostname. The URL parser refuses `sslmode=verify-ca`. +When the runtime file sets `database.transport: loopback-plaintext`, `provision` connects in plaintext to a loopback host (`127.0.0.1`, `::1`, or `localhost` resolving only to loopback) with `sslmode` omitted or `disable`. The command never prints the administrator URL or a password. diff --git a/docs/site/src/content/docs/reference/api-stability.mdx b/docs/site/src/content/docs/reference/api-stability.mdx index 4761b870b9..c749e828d2 100644 --- a/docs/site/src/content/docs/reference/api-stability.mdx +++ b/docs/site/src/content/docs/reference/api-stability.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-19" +last_reviewed: "2026-12-02" doc_type: reference locale: en standards_referenced: [] @@ -149,6 +149,7 @@ release without deprecation: Registry Document Store is held out of the 1.0 release. Numbered releases ship the session service binary, `registry-session`, from v0.51.0. +The Session container image joins numbered releases from v0.52.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 @@ -248,6 +249,16 @@ A client must ignore response members it does not recognise, and must not fail o it does not recognise; it handles that problem by its HTTP status. That rule is what lets a minor release add members and codes. +Where a published response schema is closed, it describes the members emitted by a given release. +This applies to closed schemas in OpenAPI documents and in published JSON Schema files. +Several response schemas are open by design. +If you validate responses against a closed schema, have your client ignore unknown members so it +can accept responses with members added in later minor releases. + +{/* Evidence: crates/registry-evidence/src/contracts.rs, RESPONSE_EMISSION_NOTE and + RESPONSE_SCHEMA_FILES; products/evidence/generated/jwks-v1.schema.json, $comment; + products/coordinator/generated/openapi/coordinator.openapi.json. */} + Signed payloads and governed, digest-verified artifacts keep their own closed formats. Casework clients keep review policy closures and their dependencies intact for digest verification before use. diff --git a/docs/site/src/content/docs/reference/breg-api.mdx b/docs/site/src/content/docs/reference/breg-api.mdx index d08f96a91b..e546a90dcf 100644 --- a/docs/site/src/content/docs/reference/breg-api.mdx +++ b/docs/site/src/content/docs/reference/breg-api.mdx @@ -60,14 +60,32 @@ A direct Create, direct Batch item, or Patch that moves a visible Record outside the selected profile's row boundary answers `403 write.outside-boundary`. The fixed problem has no field, value, claim, or location extension, and no item commits. A hidden or absent Patch target and a stale condition remain the same value-free -`412 precondition.failed`. Ingestion items, immediate Action effects, and Proposal targets and -effects also retain their generic `412` boundary refusal. +`412 precondition.failed`. An immediate Action Create whose new row falls outside the selected +profile's target row boundary also answers `403 write.outside-boundary`. BReg decides it from the +request alone, before it reads any target or evaluates any guard, so the answer is the same +whatever the guards and the named targets hold. A Create that takes a value from another effect's +Record, a boundary on a generated field, and an Action whose plan runs on Evidence keep the +generic `412` for target row-boundary refusals. So do immediate Action Patch and ingestion items. + +Proposal Apply returns the generic `412 precondition.failed` for a hidden or missing target. +A frozen Create outside the applying caller's row boundary also fails admission with that `412`. +If Apply admits a Patch target and the resulting row crosses the applying caller's boundary, it +returns `403 write.outside-boundary`. + +A disclosure condition that binds the writing profile can independently refuse an immediate +Action write or a Proposal Apply with `403 write.outside-boundary`. {/* Evidence: crates/registry-breg/src/auth.rs; crates/registry-breg/src/api/mod.rs, probe_routes(), authenticated_router(), not_found(), refuse_head(), select_surface_by_fit(); crates/registry-breg/src/query.rs, access_profile; crates/registry-breg/src/contract.rs, ProjectAccessProfileSource and PermissionsSource; - crates/registry-breg/tests/postgres_mutation.rs, real_postgres_row_boundary_write_refusals_are_safe_audited_and_atomic. */} + crates/registry-breg/tests/postgres_mutation.rs, real_postgres_row_boundary_write_refusals_are_safe_audited_and_atomic; + crates/registry-breg/src/mutation/action.rs, refuse_create_outside_boundary; + crates/registry-breg/tests/postgres_immediate_actions.rs, an_action_create_outside_the_boundary_is_refused_before_targets_and_guards; + crates/registry-breg/src/mutation/proposal.rs, load_proposal_row(), check_proposal_document(), apply_frozen_proposal(); + crates/registry-breg/src/mutation.rs, write_plan_row(), update_current_row(); + crates/registry-breg/tests/disclosure/writes.rs, a_write_is_refused_only_by_a_condition_that_binds_the_writer; + crates/registry-breg/tests/postgres_proposal.rs, admitted_apply_outside_the_callers_write_boundary_persists_nothing. */} ## Routes diff --git a/docs/site/src/content/docs/reference/client-api.mdx b/docs/site/src/content/docs/reference/client-api.mdx index e78065e7d3..1abeefb009 100644 --- a/docs/site/src/content/docs/reference/client-api.mdx +++ b/docs/site/src/content/docs/reference/client-api.mdx @@ -45,7 +45,7 @@ beginning with Registry Stack v0.38.0; the `scheduling` namespac beginning with Registry Stack v0.40.0. The `coordinator` namespace is selected from v0.44.0. Published v0.43.0 packages have no Coordinator namespace. Runtime binary and image availability are separate release prerequisites: the binaries ship from v0.44.0 -and the image is held. +and the image ships from v0.52.0. Python requires version 3.11 or later and the wheels use the Python 3.11 stable ABI (`abi3-py311`), so a later Python imports the same file. Node requires version 24.11 or later. Both packages select a native build for Linux amd64 with glibc, Linux arm64 with glibc, or @@ -449,8 +449,12 @@ Python raises `discovery.DiscoveryClientError` and Node throws the same named cl `capability-mismatch`, `local-acceptance-refused`, `selection-changed`, `transport`, `problem`, `protocol`, and `client`. Rust returns the matching `DiscoveryClientError` variants. -For kind `problem`, `problem` is one of `invalid-request`, `not-found`, `result-bound-exceeded`, -`unavailable`, or `unknown`. +For kind `problem`, a problem the client knows sets `problem` to `invalid-request`, `not-found`, +`result-bound-exceeded`, or `unavailable`, and `code` to that problem's code. A problem the client +does not recognise, either a newer type or a known type with a newer code, leaves `problem` unset +and carries its type (`problemType` in Node, `problem_type` in Python) and, when the server +supplied one, its `code`. The TypeScript client's `RegistryError.code` is the response's `code` +member, so it stays unset for a Discovery problem body that carries no code. {/* Evidence: crates/registry-stack-client-node/discovery/client.d.ts, crates/registry-discovery-client-py/python/registry_discovery_client/__init__.pyi, diff --git a/docs/site/src/content/docs/reference/contracts.mdx b/docs/site/src/content/docs/reference/contracts.mdx index e759faf7b0..776020a02f 100644 --- a/docs/site/src/content/docs/reference/contracts.mdx +++ b/docs/site/src/content/docs/reference/contracts.mdx @@ -8,7 +8,7 @@ source_repos: - registry-manifest - registry-evidence - registrystack-id -last_reviewed: "2026-08-11" +last_reviewed: "2026-12-02" doc_type: reference locale: en standards_referenced: @@ -119,5 +119,11 @@ Current contracts follow the pre-1.0 compatibility policy. Historical Relay iden released artifacts keep their recorded identity, but they are not current runtime contracts and must not be reassigned to another product. +Where a published response schema is closed, it describes the members emitted by a given release. +Several response schemas are open by design. +A later minor release may add response members. Clients tolerate them by ignoring members they +do not recognise, as described in [clients and servers](../api-stability/#clients-and-servers). +Signed payloads and digest-verified artifacts keep their own closed formats. + - [API stability and versioning](../api-stability/) - [Registry Relay retirement](../../decisions/registry-relay-retirement-2026-10-03/) diff --git a/docs/site/src/content/docs/reference/documents-configuration.mdx b/docs/site/src/content/docs/reference/documents-configuration.mdx index fdf6b35ca3..a1dec97b2f 100644 --- a/docs/site/src/content/docs/reference/documents-configuration.mdx +++ b/docs/site/src/content/docs/reference/documents-configuration.mdx @@ -156,9 +156,17 @@ The other blocks are checked, so a deployment written now keeps its meaning when - `secretProviders` declares the secret providers, such as `file.root`. A reference to an undeclared provider is refused. - `database.runtimeUrlRef` is the secret reference to the PostgreSQL URL the runtime connects with. - The connection always uses TLS and verifies the server certificate and its host name; an `sslmode` in the URL does not change that. - `database.migrationUrlRef` is the secret reference to the PostgreSQL URL that `documentsctl apply` connects with to apply the schema, record the package in the activation ledger, and grant the runtime role. - The runtime never uses it, and it requires TLS like the runtime URL. + Only the operator commands use this reference. +- `database.transport` selects the transport for both URLs. + With `database.transport: verified-tls` (the default), these URLs can omit `sslmode` or + set it to `verify-full` or `require`. The runtime verifies the server certificate chain and + hostname and refuses `verify-ca`. A plaintext transport refuses `require` and `verify-full`. + Set the transport to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep + the configured plaintext transport. + +{/* Evidence: crates/registry-platform-postgres/src/lib.rs parse_runtime_url. */} + - `database.caBundleRef` is an optional secret reference to a PEM bundle of the CA certificates that sign the database certificate, for a private CA. When it is set, these are the only roots trusted; when it is omitted, the system's trusted roots are used. - `database.testOnlyPlaintext` is accepted only by builds with the `postgres-test` feature, for the PostgreSQL test suites. diff --git a/docs/site/src/content/docs/reference/errors.mdx b/docs/site/src/content/docs/reference/errors.mdx index 584427276a..dc1a2125e8 100644 --- a/docs/site/src/content/docs/reference/errors.mdx +++ b/docs/site/src/content/docs/reference/errors.mdx @@ -52,13 +52,33 @@ A closed client rejects extensions unless its owning contract explicitly accepts Discovery preserves its problem type URIs and adds the codes `request.invalid`, `request.not-found`, `request.result-bound-exceeded`, and `service.unavailable`, a fixed `detail`, and `traceId`. Its indeterminate 503 carries no guessed retry interval. -Its client classifies a problem by HTTP status and the original `type`, `title`, and `status` trio; a supplied `code` must agree for known problem types. -Additive members, `detail`, `traceId`, and the response `traceparent` are opaque to classification. -The entire problem body is bounded at 4 KiB. -Unknown future Discovery problem types keep a bounded, status-only fallback. - -{/* Evidence: crates/registry-discovery-client/src/client.rs request.result-bound-exceeded; - crates/registry-discovery/src/openapi.rs request.result-bound-exceeded. */} +Discovery clients require a string `title`, and the server can reword it freely. +The document's `status` must match the HTTP status. +For a known `type`, the HTTP status must match that type and a supplied known `code` must match the same problem. +Legacy documents may omit `code`. +A valid future Discovery type or a valid future code under a known type yields an unrecognized Problem with its HTTP status, type, and supplied code. +Future types must use the Discovery problem URI prefix and a lowercase kebab-case suffix of at most 128 ASCII characters. +Future codes may contain one or more dot-separated lowercase kebab-case segments, with at most 128 ASCII characters total. + +Rust, Node.js, and Python classify the Problem even if trace data is missing, malformed, or mismatched. +For an unrecognized Problem, they retain a trace ID when the body's `traceId` matches a valid response `traceparent`. +TypeScript requires this correlation for a known type and whenever a Problem with an unfamiliar type supplies either trace field. +The native clients bound the problem body at 4 KiB. + +Structured errors discard the server's `title` and `detail`. +Read unfamiliar identifiers explicitly from Rust's `UnrecognizedProblem` fields, Node.js's `problemType` and `code`, or Python's `problem_type` and `code`. +Rust Debug, Node.js default inspection and JSON serialization, and Python's string and repr output omit these identifiers. +Read the optional native trace with Rust's `trace_id()`, Node.js's `traceId`, or Python's `trace_id`. +In TypeScript, read the identifiers from the structured `problem`. +The transport error's explicit `raw` accessor exposes the original response bytes. + +Persisted selections have a closed shape and require explicit local acceptance before use. + +{/* Evidence: crates/registry-discovery-client/src/client.rs problem_from_response(), strict_decode(); + crates/registry-discovery-client/src/selection.rs accept_service_selection(); + crates/registry-discovery/src/openapi.rs request.result-bound-exceeded; + clients/typescript/generate.ts matchesTrace(); + clients/typescript/core.ts raw. */} Render uses the same core with its own vocabulary and extensions. Its `code` values are `render.`, and its type base is its own released `https://render.registrystack.org/problems`. @@ -202,6 +222,35 @@ states what each check accepts. | `platform.secret-file.group-access` | The secret file's group has access the rule does not allow. | Use mode `0400` or `0600` for a file the runtime user owns. Group read is accepted only on a root-owned file (`0440` or `0640`) read by a non-root runtime. | | `platform.secret-file.mode-bits` | The secret file has an execute, setuid, setgid or sticky bit, or its owner cannot read it. | Set mode `0400` or `0600`. | +## Provision secret codes + +When a `provision` tool cannot read a database member's secret or public document, it reports +one of these `platform.provision.*` codes at the member's pointer: `/database/runtimeUrlRef`, +`/database/migrationUrlRef` or `/database/caBundleRef`, or under `/store` for +`adapterctl job-provision`. A refusal to set up the secret providers carries the same code at +`/secretProviders`, except in `bregctl`, which reports it as a refused runtime file. Every provision +tool uses the same code for the same member refusal. The message names +the member and the reason, never a reference or a value, and `suggestedAction` names the fix once. + +| Code | Meaning | +| --- | --- | +| `platform.provision.secret-reference-invalid` | The member is not an exact `secret:env/NAME` or `secret:file/name` reference. | +| `platform.provision.secret-provider-disabled` | The reference names a provider the runtime file does not enable. | +| `platform.provision.secret-providers-invalid` | The secret provider configuration is invalid. | +| `platform.provision.secret-unavailable` | No readable secret of that name exists under the configured provider. | +| `platform.provision.secret-file-unsafe` | The secret file fails a [secret file check](#secret-file-codes); the message names its `platform.secret-file.*` code. | +| `platform.provision.public-document-unsafe` | The CA bundle's file fails a public-document check; the message names its `platform.secret-file.*` code. | +| `platform.provision.public-document-private-key` | The CA bundle holds a PEM private key block. | +| `platform.provision.secret-unreadable` | The secret could not be read. | +| `platform.provision.secret-value-invalid` | The secret or CA bundle is empty, larger than 64 KiB, or holds a NUL byte, or a URL secret is not UTF-8 text. | +| `platform.provision.ca-bundle-no-certificate` | The CA bundle holds no PEM certificate. | +| `platform.provision.ca-bundle-invalid-pem` | A PEM block in the CA bundle is not valid. | +| `platform.provision.ca-bundle-unusable-certificate` | A certificate in the CA bundle cannot be used as a trusted root. | + +A `provision` tool reads the CA bundle's certificates as the runtime does, in print mode as well as +apply mode. Text outside the certificate blocks is ignored in any encoding, a leading byte-order +mark is skipped, and blocks that are not certificates are skipped. + ## Retired Relay codes Registry Relay and its problem-code catalogue were retired in Registry Stack 0.39.0. Existing diff --git a/docs/site/src/content/docs/reference/render-configuration.mdx b/docs/site/src/content/docs/reference/render-configuration.mdx index 5fe7361e33..67963b8059 100644 --- a/docs/site/src/content/docs/reference/render-configuration.mdx +++ b/docs/site/src/content/docs/reference/render-configuration.mdx @@ -32,10 +32,8 @@ package, secret providers, authentication, limits, and audit. `authentication` takes exactly one mode. `oidc` admits resource-bound access tokens and names each client. `apiKeyRef` names a shared API key: one static bearer credential that every request -presents. The shared API key is a supported mode for a single trusted caller where no OIDC issuer -is available. It never seals. Every request carries the same key, so the audit records one -fingerprint for all calls and cannot tell callers apart. Use `oidc` when more than one system calls -Render or when a deployment seals. +presents. It requires explicit development posture and a loopback `listener.bind`. Every call +shares one audit fingerprint. Use `oidc` in production and for sealing. The JSON Schema a document type names for its data is yours to write; Render applies it to every request and has no schema of its own for it. A schema-valid file still needs `registry-render @@ -163,6 +161,8 @@ Serve and `check` report these as runtime problems at the position of the key. | Code | Meaning | |---|---| +| `render.posture.shared-api-key` | Refuses `authentication.apiKeyRef` in production and warns in development. | +| `render.runtime.shared-key-requires-loopback` | Development configures a shared key on a private or link-local API address, or a container wildcard. | | `render.runtime.signing-requires-oidc` | `signing` is declared with the shared API key. | | `render.runtime.no-seals` | `signing.seals` is empty. | | `render.runtime.relative-path` | `certificateChainFile`, or a `transit` signer's `unixSocketPath`, is relative or has a `.` or `..` segment. | diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index eb9eaadce7..35a91dfa59 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -455,6 +455,25 @@ A caller who holds no read grant on the guarded field gets the generic `412 prec a_current_revision_action_does_not_tell_a_hidden_record_from_a_missing_one; products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-224. */} +### Action creates outside the boundary + +An immediate Action Create whose new row falls outside the caller's target row boundary answers +`403 write.outside-boundary`, as a direct Create does (`BREG-SEC-246`). +BReg decides it from the request alone: the caller's inputs, the Action's literal values and the +identifiers BReg reserves for the new Records. +It does so before it reads any target, evaluates any guard, or calls Evidence. +A passing guard, a failing guard the caller reads, a failing guard on a field the caller cannot +read, and a visible, hidden or missing target therefore all give the same answer. +A later refusal could otherwise tell the caller that every guard passed. +A Create that takes a value from another effect's Record, a boundary on a generated field, a timer +firing, and a plan computed on Evidence keep the generic `412 precondition.failed` at the write. + +{/* Evidence: crates/registry-breg/src/mutation/action.rs, refuse_create_outside_boundary; + crates/registry-breg/src/postgres/context.rs, create_row_matches_request_boundaries; + crates/registry-breg/tests/postgres_immediate_actions.rs, + an_action_create_outside_the_boundary_is_refused_before_targets_and_guards; + products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-246. */} + ### Record files A Record type's file slot is written once. diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index f2bd83f3c3..fc8dd41863 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -891,8 +891,13 @@ Enforcement: 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. + `rstack dev` generates a per-run host key for the preview function host. After validating the key, + the host removes it from the Web Request headers and passes the caller kind to the + binding as an in-process argument. The raw Node request can still carry the key. + A custom handler that bypasses the binding receives the page actor's bearer. + The binding strips credential headers and gives Coordinator-called functions a registry client + that refuses before dispatch. The host rejects gateway handoffs to functions in + `preview.coordinatorFunctions`. Calls to `preview.functions` admit both caller kinds. 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 @@ -929,6 +934,10 @@ Coordinator's audience, and task authority on a function connection. normalised_resource, validate_workflow_effect_bindings; crates/registry-coordinator/src/adapters.rs distinct_function_keys; crates/registry-coordinator/src/external_http.rs ServiceFunctionConfig; + clients/typescript/preview/host.mjs startFunctionHost, functionHostAuthorizer; + clients/typescript/generate-service.ts generatePreviewFunctionBinding; + clients/typescript/tests/generate-preview.test.ts; + clients/typescript/preview/tests/preview.test.mjs; 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, diff --git a/docs/site/src/content/docs/security/messaging.mdx b/docs/site/src/content/docs/security/messaging.mdx index 7307ba028c..51efccdc56 100644 --- a/docs/site/src/content/docs/security/messaging.mdx +++ b/docs/site/src/content/docs/security/messaging.mdx @@ -63,10 +63,14 @@ closed set of 45 names such as `token-signature`, `scope`, `actor-kind`, `access label. A verifier that cannot reach its key source counts under `key-source-unavailable`. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window -held back. Where an operator can fix the cause in configuration, the line carries a fixed remedy -that names the setting, for example `accessProfiles` for `access-profile` or -the issuer entry's `scopeClaim` for `scope`. Neither the counter nor the line holds a token, claim, -client, subject, scope or identifier. In production you can distinguish the checks that caused +held back. Where an operator can fix the cause in configuration or the token, the line carries a +fixed remedy that names the setting or claim, for example `accessProfiles` for `access-profile`, +the issuer entry's `scopeClaim` for `scope`, the token's `aud` claim and the entry's `audience` for +`token-audience`, or the token's `exp` claim for an expired token. +Neither the counter nor the line holds the presented token or the caller's claim values, +client identifier, subject identifier, or supplied scope. For a scope refusal, the operator +line can name the configured claim key, required scope and access profile. +In production you can distinguish the checks that caused refusals through the private metrics and logs. In development a JSON refusal body also carries `failedCheck`. diff --git a/docs/site/src/content/docs/security/render.mdx b/docs/site/src/content/docs/security/render.mdx index 3caa227f76..02583d2d35 100644 --- a/docs/site/src/content/docs/security/render.mdx +++ b/docs/site/src/content/docs/security/render.mdx @@ -19,6 +19,22 @@ To deploy and configure Render, see [Deploy Registry Render](../../operate/regis ## Accepted residuals +### The shared Render key is for loopback development + +Production requires OIDC. The `render.posture.shared-api-key` posture gate refuses +`authentication.apiKeyRef` in production before key resolution. Serving can access the +reference only with the development witness required by `Gated::get`. Explicit +development permits the key on a loopback API listener. A shared key is replayable by any holder and gives all calls +one audit fingerprint. OIDC lets operators admit and revoke clients individually. +Only an authorized OIDC client can seal. +A same-host proxy, host networking, or a sidecar can expose a loopback listener remotely. The explicit development posture gates shared-key use. + +{/* Evidence: crates/registry-render/src/runtime.rs, RENDER_SHARED_API_KEY and findings; + crates/registry-render/src/server.rs, load_service; + crates/registry-render/tests/serve.rs, shared_key_requires_explicit_loopback_development + and production_shared_key_refusal_precedes_package_loading; + crates/registry-render/tests/serve_seal.rs, the_shared_api_key_never_seals. */} + ### A render worker is not a sandbox It runs as the serving process's user, with the same filesystem and network. diff --git a/docs/site/src/content/docs/start/registry-render.mdx b/docs/site/src/content/docs/start/registry-render.mdx index 803db8b992..866179de9b 100644 --- a/docs/site/src/content/docs/start/registry-render.mdx +++ b/docs/site/src/content/docs/start/registry-render.mdx @@ -57,7 +57,7 @@ receives](../../reference/render-payload/#what-fixes-the-bytes) gives the rules. `registry-render compile` renders one document at a terminal, for authoring and for printing at a counter without a service. `registry-render serve` is a small HTTP service that admits callers by -OIDC access token, or by a shared API key, and serves one package. `registry-render package` copies +OIDC access token, or by a shared API key in loopback development, and serves one package. `registry-render package` copies validated source into a new directory and writes a sorted `SHA256SUMS` file covering every file, plus an optional `REVISION`. The package digest is the sha256 of that checksum file. The package writer refuses an existing directory, so a digest never gains different bytes. 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 6c391dde29..a4677d74d9 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. This issuer entry admits a token from every client this issuer signs for. error[evidence.target.production-assurance-required] deploy-target/target.yaml:/assuranceProfile deployment closure requires production or evidence-grade target assurance next: Correct the selected project or target artifact and rerun check. @@ -181,7 +181,7 @@ rstack evidence package adult-status --target deploy-target/target.yaml --output ```text test-expect warning[evidence.posture.local-assurance] deploy-target/target.yaml:1:1 /assuranceProfile - local assurance permits locally held signing keys; production refuses it + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file Package digest: sha256: @@ -266,9 +266,9 @@ 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. This issuer entry 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 + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 23 files ``` 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 efa3ef3ad4..3e0439b7d7 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,9 +149,9 @@ 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. This issuer entry 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 + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file PASS: check @@ -206,9 +206,9 @@ 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. This issuer entry 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 + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file ``` 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 c55349f3ac..dc89a1c449 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,9 +93,9 @@ 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. This issuer entry 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 + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file PASS: check diff --git a/docs/site/src/content/docs/tutorials/control-who-can-request-evidence.mdx b/docs/site/src/content/docs/tutorials/control-who-can-request-evidence.mdx index 205534a8d2..f2d907098f 100644 --- a/docs/site/src/content/docs/tutorials/control-who-can-request-evidence.mdx +++ b/docs/site/src/content/docs/tutorials/control-who-can-request-evidence.mdx @@ -100,7 +100,7 @@ rstack evidence check . --target local-target.yaml ```text test-excerpt warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile - local assurance permits locally held signing keys; production refuses it + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file ``` 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 e651226e6b..cb897c7198 100644 --- a/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx +++ b/docs/site/src/content/docs/tutorials/first-evidence-assertion.mdx @@ -87,9 +87,9 @@ 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. This issuer entry 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 + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file ``` diff --git a/docs/site/src/content/docs/tutorials/first-render-document.mdx b/docs/site/src/content/docs/tutorials/first-render-document.mdx index 991e075c32..cb4c324657 100644 --- a/docs/site/src/content/docs/tutorials/first-render-document.mdx +++ b/docs/site/src/content/docs/tutorials/first-render-document.mdx @@ -111,7 +111,7 @@ The `sha256:` digest names this package. A later change to any file in it is ref ## Serve the package -Create the API key callers present, and a runtime file that names the package, the key, and an +Use explicit development posture for this loopback exercise. Create the API key callers present, and a runtime file that names the package, the key, and an audit file. Its paths are absolute: ```sh @@ -134,17 +134,18 @@ authentication: audit: path: $here/audit/render.jsonl EOF -registry-render check --runtime-config "$here/deploy/runtime.yaml" +registry-render check --posture development --runtime-config "$here/deploy/runtime.yaml" ``` -```text test-expect -0 errors, 0 warnings in 1 file +```text test-excerpt +0 errors, 1 warning in 1 file ``` +The `render.posture.shared-api-key` warning records that the runtime uses a development-only shared key. Start the service and leave it running in this terminal: ```sh test-background="http://127.0.0.1:64123/health" -registry-render serve --runtime-config "$here/deploy/runtime.yaml" +registry-render serve --posture development --runtime-config "$here/deploy/runtime.yaml" ``` It logs JSON lines to standard error. Open a second terminal in the same directory and run the diff --git a/docs/site/src/content/docs/tutorials/publish-and-consume-discovery-index.mdx b/docs/site/src/content/docs/tutorials/publish-and-consume-discovery-index.mdx index 57ca97fc67..e8802212b3 100644 --- a/docs/site/src/content/docs/tutorials/publish-and-consume-discovery-index.mdx +++ b/docs/site/src/content/docs/tutorials/publish-and-consume-discovery-index.mdx @@ -103,7 +103,7 @@ rstack discovery check --project discovery-project --posture development ```text test-expect valid origins=1 mappings=1 warning[discovery.posture.loopback-catalog-url] discovery-project/origins.yaml:5:17 /origins/tutorial-evidence/catalogUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. 0 errors, 1 warning in 3 files ``` @@ -136,10 +136,10 @@ rstack discovery package \ ```text test-expect packaged packageDigest=sha256: catalogRevision=sha256:7e0799f2c5fd24957e4d1372f757c40abef694110eb70fc260a0abdc312ca963 mappingRevision=sha256:332004ca3920c498539180946e8f2637e9998ba7e49cd98f31e19d6f818857ac warning[discovery.posture.loopback-catalog-url] discovery-project/package/discovery-index.json /origins/0/catalogUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. warning[discovery.posture.loopback-catalog-url] discovery-project/package/discovery-index.json /services/0/originUrl - the index advertises an address on the reader's own machine; production refuses it + The index advertises an address on the reader's own machine; production refuses it next: Publish HTTPS URLs on non-loopback hosts. ``` diff --git a/docs/site/src/content/docs/tutorials/request-evidence-as-sd-jwt-vc.mdx b/docs/site/src/content/docs/tutorials/request-evidence-as-sd-jwt-vc.mdx index 8ed09eb355..975db676ee 100644 --- a/docs/site/src/content/docs/tutorials/request-evidence-as-sd-jwt-vc.mdx +++ b/docs/site/src/content/docs/tutorials/request-evidence-as-sd-jwt-vc.mdx @@ -95,7 +95,7 @@ rstack evidence check . --target local-target.yaml ```text test-excerpt warning[evidence.posture.local-assurance] local-target.yaml:1:1 /assuranceProfile - local assurance permits locally held signing keys; production refuses it + Local assurance permits locally held signing keys; production refuses it next: Build a production or evidence-grade package with a Transit signer. 0 errors, 1 warning in 1 file ``` diff --git a/docs/site/src/data/breg-api.yaml b/docs/site/src/data/breg-api.yaml index 1e0858a69c..4b2669f88d 100644 --- a/docs/site/src/data/breg-api.yaml +++ b/docs/site/src/data/breg-api.yaml @@ -95,8 +95,8 @@ - ['`attachment.verification-pending`', '409', 'Submit found a file awaiting verification. Refresh the Proposal before submitting. The problem''s `fieldPath` names only `/attachments/`.'] - ['`attachment.verification-rejected`', '422', 'Submit found a rejected file in an optional slot. Replace or remove the file before submitting. The problem''s `fieldPath` names only `/attachments/`.'] - ['`precondition.required`', '428', 'A route that requires `If-Match` was called without it.'] - - ['`precondition.failed`', '412', '`If-Match` did not match the current revision, a Patch target was hidden or absent, or an ingestion item, immediate Action effect, or Proposal target or effect failed its boundary check. Invoke also answers this when a file already has a rejected verification verdict. Apply also answers this when a Proposal file it promotes is waiting for verification or was rejected by it. The response is value-free.'] - - ['`write.outside-boundary`', '403', 'A direct Create, direct Batch item, or Patch of a visible Record would put the resulting Record outside the selected access profile''s row boundary, or would leave a Record that a `record` disclosure condition then withholds from that profile. An immediate Action, or a Proposal applied by hand, is refused the same way when its plan creates or patches a Record that a `record` disclosure condition binding the applying profile would then withhold from it. A Patch, Batch item, immediate Action or Proposal applied by hand is also refused when a disclosure condition that binds the applying profile matches the Record and the write names one of its withheld fields or would lift the mark. The response has no field, value, claim, or location extension, and no item commits.'] + - ['`precondition.failed`', '412', '`If-Match` did not match the current revision, a write target was hidden or absent, or a write failed a generic boundary check. This includes target row-boundary refusals on immediate Action Patch and ingestion items. It also covers a frozen Create that fails the applying caller''s row boundary at Apply admission. Invoke also answers this when a file already has a rejected verification verdict. Apply also answers this when a Proposal file it promotes is waiting for verification or was rejected by it. The response is value-free.'] + - ['`write.outside-boundary`', '403', 'A direct Create, direct Batch item, or Patch of a visible Record would put the resulting Record outside the selected access profile''s row boundary, or would leave a Record that a `record` disclosure condition then withholds from that profile. This code also covers a row-boundary refusal for a request-only immediate Action Create or the resulting row of a Patch admitted by Proposal Apply. An immediate Action, or a Proposal applied by hand, is refused the same way when its plan creates or patches a Record that a `record` disclosure condition binding the applying profile would then withhold from it. A Patch, Batch item, immediate Action or Proposal applied by hand is also refused when a disclosure condition that binds the applying profile matches the Record and the write names one of its withheld fields or would lift the mark. The response has no field, value, claim, or location extension, and no item commits.'] - ['`proposal.rejected`', '409', 'A Review rejected the Proposal, and a rejection is final: Submit, Edit, Add, Answer, Revise, Rebase, Apply, Retry and Cancel are refused. Start a new Proposal to try again.'] - ['`proposal.review-result-mismatch`', '412', 'The current Review result differs from the retained approval. Apply commits no effects. Reconcile the review result before attempting application again.'] - ['`proposal.submission-expired`', '410', 'The submission''s review result window has lapsed or its detail was erased, and it has no application receipt. The Proposal itself stays readable.'] diff --git a/docs/site/src/data/posture-diagnostics.json b/docs/site/src/data/posture-diagnostics.json index 5ecaea67b9..90b3725e8b 100644 --- a/docs/site/src/data/posture-diagnostics.json +++ b/docs/site/src/data/posture-diagnostics.json @@ -88,7 +88,7 @@ { "code": "casework.posture.unrestricted-clients", "key": "allowedClients", - "condition": "this issuer entry admits a token from every client the issuer signs for", + "condition": "This issuer entry admits a token from every client the issuer signs for", "remedy": "List the OAuth clients whose access tokens this issuer entry admits.", "crates": [ "registry-casework" @@ -97,7 +97,7 @@ { "code": "discovery.posture.loopback-catalog-url", "key": "catalogUrl", - "condition": "the index advertises an address on the reader's own machine", + "condition": "The index advertises an address on the reader's own machine", "remedy": "Publish HTTPS URLs on non-loopback hosts.", "crates": [ "registry-discovery" @@ -115,7 +115,7 @@ { "code": "evidence.posture.credential-free-source", "key": "authentication", - "condition": "a credential-free source connection provides no client authentication", + "condition": "A credential-free source connection provides no client authentication", "remedy": "Bind an mtlsIdentity or configure an authenticated endpoint.", "crates": [ "registry-evidence" @@ -124,7 +124,7 @@ { "code": "evidence.posture.local-assurance", "key": "assuranceProfile", - "condition": "local assurance permits locally held signing keys", + "condition": "Local assurance permits locally held signing keys", "remedy": "Build a production or evidence-grade package with a Transit signer.", "crates": [ "registry-evidence", @@ -134,7 +134,7 @@ { "code": "evidence.posture.supervised-validation", "key": "validationMode", - "condition": "supervised validation permits a published loopback HTTP credential issuer", + "condition": "Supervised validation permits a published loopback HTTP credential issuer", "remedy": "Use validationMode: strict and publish an HTTPS credential issuer.", "crates": [ "registry-evidence-oid4vci" @@ -143,7 +143,7 @@ { "code": "evidence.posture.unrestricted-offer-gate", "key": "allowedClients", - "condition": "an unrestricted offer gate admits all values vouched for by the issuer", + "condition": "An unrestricted offer gate admits all values vouched for by the issuer", "remedy": "List the required clients and scopes explicitly.", "crates": [ "registry-evidence-oid4vci" @@ -215,7 +215,7 @@ { "code": "render.posture.local-assurance", "key": "assuranceProfile", - "condition": "seals use a local key file and are marked as test seals", + "condition": "Seals use a local key file and are marked as test seals", "remedy": "Configure assuranceProfile: production and sign through Transit.", "crates": [ "registry-render" @@ -224,18 +224,27 @@ { "code": "render.posture.seals-not-served", "key": "signing", - "condition": "the bundle declares seals, but this runtime has no signing block and renders those document types unsealed", + "condition": "The bundle declares seals, but this runtime has no signing block and renders those document types unsealed", "remedy": "Configure signing.seals for the bundle's seals, or deploy a bundle whose documents do not declare seals.", "crates": [ "registry-render" ] + }, + { + "code": "render.posture.shared-api-key", + "key": "apiKeyRef", + "condition": "Render accepts a shared bearer key for rendering", + "remedy": "Replace authentication.apiKeyRef with authentication.oidc and configure callers to obtain Render access tokens.", + "crates": [ + "registry-render" + ] } ], "explicit": [ { "code": "adapter.posture.anonymous-https", "key": "anonymousHttps", - "condition": "a fixed HTTPS source is reached without an application credential", + "condition": "A fixed HTTPS source is reached without an application credential", "crates": [ "registry-adapter-core" ] @@ -243,7 +252,7 @@ { "code": "breg.posture.scopeless-without-subject-rule", "key": "accessProfiles", - "condition": "a profile admits declared-kind tokens with no scope and no row rule keyed on the subject", + "condition": "A profile admits declared-kind tokens with no scope and no row rule keyed on the subject", "crates": [ "registry-breg" ] @@ -251,7 +260,7 @@ { "code": "platform.posture.client-actor-kinds", "key": "clientActorKinds", - "condition": "tokens from the named clients are treated as the declared kinds", + "condition": "Tokens from the named clients are treated as the declared kinds", "crates": [ "registry-platform-config" ] @@ -275,7 +284,7 @@ { "code": "platform.posture.issuer-actor-kind", "key": "actorKind", - "condition": "every token from this issuer is treated as the declared kind", + "condition": "Every token from this issuer is treated as the declared kind", "crates": [ "registry-platform-config" ] @@ -291,7 +300,7 @@ { "code": "platform.posture.jwt-access-token", "key": "accessTokenType", - "condition": "admits access tokens typed JWT. ID tokens stay refused", + "condition": "This setting admits access tokens typed JWT. ID tokens stay refused", "crates": [ "registry-platform-config" ] @@ -299,7 +308,7 @@ { "code": "platform.posture.scope-claim", "key": "scopeClaim", - "condition": "reads scopes from a claim other than scope", + "condition": "The service reads scopes from a claim other than scope", "crates": [ "registry-platform-config" ] @@ -307,7 +316,7 @@ { "code": "platform.posture.unrestricted-clients", "key": "allowedClients", - "condition": "admits a token from every client this issuer signs for", + "condition": "This issuer entry admits a token from every client this issuer signs for", "crates": [ "registry-platform-config" ] diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index e4a1ad8b59..dc6008f5e4 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + This applies to both the facade and the job store, which uses `store.transport`. + +- Adapter job check and startup identify signed Coordinator destination origin, + private range and TLS transport refusals with a configuration path and a fix. + The diagnostics omit configured URL, CIDR, trust profile and key values. + - BREAKING: Native `breg-records` v1 contracts publish `recordId` as the record path argument. Replace `record_id` in generated client and MCP path arguments. Refresh the Live Effective Contract and its pinned digest diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 496b471e97..eb6ab7a664 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + +- BREAKING: Invoke returns `403 write.outside-boundary` if an immediate Action Plan produces a + valid Create from the request alone and a target row predicate fails during the early boundary + check. BReg makes this check before reading target Records, evaluating + guards, or acquiring Evidence. A Create that takes a value from another effect's Record, a + boundary on a generated field, a timer firing, and a Plan computed on Evidence keep the generic + `412 precondition.failed` for target row-boundary refusals. Invoke OpenAPI documents the + row-boundary `403` when the compiled Plan admits a valid request-only Create and a target row + predicate can fail on that Create before any effect runs. Update clients that handled the early + refusal as `412` to handle `403 write.outside-boundary`. - Record and read-path permissions can select stored fields with `readableFields.upToClassification`. Consent-gated permissions require explicit fields. diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index 2316d0aea8..8c1d58679d 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -262,3 +262,4 @@ invariants: - {"id":"BREG-SEC-243","state":"enforced","targetWave":"W4","threat":"Pruning value-free dedupe receipts causes a cursor reset to fetch or duplicate a retained ask.","enforcementPoint":"Maintenance uses the observation recovery window; feed processing checks the stored mirror before network I/O.","refusal":"Prune exact bounded receipt counts while preserving mirrored questions and answers and skipping stored observations.","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} - {id: BREG-SEC-244, state: enforced, targetWave: W5, threat: "A signed hook is sent in plaintext to a non-loopback destination.", enforcementPoint: "BReg networkProfile decoding and shared destination policy construction before key resolution.", refusal: "Refuse non-loopback HTTP in both postures, including when the origin falls within allowedPrivateCidrs.", negativeId: BREG-NEG-244, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: event_destinations_refuse_non_loopback_plaintext_in_both_postures}} - {id: BREG-SEC-245, state: enforced, targetWave: W5, threat: "A field addition or reclassification widens a gated permission under the same consent scope.", enforcementPoint: "The compiler checks direct and read-path readableFields on every composed permission with requireConsent.", refusal: "Refuse a classification ceiling with breg.consent.readable-fields-explicit-required. Require explicit field lists on the gated permission.", negativeId: BREG-NEG-245, negativeTest: {path: crates/registry-breg/tests/consent_access.rs, name: a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths}} + - {id: BREG-SEC-246, state: enforced, targetWave: W5, threat: "An immediate Action create outside the caller's target row boundary answers in a way that depends on the Action's guards or on records the caller cannot read, turning the refusal into an oracle.", enforcementPoint: "The Action Invoke validates typed target boundary claims, then checks request-only Create candidates using caller inputs, Plan values and reserved identifiers before target reads, guards, Evidence acquisition or writes. Commit-only Evidence leaves the Plan request-only. Evidence preflight and finalization share the candidate and reserved identifiers.", refusal: "Refuse with the value-free 403 write.outside-boundary, the same for a passing guard, a failing guard the caller reads or cannot read, and a visible, hidden or missing target. A create that needs another effect's record, a boundary on a generated field, a timer firing and an Evidence-computed plan keep the generic 412 at the write.", negativeId: BREG-NEG-246, negativeTest: {path: crates/registry-breg/tests/postgres_immediate_actions.rs, name: an_action_create_outside_the_boundary_is_refused_before_targets_and_guards}} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index e30f32be5a..7429f25359 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -303,3 +303,5 @@ traceability: - {"id":"BREG-SEC-243","state":"enforced","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} - {id: BREG-SEC-244, state: enforced, negativeId: BREG-NEG-244, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: event_destinations_refuse_non_loopback_plaintext_in_both_postures}} - {id: BREG-SEC-245, state: enforced, negativeId: BREG-NEG-245, negativeTest: {path: crates/registry-breg/tests/consent_access.rs, name: a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths}} + # Commit Evidence proof: crates/registry-breg/tests/postgres_action_evidence.rs::commit_evidence_is_guard_only_and_replay_never_reacquires + - {id: BREG-SEC-246, state: enforced, negativeId: BREG-NEG-246, negativeTest: {path: crates/registry-breg/tests/postgres_immediate_actions.rs, name: an_action_create_outside_the_boundary_is_refused_before_targets_and_guards}} diff --git a/products/breg/examples/formats/ctl-report.json b/products/breg/examples/formats/ctl-report.json index 93f7d46ac1..488e1ab2da 100644 --- a/products/breg/examples/formats/ctl-report.json +++ b/products/breg/examples/formats/ctl-report.json @@ -1664,13 +1664,13 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:164298649ea88ba9ce13697b513f4c2dc8028c77b5bbeff20a3daa3508824f9e", + "revision": "sha256:da8467d58f3d97da519f2f7c59ef3eaf9c64cd585cf5bae8b40fdc5fe87a080b", "statisticalDatasets": [] }, "kind": "BRegCtlReport", "ok": true, "profile": "authoring", - "revision": "sha256:164298649ea88ba9ce13697b513f4c2dc8028c77b5bbeff20a3daa3508824f9e", + "revision": "sha256:da8467d58f3d97da519f2f7c59ef3eaf9c64cd585cf5bae8b40fdc5fe87a080b", "status": "complete", "version": "0.52.0-dev" } diff --git a/products/breg/examples/formats/explain/actions-explanation.json b/products/breg/examples/formats/explain/actions-explanation.json index edbb0ad61b..7119b2880a 100644 --- a/products/breg/examples/formats/explain/actions-explanation.json +++ b/products/breg/examples/formats/explain/actions-explanation.json @@ -1641,6 +1641,6 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:164298649ea88ba9ce13697b513f4c2dc8028c77b5bbeff20a3daa3508824f9e", + "revision": "sha256:da8467d58f3d97da519f2f7c59ef3eaf9c64cd585cf5bae8b40fdc5fe87a080b", "statisticalDatasets": [] } diff --git a/products/breg/examples/formats/explain/model-explanation.json b/products/breg/examples/formats/explain/model-explanation.json index e9443eadec..f02e5d879e 100644 --- a/products/breg/examples/formats/explain/model-explanation.json +++ b/products/breg/examples/formats/explain/model-explanation.json @@ -2602,7 +2602,7 @@ "protocol": "id.registrystack.org/protocols/review/v1" } ], - "revision": "sha256:164298649ea88ba9ce13697b513f4c2dc8028c77b5bbeff20a3daa3508824f9e", + "revision": "sha256:da8467d58f3d97da519f2f7c59ef3eaf9c64cd585cf5bae8b40fdc5fe87a080b", "statisticalDatasets": [], "version": "0.1.0" } diff --git a/products/breg/fixtures/asset-registration-actions/tests/journeys.yaml b/products/breg/fixtures/asset-registration-actions/tests/journeys.yaml index 00346dc68a..4661b55a3f 100644 --- a/products/breg/fixtures/asset-registration-actions/tests/journeys.yaml +++ b/products/breg/fixtures/asset-registration-actions/tests/journeys.yaml @@ -97,5 +97,5 @@ journeys: initialResult: passed expect: outcome: refusal - status: 412 - problemCode: precondition.failed + status: 403 + problemCode: write.outside-boundary diff --git a/products/breg/generated/facility/generated/openapi.json b/products/breg/generated/facility/generated/openapi.json index 1d5bb9d848..c5b9c11715 100644 --- a/products/breg/generated/facility/generated/openapi.json +++ b/products/breg/generated/facility/generated/openapi.json @@ -1 +1 @@ -{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"enum":["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}},"then":{"allOf":[{"else":{"properties":{"status":{"const":422}}},"if":{"properties":{"code":{"const":"attachment.verification-pending"}}},"then":{"properties":{"status":{"const":409}}}}],"properties":{"fieldPath":{"pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$","type":"string"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","fieldPath"]},"required":["fieldPath"]}},{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","failedCheck"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard-failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical-dataset.release-refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical-dataset.release-refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical-dataset.version-withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical-dataset.version-withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"access-profile.ambiguous"}}},"then":{"additionalProperties":true,"not":{"required":["failedCheck"]},"properties":{"status":{"const":400}},"required":["accessProfiles"]}},{"if":{"properties":{"code":{"not":{"const":"access-profile.ambiguous"}}}},"then":{"not":{"required":["accessProfiles"]}}},{"if":{"properties":{"code":{"const":"action.evidence-failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler-failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"anyOf":[{"properties":{"code":{"const":"access-profile.ambiguous"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},{"properties":{"code":{"const":"action.evidence-failed"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/evidence-failed"}}},{"properties":{"code":{"const":"action.guard-failed"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}}},{"properties":{"code":{"const":"action.handler-failed"},"status":{"const":500},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/handler-failed"}}},{"properties":{"code":{"const":"action.refused"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/refused"}}},{"properties":{"code":{"const":"attachment.content-type"},"status":{"const":415},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},{"properties":{"code":{"const":"attachment.digest-mismatch"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch"}}},{"properties":{"code":{"const":"attachment.limit-reached"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached"}}},{"properties":{"code":{"const":"attachment.required"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/required"}}},{"properties":{"code":{"const":"attachment.slot-write-once"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once"}}},{"properties":{"code":{"const":"attachment.too-large"},"status":{"const":413},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},{"properties":{"code":{"const":"attachment.verification-pending"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}}},{"properties":{"code":{"const":"attachment.verification-rejected"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected"}}},{"properties":{"code":{"const":"authentication.refused"},"status":{"const":401},"type":{"const":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},{"properties":{"code":{"const":"idempotency.expired"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},{"properties":{"code":{"const":"idempotency.key-reused"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}}},{"properties":{"code":{"const":"ingestion.chunk-mismatch"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch"}}},{"properties":{"code":{"const":"ingestion.profile-mismatch"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch"}}},{"properties":{"code":{"const":"ingestion.receipt-erased"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased"}}},{"properties":{"code":{"const":"ingestion.run-blocked"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked"}}},{"properties":{"code":{"const":"ingestion.run-not-open"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open"}}},{"properties":{"code":{"const":"lookup.unresolved"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/lookup/unresolved"}}},{"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},{"properties":{"code":{"const":"precondition.failed"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},{"properties":{"code":{"const":"precondition.required"},"status":{"const":428},"type":{"const":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},{"properties":{"code":{"const":"profile.not-authorized"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},{"properties":{"code":{"const":"proposal.rejected"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},{"properties":{"code":{"const":"proposal.review-result-mismatch"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch"}}},{"properties":{"code":{"const":"proposal.submission-expired"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired"}}},{"properties":{"code":{"const":"query.cursor-invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}}},{"properties":{"code":{"const":"query.filter-required"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/filter-required"}}},{"properties":{"code":{"const":"query.invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},{"properties":{"code":{"const":"request.access-reason-required"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/access-reason-required"}}},{"properties":{"code":{"const":"request.invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},{"properties":{"code":{"const":"request.timeout"},"status":{"const":504},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},{"properties":{"code":{"const":"resource.not-found"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},{"properties":{"code":{"const":"runtime.field-encryption.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}}},{"properties":{"code":{"const":"service.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},{"properties":{"code":{"const":"source.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},{"properties":{"code":{"const":"statistical-dataset.domain-violation"},"status":{"const":500},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation"}}},{"properties":{"code":{"const":"statistical-dataset.release-refused"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused"}}},{"properties":{"code":{"const":"statistical-dataset.version-conflict"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict"}}},{"properties":{"code":{"const":"statistical-dataset.version-withdrawn"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn"}}},{"properties":{"code":{"const":"unsupported.media-type"},"status":{"const":415},"type":{"const":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},{"properties":{"code":{"const":"write.outside-boundary"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}}],"properties":{"accessProfiles":{"items":{"maxLength":128,"minLength":1,"type":"string"},"minItems":2,"type":"array","uniqueItems":true},"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["access-profile.ambiguous","action.evidence-failed","action.guard-failed","action.handler-failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.limit-reached","attachment.required","attachment.slot-write-once","attachment.too-large","attachment.verification-pending","attachment.verification-rejected","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk-mismatch","ingestion.profile-mismatch","ingestion.receipt-erased","ingestion.run-blocked","ingestion.run-not-open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","profile.not-authorized","proposal.rejected","proposal.review-result-mismatch","proposal.submission-expired","query.cursor-invalid","query.filter-required","query.invalid","request.access-reason-required","request.invalid","request.timeout","resource.not-found","runtime.field-encryption.unavailable","service.unavailable","source.unavailable","statistical-dataset.domain-violation","statistical-dataset.release-refused","statistical-dataset.version-conflict","statistical-dataset.version-withdrawn","unsupported.media-type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"failedCheck":{"description":"The check that refused the request, included only in development.","type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-address-invoke-input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"action-correct-address-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-deactivate-facility-invoke-input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"action-deactivate-facility-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-register-facility-availability-input":{"$id":"urn:breg:action:register-facility:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"operatorId":{"format":"uuid","type":"string"}},"required":["operatorId"]},"targetInput":{"const":"operatorId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["operatorId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-availability-response":{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-invoke-input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"action-register-facility-invoke-response":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"directory-entry":{"$id":"urn:breg:record-type:directory-entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"directory-entry-create-input":{"$id":"urn:breg:record-type:directory-entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"facility":{"$id":"urn:breg:record-type:facility","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"required":["facilityCode","name","addressLine","city","postalCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"facility-assignment":{"$id":"urn:breg:record-type:facility-assignment","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"required":["facility","operator","jurisdiction"],"type":"object","x-registry-mutationMode":"create-only"},"operator":{"$id":"urn:breg:record-type:operator","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"operator-create-input":{"$id":"urn:breg:record-type:operator:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"facility-registry","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/correct-address/proposals":{"post":{"operationId":"actions.correct-address.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"correctAddress","attachments":[{"contentTypes":["application/pdf"],"id":"supporting-document","maximumBytes":1048576,"required":false}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"execution":{"application":"automatic","mode":"proposal","review":"required"},"id":"correct-address","inputMode":"handler","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}}],"maximumInputStringBytes":16384,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-address","operation":"patch","recordType":"facility"}],"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a","route":"/v1/actions/correct-address/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-address-invoke-input","method":"POST","operationId":"actions.correct-address.start","path":"/v1/actions/correct-address/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-address-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/deactivate-facility/proposals":{"post":{"operationId":"actions.deactivate-facility.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"deactivateFacility","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"deactivate-facility","inputMode":"fixed","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-status","operation":"patch","recordType":"facility"}],"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d","route":"/v1/actions/deactivate-facility/proposals","routes":{"availability":null,"start":{"inputSchema":"action-deactivate-facility-invoke-input","method":"POST","operationId":"actions.deactivate-facility.start","path":"/v1/actions/deactivate-facility/proposals","requiresIdempotencyKey":true,"responseSchema":"action-deactivate-facility-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility":{"post":{"operationId":"actions.register-facility.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard-failed":{"value":{"code":"action.guard-failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field-encryption.unavailable":{"value":{"code":"runtime.field-encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility/availability":{"post":{"operationId":"actions.register-facility.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field-encryption.unavailable":{"value":{"code":"runtime.field-encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","query.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/review-context":{"get":{"description":"One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB.","operationId":"proposals.get-review-context-batch","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["proposal-reviewer"],"maxLength":128,"type":"string"}},{"description":"One to 100 distinct canonical Proposal UUIDs, in response order.","explode":false,"in":"query","name":"ids","required":true,"schema":{"items":{"format":"uuid","type":"string"},"maxItems":100,"minItems":1,"type":"array","uniqueItems":true},"style":"form"}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"context":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"},"id":{"format":"uuid","type":"string"},"status":{"const":"visible"}},"required":["id","status","context"],"type":"object"},{"additionalProperties":false,"properties":{"id":{"format":"uuid","type":"string"},"status":{"const":"concealed"}},"required":["id","status"],"type":"object"}]},"maxItems":100,"minItems":1,"type":"array"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard-failed":{"value":{"code":"action.guard-failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}},"proposal.review-result-mismatch":{"value":{"code":"proposal.review-result-mismatch","detail":"The current review result does not match the retained approval.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.guard-failed","precondition.failed","proposal.review-result-mismatch"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard-failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier"]}},"/v1/proposals/{proposal_id}/attachments/supporting-document":{"delete":{"operationId":"proposals.attachments.supporting-document.delete","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]},"get":{"operationId":"proposals.attachments.supporting-document.get","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author","proposal-reviewer"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"*/*":{"schema":{"contentMediaType":"application/octet-stream","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author","proposal-reviewer"]},"patch":{"operationId":"proposals.attachments.supporting-document.patch","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/pdf":{"schema":{"format":"binary","maxLength":1048576,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"413":{"content":{"application/problem+json":{"examples":{"attachment.too-large":{"value":{"code":"attachment.too-large","detail":"The file is larger than the attachment slot accepts.","status":413,"title":"Content Too Large","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.too-large"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"attachment.content-type":{"value":{"code":"attachment.content-type","detail":"The file media type is not one the attachment slot accepts.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.content-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/retry":{"post":{"operationId":"proposals.retry","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/review-context":{"get":{"operationId":"proposals.get-review-context","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["proposal-reviewer"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request live applicant answers for a displayed human review context. Admission and preflight reads omit this option and receive no intrinsic asks.","in":"query","name":"include","required":false,"schema":{"const":"answers"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"answeredAt":{"format":"date-time","type":"string"},"documents":{"items":{"additionalProperties":false,"properties":{"byteSize":{"maximum":16777216,"minimum":1,"type":"integer"},"contentType":{"maxLength":255,"type":"string"},"download":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"method":{"const":"GET"},"operation":{"const":"get-review-context"},"path":{"type":"string"}},"required":["method","operation","accessProfile","path"],"type":"object"},"id":{"format":"uuid","type":"string"},"sha256":{"pattern":"^[0-9a-f]{64}$","type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["id","sha256","contentType","byteSize","verificationStatus"],"type":"object"},"maxItems":32,"type":"array"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["documents","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state"],"type":"object"},"maxItems":50,"type":"array"},"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}/review-status":{"get":{"operationId":"proposals.get-review-status","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["casework-review-status","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress.","in":"query","name":"include","required":false,"schema":{"const":"progress"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"reference":{"type":"string"}},"required":["reference"],"type":"object"},"effectDigest":{"type":"string"},"handoff":{"additionalProperties":false,"properties":{"reason":{"enum":["remote-refused","producer-identity-mismatch","review-acceptance-changed","review-policy-changed","submission-recovery-expired","operator-closed","unspecified"]},"state":{"enum":["pending","accepted","failed","withdrawn"]}},"required":["state"],"type":"object"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"progressCode":{"description":"Institution-defined applicant-visible progress. Absent when the institution conceals the current stage, progress was not requested or granted, the provider is unavailable, or the accepted review round is no longer live.","maxLength":64,"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"requestId":{"format":"uuid","type":"string"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["casework-review-status","facility-correction-author"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"proposal.submission-expired":{"value":{"code":"proposal.submission-expired","detail":"The review result and application receipt of the submission are no longer retained.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["proposal.submission-expired"]}},"type":"object"}]}}},"description":"The submission's review result and application receipt are no longer retained","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"attachment.verification-pending":{"value":{"code":"attachment.verification-pending","detail":"The attachment is awaiting verification. Refresh the Proposal before submitting.","fieldPath":"/attachments/supporting-document","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}},"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.verification-pending","idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard-failed":{"value":{"code":"action.guard-failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.guard-failed","precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard-failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"422":{"content":{"application/problem+json":{"examples":{"action.refused/invalid-postal-code":{"value":{"code":"action.refused","detail":"Postal code is invalid","refusalCode":"invalid-postal-code","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/refused"}},"attachment.verification-rejected":{"value":{"code":"attachment.verification-rejected","detail":"The attachment was rejected by verification. Replace or remove the file before submitting.","fieldPath":"/attachments/supporting-document","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.refused","attachment.verification-rejected"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"500":{"content":{"application/problem+json":{"examples":{"action.handler-failed":{"value":{"code":"action.handler-failed","detail":"The action handler could not produce an accepted result.","status":500,"title":"Internal Server Error","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/handler-failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.handler-failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/records/directory-entries":{"get":{"operationId":"records.directory-entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","requiredFilters":[],"selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.directory-entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/directory-entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/directory-entries/{record_id}":{"get":{"operationId":"records.directory-entry.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.directory-entry.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities":{"get":{"operationId":"records.facility.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["addressLine","city","facilityCode","jurisdiction","name","postalCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facilities/{record_id}":{"get":{"operationId":"records.facility.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","proposal-reviewer"],"x-registry-operation":"get","x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities/{record_id}/operators":{"get":{"operationId":"records.facility.path.operators","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments":{"get":{"operationId":"records.facility-assignment.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[{"operators":["equals","in","is-null","is-not-null"],"property":"facility"},{"operators":["equals","in","is-null","is-not-null"],"property":"operator"}],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["facility","jurisdiction","operator"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments/{record_id}":{"get":{"operationId":"records.facility-assignment.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"get","x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators":{"get":{"operationId":"records.operator.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null},"operator-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"operator-editor","requiredFilters":[],"selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.operator.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/operator-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"create","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators/{record_id}":{"get":{"operationId":"records.operator.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"get","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.operator.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"patch","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file +{"components":{"schemas":{"ImmediateActionPrecondition":{"additionalProperties":false,"properties":{"ifMatch":{"maxLength":256,"minLength":3,"pattern":"^\\\"[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"required":["ifMatch"],"type":"object"},"ImmediateActionResultReference":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"enum":["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}},"then":{"allOf":[{"else":{"properties":{"status":{"const":422}}},"if":{"properties":{"code":{"const":"attachment.verification-pending"}}},"then":{"properties":{"status":{"const":409}}}}],"properties":{"fieldPath":{"pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$","type":"string"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","fieldPath"]},"required":["fieldPath"]}},{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","failedCheck"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard-failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical-dataset.release-refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical-dataset.release-refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical-dataset.version-withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical-dataset.version-withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"access-profile.ambiguous"}}},"then":{"additionalProperties":true,"not":{"required":["failedCheck"]},"properties":{"status":{"const":400}},"required":["accessProfiles"]}},{"if":{"properties":{"code":{"not":{"const":"access-profile.ambiguous"}}}},"then":{"not":{"required":["accessProfiles"]}}},{"if":{"properties":{"code":{"const":"action.evidence-failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler-failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"anyOf":[{"properties":{"code":{"const":"access-profile.ambiguous"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},{"properties":{"code":{"const":"action.evidence-failed"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/evidence-failed"}}},{"properties":{"code":{"const":"action.guard-failed"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}}},{"properties":{"code":{"const":"action.handler-failed"},"status":{"const":500},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/handler-failed"}}},{"properties":{"code":{"const":"action.refused"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/refused"}}},{"properties":{"code":{"const":"attachment.content-type"},"status":{"const":415},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},{"properties":{"code":{"const":"attachment.digest-mismatch"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch"}}},{"properties":{"code":{"const":"attachment.limit-reached"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached"}}},{"properties":{"code":{"const":"attachment.required"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/required"}}},{"properties":{"code":{"const":"attachment.slot-write-once"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once"}}},{"properties":{"code":{"const":"attachment.too-large"},"status":{"const":413},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},{"properties":{"code":{"const":"attachment.verification-pending"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}}},{"properties":{"code":{"const":"attachment.verification-rejected"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected"}}},{"properties":{"code":{"const":"authentication.refused"},"status":{"const":401},"type":{"const":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},{"properties":{"code":{"const":"idempotency.expired"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},{"properties":{"code":{"const":"idempotency.key-reused"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}}},{"properties":{"code":{"const":"ingestion.chunk-mismatch"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch"}}},{"properties":{"code":{"const":"ingestion.profile-mismatch"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch"}}},{"properties":{"code":{"const":"ingestion.receipt-erased"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased"}}},{"properties":{"code":{"const":"ingestion.run-blocked"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked"}}},{"properties":{"code":{"const":"ingestion.run-not-open"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open"}}},{"properties":{"code":{"const":"lookup.unresolved"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/lookup/unresolved"}}},{"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},{"properties":{"code":{"const":"precondition.failed"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},{"properties":{"code":{"const":"precondition.required"},"status":{"const":428},"type":{"const":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},{"properties":{"code":{"const":"profile.not-authorized"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},{"properties":{"code":{"const":"proposal.rejected"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},{"properties":{"code":{"const":"proposal.review-result-mismatch"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch"}}},{"properties":{"code":{"const":"proposal.submission-expired"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired"}}},{"properties":{"code":{"const":"query.cursor-invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}}},{"properties":{"code":{"const":"query.filter-required"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/filter-required"}}},{"properties":{"code":{"const":"query.invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},{"properties":{"code":{"const":"request.access-reason-required"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/access-reason-required"}}},{"properties":{"code":{"const":"request.invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},{"properties":{"code":{"const":"request.timeout"},"status":{"const":504},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},{"properties":{"code":{"const":"resource.not-found"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},{"properties":{"code":{"const":"runtime.field-encryption.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}}},{"properties":{"code":{"const":"service.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},{"properties":{"code":{"const":"source.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},{"properties":{"code":{"const":"statistical-dataset.domain-violation"},"status":{"const":500},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation"}}},{"properties":{"code":{"const":"statistical-dataset.release-refused"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused"}}},{"properties":{"code":{"const":"statistical-dataset.version-conflict"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict"}}},{"properties":{"code":{"const":"statistical-dataset.version-withdrawn"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn"}}},{"properties":{"code":{"const":"unsupported.media-type"},"status":{"const":415},"type":{"const":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},{"properties":{"code":{"const":"write.outside-boundary"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}}],"properties":{"accessProfiles":{"items":{"maxLength":128,"minLength":1,"type":"string"},"minItems":2,"type":"array","uniqueItems":true},"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["access-profile.ambiguous","action.evidence-failed","action.guard-failed","action.handler-failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.limit-reached","attachment.required","attachment.slot-write-once","attachment.too-large","attachment.verification-pending","attachment.verification-rejected","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk-mismatch","ingestion.profile-mismatch","ingestion.receipt-erased","ingestion.run-blocked","ingestion.run-not-open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","profile.not-authorized","proposal.rejected","proposal.review-result-mismatch","proposal.submission-expired","query.cursor-invalid","query.filter-required","query.invalid","request.access-reason-required","request.invalid","request.timeout","resource.not-found","runtime.field-encryption.unavailable","service.unavailable","source.unavailable","statistical-dataset.domain-violation","statistical-dataset.release-refused","statistical-dataset.version-conflict","statistical-dataset.version-withdrawn","unsupported.media-type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"failedCheck":{"description":"The check that refused the request, included only in development.","type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"action-correct-address-invoke-input":{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},"action-correct-address-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-deactivate-facility-invoke-input":{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},"action-deactivate-facility-invoke-response":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"action-register-facility-availability-input":{"$id":"urn:breg:action:register-facility:availability-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"oneOf":[{"properties":{"input":{"properties":{"operatorId":{"format":"uuid","type":"string"}},"required":["operatorId"]},"targetInput":{"const":"operatorId"}}}],"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"},"targetInput":{"enum":["operatorId"],"type":"string"}},"required":["targetInput","input"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-availability-response":{"$id":"urn:breg:action:register-facility:availability-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"availability":{"oneOf":[{"additionalProperties":false,"properties":{"available":{"const":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"}},"required":["available","observedRevision"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"const":false},"guardLabel":{"maxLength":256,"minLength":1,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"guard-not-satisfied"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"missingInputs":{"items":{"enum":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"string"},"minItems":1,"type":"array","uniqueItems":true},"observedRevision":{"format":"int64","minimum":1,"type":"integer"},"reason":{"const":"input-required"},"recovery":{"const":"correct-input"}},"required":["available","observedRevision","reason","recovery","missingInputs"],"type":"object"},{"additionalProperties":false,"properties":{"available":{"type":"null"},"observedRevision":{"type":"null"},"reason":{"const":"not-disclosed"},"recovery":{"const":"none"}},"required":["available","observedRevision","reason","recovery"],"type":"object"}]}},"required":["availability"],"type":"object","x-registry-action":"register-facility"},"action-register-facility-invoke-input":{"$id":"urn:breg:action:register-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"operatorId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":["facilityCode","name","addressLine","city","postalCode","operatorId","jurisdiction"],"type":"object"},"preconditions":{"additionalProperties":false,"properties":{},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"register-facility","x-registry-requiredConditionKeys":[]},"action-register-facility-invoke-response":{"$id":"urn:breg:action:register-facility:invoke-response","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"action":{"const":"register-facility"},"applicationId":{"format":"uuid","type":"string"},"results":{"additionalProperties":false,"properties":{"assignment":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility-assignment"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"facility":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"const":"facility"},"revision":{"format":"int64","minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"}},"required":["assignment","facility"],"type":"object"}},"required":["action","applicationId","results"],"type":"object"},"directory-entry":{"$id":"urn:breg:record-type:directory-entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"directory-entry-create-input":{"$id":"urn:breg:record-type:directory-entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"required":["name","email","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"facility":{"$id":"urn:breg:record-type:facility","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"required":["facilityCode","name","addressLine","city","postalCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable","x-registry-mutationPolicy":{"patch":"proposal-required"}},"facility-assignment":{"$id":"urn:breg:record-type:facility-assignment","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"required":["facility","operator","jurisdiction"],"type":"object","x-registry-mutationMode":"create-only"},"operator":{"$id":"urn:breg:record-type:operator","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"},"operator-create-input":{"$id":"urn:breg:record-type:operator:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"required":["operatorCode","status","jurisdiction"],"type":"object","x-registry-mutationMode":"mutable"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"facility-registry","version":"0.1.0"},"openapi":"3.1.0","paths":{"/v1/actions/correct-address/proposals":{"post":{"operationId":"actions.correct-address.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-correct-address-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"correctAddress","attachments":[{"contentTypes":["application/pdf"],"id":"supporting-document","maximumBytes":1048576,"required":false}],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a frozen address correction for independent review and later application.","label":"Correct facility address"},"execution":{"application":"automatic","mode":"proposal","review":"required"},"id":"correct-address","inputMode":"handler","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}}],"maximumInputStringBytes":16384,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-address","operation":"patch","recordType":"facility"}],"revision":"sha256:efb20d40704ae6c133b660f2fe3d556b4a00ee5478a5871cf1fd026e7d7b6b7a","route":"/v1/actions/correct-address/proposals","routes":{"availability":null,"start":{"inputSchema":"action-correct-address-invoke-input","method":"POST","operationId":"actions.correct-address.start","path":"/v1/actions/correct-address/proposals","requiresIdempotencyKey":true,"responseSchema":"action-correct-address-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/deactivate-facility/proposals":{"post":{"operationId":"actions.deactivate-facility.start","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-input"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-deactivate-facility-invoke-response"}}},"description":"Proposal created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag for the created Proposal.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Location":{"description":"Relative URL of the created Proposal.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-correction-author"],"x-registry-action":{"access":{"accessProfiles":["facility-correction-author"]},"apiName":"deactivateFacility","attachments":[],"bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"display":{"description":"Submit a durable deactivation that requires no external review.","label":"Deactivate facility"},"execution":{"application":"manual","mode":"proposal","review":"none"},"id":"deactivate-facility","inputMode":"fixed","inputs":[{"apiName":"facilityId","classification":"internal","fieldType":{"onDelete":"restrict","target":"facility","type":"reference"},"id":"facility","label":"facilityId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"facilityId","input":"facility","targetRecordType":"facility"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility-status","operation":"patch","recordType":"facility"}],"revision":"sha256:9237300ee419a0014c3b123cc7ac90eb9623cb4c45bba4a65c03936083299f1d","route":"/v1/actions/deactivate-facility/proposals","routes":{"availability":null,"start":{"inputSchema":"action-deactivate-facility-invoke-input","method":"POST","operationId":"actions.deactivate-facility.start","path":"/v1/actions/deactivate-facility/proposals","requiresIdempotencyKey":true,"responseSchema":"action-deactivate-facility-invoke-response"}}},"x-registry-defaultAccessProfile":"facility-correction-author","x-registry-operation":"start","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility":{"post":{"operationId":"actions.register-facility.invoke","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to the action route, selected profile, package revision, normalized action input, preconditions, and granted result contract.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-invoke-response"}}},"description":"Immediate action committed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard-failed":{"value":{"code":"action.guard-failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field-encryption.unavailable":{"value":{"code":"runtime.field-encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"invoke"}},"/v1/actions/register-facility/availability":{"post":{"operationId":"actions.register-facility.availability","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-input"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/action-register-facility-availability-response"}}},"description":"Action availability returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"runtime.field-encryption.unavailable":{"value":{"code":"runtime.field-encryption.unavailable","detail":"The Registry field-encryption service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}},"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-registrar"],"x-registry-action":{"access":{"accessProfiles":["facility-registrar"]},"apiName":"registerFacility","bounds":{"maximumFieldMutations":128,"maximumSnapshotBytes":2097152,"maximumTargets":16},"conditionRoute":null,"display":{"description":"Create a facility and its initial operator assignment atomically.","label":"Register facility"},"execution":{"mode":"immediate"},"id":"register-facility","inputMode":"fixed","inputs":[{"apiName":"facilityCode","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":1,"type":"string"},"id":"facility-code","label":"facilityCode","nullable":false,"required":true,"schema":{"maxLength":64,"minLength":1,"type":"string"}},{"apiName":"name","classification":"internal","fieldType":{"maximumLength":200,"minimumLength":1,"type":"string"},"id":"name","label":"name","nullable":false,"required":true,"schema":{"maxLength":200,"minLength":1,"type":"string"}},{"apiName":"addressLine","classification":"internal","fieldType":{"maximumLength":240,"minimumLength":1,"type":"string"},"id":"address-line","label":"addressLine","nullable":false,"required":true,"schema":{"maxLength":240,"minLength":1,"type":"string"}},{"apiName":"city","classification":"internal","fieldType":{"maximumLength":120,"minimumLength":1,"type":"string"},"id":"city","label":"city","nullable":false,"required":true,"schema":{"maxLength":120,"minLength":1,"type":"string"}},{"apiName":"postalCode","classification":"internal","fieldType":{"maximumLength":24,"minimumLength":1,"type":"string"},"id":"postal-code","label":"postalCode","nullable":false,"required":true,"schema":{"maxLength":24,"minLength":1,"type":"string"}},{"apiName":"operatorId","classification":"internal","fieldType":{"onDelete":"restrict","target":"operator","type":"reference"},"id":"operator","label":"operatorId","nullable":false,"required":true,"schema":{"format":"uuid","type":"string"}},{"apiName":"jurisdiction","classification":"internal","fieldType":{"maximumLength":40,"minimumLength":1,"type":"string"},"id":"jurisdiction","label":"jurisdiction","nullable":false,"required":true,"schema":{"maxLength":40,"minLength":1,"type":"string"}}],"maximumInputStringBytes":null,"referenceInputs":[{"apiName":"operatorId","input":"operator","targetRecordType":"operator"}],"requiredConditionKeys":[],"resultEffects":[{"effect":"facility","operation":"create","recordType":"facility"},{"effect":"assignment","operation":"create","recordType":"facility-assignment"}],"revision":"sha256:5b5de70fa9b8f831387fc08e520f16fccd71863f18f3efe8b7999728927910f6","route":"/v1/actions/register-facility","routes":{"availability":{"inputSchema":"action-register-facility-availability-input","method":"POST","operationId":"actions.register-facility.availability","path":"/v1/actions/register-facility/availability","requiresIdempotencyKey":false,"responseSchema":"action-register-facility-availability-response"},"invoke":{"inputSchema":"action-register-facility-invoke-input","method":"POST","operationId":"actions.register-facility.invoke","path":"/v1/actions/register-facility","requiresIdempotencyKey":true,"responseSchema":"action-register-facility-invoke-response"},"targetConditions":null}},"x-registry-defaultAccessProfile":"facility-registrar","x-registry-operation":"invoke","x-registry-routeKind":"availability"}},"/v1/proposals":{"get":{"operationId":"proposals.list","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"owner","schema":{"const":"caller"}},{"in":"query","name":"target","schema":{"format":"uuid","type":"string"}},{"in":"query","name":"state","schema":{"enum":["draft","submitted","applied","cancelled","rejected"]}},{"in":"query","name":"turn","schema":{"enum":["party","official","nobody"]}},{"in":"query","name":"cursor","schema":{"type":"string"}},{"description":"The most items a page holds. A page may hold fewer than `limit` items, so keep paging while `nextCursor` is present.","in":"query","name":"limit","schema":{"default":50,"maximum":100,"minimum":1,"type":"integer"}},{"in":"query","name":"pendingManualApplication","schema":{"default":false,"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"},"maxItems":100,"type":"array"},"nextCursor":{"type":"string"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","query.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/review-context":{"get":{"description":"One bounded transport exchange under each item's current get-review-context authority. Ordered visible or concealed results; operational failures refuse the whole batch. Maximum response is 8 MiB.","operationId":"proposals.get-review-context-batch","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["proposal-reviewer"],"maxLength":128,"type":"string"}},{"description":"One to 100 distinct canonical Proposal UUIDs, in response order.","explode":false,"in":"query","name":"ids","required":true,"schema":{"items":{"format":"uuid","type":"string"},"maxItems":100,"minItems":1,"type":"array","uniqueItems":true},"style":"form"}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"items":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"context":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"},"id":{"format":"uuid","type":"string"},"status":{"const":"visible"}},"required":["id","status","context"],"type":"object"},{"additionalProperties":false,"properties":{"id":{"format":"uuid","type":"string"},"status":{"const":"concealed"}},"required":["id","status"],"type":"object"}]},"maxItems":100,"minItems":1,"type":"array"}},"required":["items"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}":{"get":{"operationId":"proposals.get","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/apply":{"post":{"operationId":"proposals.apply","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"reason":{"description":"Optional application explanation, preserved unchanged. At most 4096 Unicode characters; NUL is refused.","maxLength":4096,"pattern":"^[^\\u0000]*$","type":"string"},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["submissionVersion","effectDigest"],"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard-failed":{"value":{"code":"action.guard-failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}},"proposal.review-result-mismatch":{"value":{"code":"proposal.review-result-mismatch","detail":"The current review result does not match the retained approval.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.guard-failed","precondition.failed","proposal.review-result-mismatch"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard-failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier"]}},"/v1/proposals/{proposal_id}/attachments/supporting-document":{"delete":{"operationId":"proposals.attachments.supporting-document.delete","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]},"get":{"operationId":"proposals.attachments.supporting-document.get","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author","proposal-reviewer"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"query","name":"submissionVersion","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"reviewContextField","required":false,"schema":{"pattern":"^[a-z][a-zA-Z0-9]{0,63}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"effectDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}},{"description":"All three review-context query members are required together and select only get-review-context authority. Omit all three for ordinary get authority.","in":"query","name":"contextSchemaDigest","required":false,"schema":{"pattern":"^sha256:[a-f0-9]{64}$","type":"string"}}],"responses":{"200":{"content":{"*/*":{"schema":{"contentMediaType":"application/octet-stream","maxLength":16777216,"type":"string"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author","proposal-reviewer"]},"patch":{"operationId":"proposals.attachments.supporting-document.patch","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/pdf":{"schema":{"format":"binary","maxLength":1048576,"type":"string"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"413":{"content":{"application/problem+json":{"examples":{"attachment.too-large":{"value":{"code":"attachment.too-large","detail":"The file is larger than the attachment slot accepts.","status":413,"title":"Content Too Large","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.too-large"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"attachment.content-type":{"value":{"code":"attachment.content-type","detail":"The file media type is not one the attachment slot accepts.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.content-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/cancel":{"post":{"operationId":"proposals.cancel","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/edit":{"post":{"operationId":"proposals.edit","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/rebase":{"post":{"operationId":"proposals.rebase","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/retry":{"post":{"operationId":"proposals.retry","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/review-context":{"get":{"operationId":"proposals.get-review-context","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["proposal-reviewer"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request live applicant answers for a displayed human review context. Admission and preflight reads omit this option and receive no intrinsic asks.","in":"query","name":"include","required":false,"schema":{"const":"answers"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"answeredAt":{"format":"date-time","type":"string"},"documents":{"items":{"additionalProperties":false,"properties":{"byteSize":{"maximum":16777216,"minimum":1,"type":"integer"},"contentType":{"maxLength":255,"type":"string"},"download":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"method":{"const":"GET"},"operation":{"const":"get-review-context"},"path":{"type":"string"}},"required":["method","operation","accessProfile","path"],"type":"object"},"id":{"format":"uuid","type":"string"},"sha256":{"pattern":"^[0-9a-f]{64}$","type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["id","sha256","contentType","byteSize","verificationStatus"],"type":"object"},"maxItems":32,"type":"array"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["documents","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state"],"type":"object"},"maxItems":50,"type":"array"},"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"fields":{"type":"object"},"reference":{"type":"string"}},"required":["reference","contract","fields"],"type":"object"},"effectDigest":{"type":"string"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["proposal-reviewer"]}},"/v1/proposals/{proposal_id}/review-status":{"get":{"operationId":"proposals.get-review-status","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["casework-review-status","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Request the institution's optional applicant-visible progress code. The code is returned only when the selected caller-owned grant enables readableReviewProgress.","in":"query","name":"include","required":false,"schema":{"const":"progress"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"authority":{"type":"string"},"context":{"additionalProperties":false,"properties":{"contract":{"additionalProperties":false,"properties":{"id":{"maxLength":2048,"pattern":"^urn:registry:breg:review-context:","type":"string"},"revision":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"schemaDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"}},"required":["id","revision","schemaDigest"],"type":"object"},"reference":{"type":"string"}},"required":["reference"],"type":"object"},"effectDigest":{"type":"string"},"handoff":{"additionalProperties":false,"properties":{"reason":{"enum":["remote-refused","producer-identity-mismatch","review-acceptance-changed","review-policy-changed","submission-recovery-expired","operator-closed","unspecified"]},"state":{"enum":["pending","accepted","failed","withdrawn"]}},"required":["state"],"type":"object"},"id":{"format":"uuid","type":"string"},"policy":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"type":"string"},"version":{"type":"string"}},"required":["id","version","digest"],"type":"object"},"progressCode":{"description":"Institution-defined applicant-visible progress. Absent when the institution conceals the current stage, progress was not requested or granted, the provider is unavailable, or the accepted review round is no longer live.","maxLength":64,"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"requestId":{"format":"uuid","type":"string"},"result":{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},"reviewable":{"type":"boolean"},"revision":{"minimum":1,"type":"integer"},"subject":{"additionalProperties":false,"properties":{"digest":{"type":"string"},"id":{"format":"uuid","type":"string"},"source":{"type":"string"},"subjectType":{"const":"proposal"},"version":{"type":"string"}},"required":["source","subjectType","id","version","digest"],"type":"object"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["id","actionId","actionRevision","submissionVersion","revision","effectDigest","subject","context","reviewable"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["casework-review-status","facility-correction-author"]}},"/v1/proposals/{proposal_id}/revise":{"post":{"operationId":"proposals.revise","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"anyOf":[{"$id":"urn:breg:action:correct-address:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityId":{"format":"uuid","type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"correct-address","x-registry-requiredConditionKeys":[]},{"$id":"urn:breg:action:deactivate-facility:invoke-input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"facilityId":{"format":"uuid","type":"string"}},"required":[],"type":"object"}},"required":["input"],"type":"object","x-registry-action":"deactivate-facility","x-registry-requiredConditionKeys":[]},{"additionalProperties":false,"type":"object"}]}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/proposals/{proposal_id}/submissions/{submission_version}":{"get":{"operationId":"proposals.get-submission","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-applier","facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"path","name":"submission_version","required":true,"schema":{"maximum":4294967295,"minimum":1,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"application":{"anyOf":[{"additionalProperties":false,"dependentRequired":{"appliedAt":["appliedBy"],"appliedBy":["appliedAt"]},"properties":{"applicationId":{"format":"uuid","type":"string"},"appliedAt":{"description":"Application time, present with appliedBy only when the selected profile holds get-application-actor.","format":"date-time","type":"string"},"appliedBy":{"description":"Keyed actor pseudonym, present with appliedAt only when the selected profile holds get-application-actor.","pattern":"^hmac-sha256:[0-9a-f]{64}$","type":"string"},"state":{"const":"applied"}},"required":["state","applicationId"],"type":"object"},{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},{"type":"null"}]},"current":{"type":"boolean"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"review":{"anyOf":[{"additionalProperties":false,"properties":{"availableUntil":{"format":"date-time","type":"string"},"completedAt":{"format":"date-time","type":"string"},"resultId":{"format":"uuid","type":"string"},"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]}},"required":["state"],"type":"object"},{"type":"null"}]},"submissionVersion":{"maximum":4294967295,"minimum":1,"type":"integer"}},"required":["id","actionId","submissionVersion","current","effectDigest","review","application"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"proposal.submission-expired":{"value":{"code":"proposal.submission-expired","detail":"The review result and application receipt of the submission are no longer retained.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["proposal.submission-expired"]}},"type":"object"}]}}},"description":"The submission's review result and application receipt are no longer retained","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-applier","facility-correction-author"]}},"/v1/proposals/{proposal_id}/submit":{"post":{"operationId":"proposals.submit","parameters":[{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"enum":["facility-correction-author"],"maxLength":128,"type":"string"}},{"in":"path","name":"proposal_id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"If-Match","required":true,"schema":{"type":"string"}},{"in":"header","name":"Idempotency-Key","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"type":"object"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"actionId":{"type":"string"},"actionRevision":{"type":"string"},"application":{"additionalProperties":false,"properties":{"applicationId":{"format":"uuid","type":"string"},"effectDigest":{"pattern":"^sha256:[0-9a-f]{64}$","type":"string"},"resultLinks":{"items":{"additionalProperties":false,"properties":{"recordId":{"format":"uuid","type":"string"},"recordType":{"type":"string"},"revision":{"minimum":1,"type":"integer"}},"required":["recordType","recordId","revision"],"type":"object"},"maxItems":16,"type":"array"},"submissionVersion":{"minimum":1,"type":"integer"}},"required":["applicationId","submissionVersion","effectDigest","resultLinks"],"type":"object"},"applicationStatus":{"additionalProperties":false,"properties":{"automaticRetry":{"additionalProperties":false,"properties":{"attempts":{"maximum":1000,"minimum":0,"type":"integer"},"maximumAttempts":{"maximum":1000,"minimum":1,"type":"integer"},"scheduled":{"type":"boolean"}},"required":["scheduled","attempts","maximumAttempts"],"type":"object"},"mode":{"enum":["automatic","manual"]},"reason":{"enum":["package-changed","dependency-outage","lease-expired","application-refused","attempts-exhausted"]},"recovery":{"enum":["retry","rebase","revise","correct-input"]},"state":{"enum":["awaiting-review","pending","applying","blocked","applied","cancelled","rejected"]}},"required":["state","mode"],"type":"object"},"asks":{"items":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"additions":{"items":{"format":"uuid","type":"string"},"maxItems":32,"type":"array","uniqueItems":true},"answeredAt":{"format":"date-time","type":"string"},"text":{"maxLength":2000,"minLength":1,"type":"string"}},"required":["additions","answeredAt"],"type":"object"},"askedAt":{"format":"date-time","type":"string"},"dueAt":{"format":"date-time","type":"string"},"id":{"format":"uuid","type":"string"},"links":{"additionalProperties":false,"properties":{"answer":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"const":"POST"},"operation":{"const":"answer"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation","ifMatch","availability"],"type":"object"}},"type":"object"},"state":{"enum":["open","answered","expired","closed"]},"text":{"maxLength":2000,"minLength":1,"type":"string"},"wants":{"items":{"additionalProperties":false,"properties":{"kind":{"enum":["answer","document"]}},"required":["kind"],"type":"object"},"maxItems":8,"type":"array","uniqueItems":true}},"required":["id","text","wants","askedAt","state","links"],"type":"object"},"maxItems":50,"type":"array"},"attachments":{"additionalProperties":{"additionalProperties":false,"properties":{"classification":{"enum":["public","internal","restricted"]},"contentTypes":{"items":{"type":"string"},"maxItems":16,"minItems":1,"type":"array","uniqueItems":true},"id":{"type":"string"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","PATCH","DELETE"]},"operation":{"enum":["download","upload","remove"]},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"maximumBytes":{"maximum":16777216,"minimum":1,"type":"integer"},"required":{"type":"boolean"},"value":{"additionalProperties":false,"properties":{"byteSize":{"minimum":1,"type":"integer"},"contentType":{"type":"string"},"sha256":{"pattern":"^[a-f0-9]{64}$","type":"string"},"submissionVersion":{"minimum":0,"type":"integer"},"uploadedAt":{"type":"string"},"verificationStatus":{"enum":["notRequired","pending","approved","rejected"]}},"required":["submissionVersion","sha256","contentType","byteSize","verificationStatus"],"type":"object"}},"required":["id","required","maximumBytes","contentTypes","classification","links"],"type":"object"},"maxProperties":8,"type":"object"},"blockedReason":{"enum":["package-changed"]},"createdAt":{"format":"date-time","type":"string"},"decision":{"additionalProperties":false,"properties":{"decidedAt":{"format":"date-time","type":"string"},"publicReason":{"minLength":1,"pattern":"^[^\\u0000-\\u001F\\u007F-\\u009F]*[^\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000][^\\u0000-\\u001F\\u007F-\\u009F]*$","type":"string","x-maximum-utf8-bytes":2000},"status":{"enum":["approved","rejected","changes-requested","answered"]}},"required":["status","decidedAt"],"type":"object"},"effectDigest":{"type":"string"},"handoffRefusal":{"additionalProperties":false,"properties":{"code":{"enum":["review.initiator-required","review.initiator-excluded","review.policy-mismatch","review.refused"]}},"required":["code"],"type":"object"},"id":{"format":"uuid","type":"string"},"input":{"type":"object"},"links":{"additionalProperties":{"additionalProperties":false,"properties":{"accessProfile":{"type":"string"},"availability":{"additionalProperties":false,"if":{"properties":{"available":{"const":false}}},"properties":{"available":{"type":"boolean"},"observedRevision":{"minimum":1,"type":"integer"},"reason":{"enum":["pending-review","review-rejected","review-changes-requested","review-ended","stale-revision","package-changed","dependency-outage","invalid-input","already-applied","limit-reached","application-pending","attachment-required","attachment-pending","ask-answered","ask-closed","ask-due-passed"]},"recovery":{"enum":["refresh","revise","retry","rebase","correct-input","receipt-only"]}},"required":["available","observedRevision"],"then":{"required":["reason","recovery"]},"type":"object"},"ifMatch":{"type":"string"},"method":{"enum":["GET","POST"]},"operation":{"type":"string"},"path":{"type":"string"}},"required":["method","path","accessProfile","operation"],"type":"object"},"type":"object"},"revision":{"minimum":1,"type":"integer"},"state":{"enum":["draft","submitted","applied","cancelled","rejected"]},"status":{"enum":["draft","awaiting-party","in-review","approved","processing","applied","rejected","cancelled"]},"submissionVersion":{"minimum":0,"type":"integer"},"title":{"maxLength":1024,"type":"string"},"turn":{"enum":["party","official","nobody"]}},"required":["id","actionId","actionRevision","submissionVersion","revision","state","turn","links"],"type":"object"}}},"description":"Authorized Proposal operation"},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["access-profile.ambiguous","request.invalid"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["authentication.refused"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["profile.not-authorized"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["resource.not-found"]}},"type":"object"}]}}},"description":"Resource unavailable to this caller","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"attachment.verification-pending":{"value":{"code":"attachment.verification-pending","detail":"The attachment is awaiting verification. Refresh the Proposal before submitting.","fieldPath":"/attachments/supporting-document","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}},"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}},"proposal.rejected":{"value":{"code":"proposal.rejected","detail":"The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["attachment.verification-pending","idempotency.key-reused","mutation.conflict","proposal.rejected"]}},"type":"object"}]}}},"description":"The Proposal was rejected, or the idempotency key was reused with a different request","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["idempotency.expired"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"action.guard-failed":{"value":{"code":"action.guard-failed","detail":"The action guard was not satisfied.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}},"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.guard-failed","precondition.failed"]}},"type":"object"}]}}},"description":"Observed authority or lifecycle condition changed, or a Record revision guard failed (`precondition.failed`); a failed field commit guard answers `action.guard-failed` when the selected profile can read it","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["unsupported.media-type"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"422":{"content":{"application/problem+json":{"examples":{"action.refused/invalid-postal-code":{"value":{"code":"action.refused","detail":"Postal code is invalid","refusalCode":"invalid-postal-code","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/refused"}},"attachment.verification-rejected":{"value":{"code":"attachment.verification-rejected","detail":"The attachment was rejected by verification. Replace or remove the file before submitting.","fieldPath":"/attachments/supporting-document","status":422,"title":"Unprocessable Entity","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.refused","attachment.verification-rejected"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["precondition.required"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"500":{"content":{"application/problem+json":{"examples":{"action.handler-failed":{"value":{"code":"action.handler-failed","detail":"The action handler could not produce an accepted result.","status":500,"title":"Internal Server Error","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/action/handler-failed"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["action.handler-failed"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}},"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["service.unavailable","source.unavailable"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"allOf":[{"$ref":"#/components/schemas/Problem"},{"properties":{"code":{"enum":["request.timeout"]}},"type":"object"}]}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"x-registry-accessProfiles":["facility-correction-author"]}},"/v1/records/directory-entries":{"get":{"operationId":"records.directory-entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"directory-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"directory-editor","requiredFilters":[],"selectableProperties":["email","jurisdiction","name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.directory-entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/directory-entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"create","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/directory-entries/{record_id}":{"get":{"operationId":"records.directory-entry.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"email":{"maxLength":254,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":160,"minLength":1,"type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"get","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.directory-entry.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/directory-entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"directory-entry"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["directory-editor"],"x-registry-operation":"patch","x-registry-recordType":"directory-entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"directory-entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities":{"get":{"operationId":"records.facility.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["addressLine","city","facilityCode","jurisdiction","name","postalCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facilities/{record_id}":{"get":{"operationId":"records.facility.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"addressLine":{"maxLength":240,"minLength":1,"type":"string"},"city":{"maxLength":120,"minLength":1,"type":"string"},"facilityCode":{"maxLength":64,"minLength":1,"type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"name":{"maxLength":200,"minLength":1,"type":"string"},"postalCode":{"maxLength":24,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"facility-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","proposal-reviewer"],"x-registry-operation":"get","x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/facilities/{record_id}/operators":{"get":{"operationId":"records.facility.path.operators","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments":{"get":{"operationId":"records.facility-assignment.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[{"operators":["equals","in","is-null","is-not-null"],"property":"facility"},{"operators":["equals","in","is-null","is-not-null"],"property":"operator"}],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["facility","jurisdiction","operator"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/v1/records/facility-assignments/{record_id}":{"get":{"operationId":"records.facility-assignment.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"facility":{"format":"uuid","type":"string"},"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operator":{"format":"uuid","type":"string"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"facility-assignment"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader"],"x-registry-operation":"get","x-registry-recordType":"facility-assignment","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"facility-assignment","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators":{"get":{"operationId":"records.operator.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"facility-reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"facility-reader","requiredFilters":[],"selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null},"operator-editor":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"operator-editor","requiredFilters":[],"selectableProperties":["jurisdiction","operatorCode","status"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.operator.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/operator-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"create","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/records/operators/{record_id}":{"get":{"operationId":"records.operator.get","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"jurisdiction":{"maxLength":40,"minLength":1,"type":"string"},"operatorCode":{"maxLength":64,"minLength":1,"type":"string"},"status":{"enum":["active","inactive"],"type":"string","x-registry-vocabulary":"operator-status"}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["facility-reader","operator-editor"],"x-registry-operation":"get","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"},"patch":{"operationId":"records.operator.patch","parameters":[{"description":"Canonical record UUID.","in":"path","name":"record_id","required":true,"schema":{"format":"uuid","type":"string"}},{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Strong Registry ETag for the currently visible record representation.","in":"header","name":"If-Match","required":true,"schema":{"maxLength":256,"minLength":6,"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json-patch+json":{"schema":{"items":{"additionalProperties":false,"else":{"required":["value"]},"if":{"properties":{"op":{"const":"remove"}}},"properties":{"op":{"enum":["add","replace","remove","test"],"type":"string"},"path":{"type":"string"},"value":true},"required":["op","path"],"then":{"not":{"required":["value"]}},"type":"object"},"maxItems":128,"minItems":1,"type":"array"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/operator"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"facility-registry"},"recordTypeId":{"const":"operator"},"registryId":{"const":"facility-registry"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record patched","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}},"write.outside-boundary":{"value":{"code":"write.outside-boundary","detail":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"412":{"content":{"application/problem+json":{"examples":{"precondition.failed":{"value":{"code":"precondition.failed","detail":"The mutation precondition failed.","status":412,"title":"Precondition Failed","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"428":{"content":{"application/problem+json":{"examples":{"precondition.required":{"value":{"code":"precondition.required","detail":"The mutation precondition is required.","status":428,"title":"Precondition Required","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["operator-editor"],"x-registry-operation":"patch","x-registry-recordType":"operator","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"operator","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/products/breg/scripts/test_validate_product.py b/products/breg/scripts/test_validate_product.py index f7610da015..d68b68b432 100644 --- a/products/breg/scripts/test_validate_product.py +++ b/products/breg/scripts/test_validate_product.py @@ -74,7 +74,7 @@ def test_security_range_and_negative_ids_are_closed(self) -> None: ) extension_rows = matrix["invariants"][24:] self.assertEqual( - [f"BREG-NEG-{index:02d}" for index in range(25, 246) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 247) if index not in {61, 62}], [invariant["negativeId"] for invariant in extension_rows], ) for invariant in extension_rows: diff --git a/products/breg/scripts/validate_product.py b/products/breg/scripts/validate_product.py index 0082f48510..6d3e4979cc 100644 --- a/products/breg/scripts/validate_product.py +++ b/products/breg/scripts/validate_product.py @@ -31,7 +31,7 @@ CONTRACT_STATES = {"enforced", "partial", "planned"} V1_REQUIREMENT_IDS = tuple(f"BREG-V1-{index:02d}" for index in range(1, 45)) ACCEPTANCE_JOURNEY_IDS = tuple(f"BREG-J{index:02d}" for index in range(1, 25)) -SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 246) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 247) if index not in {61, 62}) ACCEPTANCE_FIXTURES = { "BREG-J01": ("asset-site-placement", "acceptance/asset-site-placement"), "BREG-J02": ("asset-site-placement", "acceptance/asset-site-placement"), diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index 365cf965af..6c383e7efb 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + - BREAKING: Generated Casework clients use lower-camel-case `path` keys. Replace `policy_id`, `request_id`, `ask_id`, `task_id`, `grant_id`, `event_id`, `team_id`, and `absence_id` with `policyId`, `requestId`, `askId`, `taskId`, diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index cd876287d2..af246eea8d 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,11 +2,17 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + - BREAKING: Generated Coordinator clients use `workflowId`, `triggerId`, and `runId` in `path` arguments. Replace `workflow`, `trigger`, and `run` when calling the generated methods. Operation names and concrete HTTP URLs stay the same. - 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. +- Publish the `ghcr.io/registrystack/coordinator` container image and its candidate-bound security evidence from v0.52.0. ## 0.49.0 - 2026-12-01 diff --git a/products/coordinator/README.md b/products/coordinator/README.md index a1674b33b0..ec48f209b9 100644 --- a/products/coordinator/README.md +++ b/products/coordinator/README.md @@ -16,7 +16,7 @@ is version 7, with no in-place migration from earlier layouts. Build the Coordinator service, operator CLI, client, and client bindings from source using the [deployment guide](https://docs.registrystack.org/operate/coordinator/#install-and-package) and the client crate instructions. Release packaging includes the `coordinator` and `coordinatorctl` binaries and their installer, and the `coordinator` namespace of -the unified Node.js and Python client packages, from v0.44.0. The container image remains held. +the unified Node.js and Python client packages, from v0.44.0. The container image joins numbered releases from v0.52.0. The [archive-based tutorial](https://docs.registrystack.org/dev/tutorials/review-an-application-and-send-a-notice/) uses those release assets. diff --git a/products/discovery/CHANGELOG.md b/products/discovery/CHANGELOG.md index e0b0eaf77c..577deb789a 100644 --- a/products/discovery/CHANGELOG.md +++ b/products/discovery/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- BREAKING: The Rust client's `DiscoveryClientError::UnrecognizedProblem` keeps the problem `type` and the optional `code`, and the Node (`problemType`, `code`) and Python (`problem_type`, `code`) errors carry them. Migration: Match the Rust variant with `{ status, .. }`. +- The Rust, Node, Python, and TypeScript Discovery clients classify a problem by its status, `type`, and `code`, and no longer refuse a known problem whose `title` was reworded. +- A known Discovery problem type that carries a newer code is reported as an unrecognized problem with its `type` and `code` instead of a protocol failure, in the Rust, Node, Python, and TypeScript clients. A code that names a different known problem is still a protocol failure. +- The Node and Python Discovery errors set `code` for a known problem too, from `DiscoveryProblem::code()` in Rust. +- Rust, Node, and Python Discovery errors retain the correlated trace identifier for unrecognized problems when both the body and response header provide it. +- Discovery clients require a string Problem title and classify the response by status, type, and code. Native diagnostics redact unfamiliar identifiers, which callers can still read as structured fields. +- Discovery response records and persisted selection records require named objects. Persisted matched capabilities accept only kind and id. + ## 0.49.0 - 2026-12-01 - Add a credential-free TypeScript client for the public Discovery API. diff --git a/products/documents/CHANGELOG.md b/products/documents/CHANGELOG.md index 07b967a627..7888206b96 100644 --- a/products/documents/CHANGELOG.md +++ b/products/documents/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + - BREAKING: For non-loopback HTTP observer hooks, the runtime requires explicit private-network transport. Runtime load checks hook transport before resolving protected material. An undeclared private HTTP hook reports `platform.destination.private-network-not-declared` at its URL. Migration: Use HTTPS or loopback HTTP, or set `transport: private-network-plaintext` and supply allowed private CIDRs for the observer destination. - BREAKING: A valid token whose caller is not admitted (its actor kind or its client) answers HTTP 403 `profile.not-authorized` instead of HTTP 401 `authentication.refused`, an exchanged token without declared assertion authority answers HTTP 401 `authentication.refused` with a `Bearer` challenge instead of HTTP 403 `profile.not-authorized`, and configuration-refused issuer key sources (`KeySourceUnavailable`) answer HTTP 503 `service.unavailable` alongside live key-source outages. Migration: Treat HTTP 403 on valid tokens as caller admission failure, HTTP 401 on undeclared token exchanges as credential refusal, and inspect issuer key-source configuration alongside network availability when diagnosing HTTP 503 key-source refusals. diff --git a/products/evidence/generated/evidence-definitions-v1.schema.json b/products/evidence/generated/evidence-definitions-v1.schema.json index 83ca82af51..f64ea791b6 100644 --- a/products/evidence/generated/evidence-definitions-v1.schema.json +++ b/products/evidence/generated/evidence-definitions-v1.schema.json @@ -1,5 +1,5 @@ { - "$comment": "The authenticated response contains only complete request shapes that match exactly one configured authority path. It never exposes source plans, scripts, credentials, requester tags, authority-profile identifiers, selector values, codelist values, codelist paths, internal constraints, or unrelated definitions.", + "$comment": "The authenticated response contains only complete request shapes that match exactly one configured authority path. It never exposes source plans, scripts, credentials, requester tags, authority-profile identifiers, selector values, codelist values, codelist paths, internal constraints, or unrelated definitions. This closed schema describes exactly what one release emits. A later minor release may add members, so a consumer ignores members it does not know instead of rejecting the response.", "$defs": { "alternative": { "additionalProperties": false, diff --git a/products/evidence/generated/evidence-request-batch-response-v1.schema.json b/products/evidence/generated/evidence-request-batch-response-v1.schema.json index 68d53d5f6f..ee161c9aa3 100644 --- a/products/evidence/generated/evidence-request-batch-response-v1.schema.json +++ b/products/evidence/generated/evidence-request-batch-response-v1.schema.json @@ -1,5 +1,5 @@ { - "$comment": "Results are positional and one-for-one with the request. Available members are ordinary signed flattened JWS responses. Singular unavailable conditions become evidence-not-available. Mixed and all-unavailable envelopes return HTTP 200. Every other failure aborts the outer request, and a response above 1048576 serialized bytes is never released.", + "$comment": "Results are positional and one-for-one with the request. Available members are ordinary signed flattened JWS responses. Singular unavailable conditions become evidence-not-available. Mixed and all-unavailable envelopes return HTTP 200. Every other failure aborts the outer request, and a response above 1048576 serialized bytes is never released. This closed schema describes exactly what one release emits. A later minor release may add members, so a consumer ignores members it does not know instead of rejecting the response.", "$defs": { "evidence-result": { "additionalProperties": false, diff --git a/products/evidence/generated/jwks-v1.schema.json b/products/evidence/generated/jwks-v1.schema.json index 0fb7847f15..fdb5ed1534 100644 --- a/products/evidence/generated/jwks-v1.schema.json +++ b/products/evidence/generated/jwks-v1.schema.json @@ -1,5 +1,5 @@ { - "$comment": "Only the governed active and published non-revoked P-256 keys are returned. Each kid is the key's RFC 7638 SHA-256 thumbprint. Discovery is not a trust anchor; verifiers pin the governed provider and JWKS location. Only the active key carries the optional x5c member, when the deployment configures a certificate chain; the chain does not change what a verifier pins.", + "$comment": "Only the governed active and published non-revoked P-256 keys are returned. Each kid is the key's RFC 7638 SHA-256 thumbprint. Discovery is not a trust anchor; verifiers pin the governed provider and JWKS location. Only the active key carries the optional x5c member, when the deployment configures a certificate chain; the chain does not change what a verifier pins. This closed schema describes exactly what one release emits. A later minor release may add members, so a consumer ignores members it does not know instead of rejecting the response.", "$defs": { "p256-public-jwk": { "additionalProperties": false, diff --git a/products/evidence/generated/problem-v1.schema.json b/products/evidence/generated/problem-v1.schema.json index 3464d62997..cbfc8cc723 100644 --- a/products/evidence/generated/problem-v1.schema.json +++ b/products/evidence/generated/problem-v1.schema.json @@ -1,5 +1,5 @@ { - "$comment": "Problem members are a closed safe shape. No request, authority, source, script, supported-value, subject-binding, candidate, or credential detail is returned.", + "$comment": "Problem members are a closed safe shape. No request, authority, source, script, supported-value, subject-binding, candidate, or credential detail is returned. This closed schema describes exactly what one release emits. A later minor release may add members, so a consumer ignores members it does not know instead of rejecting the response.", "$id": "https://registrystack.org/schemas/evidence/problem-v1.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index 4d4ec60dc2..e09acce1f6 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -217,9 +217,34 @@ "reason": "The unknown BReg request.plan_refused Problem is a synthetic client decoding fixture, not a current runtime Problem inventory entry." }, { - "glob": "crates/registry-discovery-client-node/__test__/surface.test.js", + "path": "crates/registry-casework-client/tests/fixtures/direct-response-additions.json", + "uri": "https://id.registrystack.org/problems/registry-casework/review/future-safe", "classification": "fixture", - "reason": "The unknown future Registry Discovery Problem is a synthetic client decoding fixture outside the active resolver catalog by design." + "reason": "This synthetic Casework Problem tests whether the direct client preserves an unknown but well-formed Problem type." + }, + { + "path": "crates/registry-casework-client/tests/fixtures/problem-responses.json", + "uri": "https://id.registrystack.org/problems/registry-casework/review/future-safe", + "classification": "fixture", + "reason": "This synthetic Casework Problem exercises unknown Problem handling across status codes in direct and delegated clients." + }, + { + "path": "crates/registry-casework-client/tests/fixtures/problem-responses.json", + "uri": "https://id.registrystack.org/problems/registry-casework/review/unrelated", + "classification": "fixture", + "reason": "This synthetic Casework Problem type intentionally disagrees with the response code to test rejection by direct and delegated clients." + }, + { + "path": "crates/registry-casework-client/tests/http_boundary.rs", + "uri": "https://id.registrystack.org/problems/registry-casework/review/other", + "classification": "fixture", + "reason": "This synthetic Casework Problem type replaces the fixture's matching type to test protocol rejection at the direct HTTP boundary." + }, + { + "path": "crates/registry-discovery-client/tests/fixtures/http-responses.json", + "uri": "https://id.registrystack.org/problems/registry-discovery/future-conflict", + "classification": "fixture", + "reason": "The shared Discovery SDK response fixture represents a future Problem outside the active resolver catalog." }, { "glob": "crates/registry-discovery-client/src/client.rs", @@ -227,10 +252,82 @@ "reason": "The unknown future Registry Discovery Problem is a synthetic client decoding fixture outside the active resolver catalog by design." }, { - "path": "crates/registry-evidence-client-node/__test__/errors.test.js", + "path": "clients/typescript/tests/discovery.test.ts", + "uri": "https://id.registrystack.org/problems/registry-discovery/future-problem", + "classification": "fixture", + "reason": "This synthetic Discovery Problem lets tests exercise code validation for an unrecognised type." + }, + { + "path": "crates/registry-discovery-client/src/error.rs", + "uri": "https://id.registrystack.org/problems/registry-discovery/future", + "classification": "fixture", + "reason": "This synthetic Discovery Problem lets tests check that errors for unrecognised types have bounded, value-free display." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/evidence/future-rate-limit", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/evidence/future-unavailable", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/future--request/conflict", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/future-request-/conflict", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/platform/task/development-assertion", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/request/future--conflict", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", "uri": "https://id.registrystack.org/problems/registry-evidence/request/future-conflict", "classification": "fixture", - "reason": "This synthetic future-conflict Problem is a negative client-decoding fixture, not an active Evidence Problem." + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/request/future-conflict-", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/request/future-family/conflict", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/request/future_conflict", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." + }, + { + "path": "products/platform/fixtures/client-response-tolerance/evidence.json", + "uri": "https://id.registrystack.org/problems/registry-evidence/service/future-unavailable", + "classification": "fixture", + "reason": "Synthetic Problem type used to test Evidence client response tolerance." }, { "glob": "crates/registry-manifest-core/tests/**", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 5d0404501e..dc0e6b171e 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5706,7 +5706,7 @@ "description": "Base Registry Engine portable Action contract export schema, reproduced from the canonical compiled project.", "source": { "path": "crates/registry-breg/src/artifacts.rs", - "sha256": "586b4e3da54bad07e5b750e67ef9e5a872a454f779de5ea6ca56692c798749ea" + "sha256": "c23555cfb9db5fb39dd6fe9271c670c78bc3a5082806dfb60c5b44ffe4fb6963" }, "artifact": { "path": "products/breg/generated/facility/generated/action-contracts.schema.json", @@ -6210,7 +6210,7 @@ "description": "Registry Coordinator runtime configuration JSON Schema.", "source": { "path": "crates/registry-coordinator/src/runtime.rs", - "sha256": "083365a7bbb3eeb12293cd7c665e52d5bef7444d54e4a5eca9e2ea378c5884c3" + "sha256": "e85019cebb84aa8c6b70fece94654bc98871f9efaf21805b41e26962f6a20d21" }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", @@ -6876,7 +6876,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": "69249d1cd4b43379aa5f4a7c15bddfe443650f49bdb7477c9f068a5468f4f22f" + "sha256": "3227f9b61266f2771d56ea63c8b6d6853b2f3d9c8c53a90fcc69c829d4f20a12" }, "artifact": { "path": "crates/registry-platform-provision/schema/provision-report.schema.json", @@ -6948,7 +6948,7 @@ "description": "rstack error report JSON Schema.", "source": { "path": "crates/registry-rstack/src/cli.rs", - "sha256": "0d9a9654fefbc7fb5ab8bce66129be190c984bfe31aa1e1ac550e62c96d36ffb" + "sha256": "553b66d3c5bbd9d72b09481e3ff469572f81cf9b4ef87945ca06ea2ad0e12a53" }, "artifact": { "path": "products/platform/schemas/rstack-dev-error.v1.schema.json", @@ -7038,7 +7038,7 @@ "description": "Registry Render project, label table, and runtime configuration JSON Schema.", "source": { "path": "crates/registry-render/src/schema.rs", - "sha256": "1ecb5e7d842e79f05a2419c3c8ee772d30ec8d6b75b510cb1f5e4dc263c04fd3" + "sha256": "0e9c23efaea52489f1757d21bfa31936b572d4ab99f6ed0c5e5dfb030a374354" }, "artifact": { "path": "products/render/schemas/labels.schema.json", @@ -7056,7 +7056,7 @@ "description": "Registry Render project, label table, and runtime configuration JSON Schema.", "source": { "path": "crates/registry-render/src/schema.rs", - "sha256": "1ecb5e7d842e79f05a2419c3c8ee772d30ec8d6b75b510cb1f5e4dc263c04fd3" + "sha256": "0e9c23efaea52489f1757d21bfa31936b572d4ab99f6ed0c5e5dfb030a374354" }, "artifact": { "path": "products/render/schemas/project.schema.json", @@ -7074,11 +7074,11 @@ "description": "Registry Render project, label table, and runtime configuration JSON Schema.", "source": { "path": "crates/registry-render/src/schema.rs", - "sha256": "1ecb5e7d842e79f05a2419c3c8ee772d30ec8d6b75b510cb1f5e4dc263c04fd3" + "sha256": "0e9c23efaea52489f1757d21bfa31936b572d4ab99f6ed0c5e5dfb030a374354" }, "artifact": { "path": "products/render/schemas/runtime.schema.json", - "sha256": "bee49b33f6ce372948d096d55424f59cfb65823d4e44a2fc5cd4561335aae77b", + "sha256": "dafaa6af320cc798dd0f62c1647381f0666c1e0ddfcc6d9f5b948a670d5caadd", "mediaType": "application/schema+json" } }, @@ -7096,7 +7096,7 @@ }, "artifact": { "path": "products/platform/generated/dev/dev.v1alpha1.schema.json", - "sha256": "a7d8da1e475b8e5ef80e4879a4144bb5b247912ec5315d475d80c3b726953114", + "sha256": "ee0cc81ceaa6fbc39784744789020fb17d06816626c0cdc89736485ba1a862e3", "mediaType": "application/schema+json" } }, diff --git a/products/messaging/CHANGELOG.md b/products/messaging/CHANGELOG.md index 85131a6832..b6fcb8137b 100644 --- a/products/messaging/CHANGELOG.md +++ b/products/messaging/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + - BREAKING: Generated Messaging clients use `messageId`, `providerId`, and `templateId` in `path` arguments. Replace `message_id`, `provider_id`, and `template_id`, and replace `version` with `templateVersion` on template diff --git a/products/messaging/scripts/check-role-assignment.sh b/products/messaging/scripts/check-role-assignment.sh new file mode 100755 index 0000000000..344bb8c430 --- /dev/null +++ b/products/messaging/scripts/check-role-assignment.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# The native Messaging role-assignment check behind `rstack dev check`. It runs +# the registry-rstack-dev test that reads the starter package's access +# profiles through a matching messagingctl and requires the operations profile +# to keep its exact scopes without an actor selector. The default test run +# ignores that test because it needs the built binary. +# +# The check fails unless exactly that one test runs and passes, so a skipped, +# renamed or filtered-out test cannot pass silently. +# +# MESSAGINGCTL_BIN names the messagingctl built from this tree, as an absolute +# path. CARGO, when set, names the cargo to run. +set -euo pipefail + +test_name=dev_facts::tests::offline_messaging_native_facts_retain_actorless_owner_profile + +fail() { + printf 'check-role-assignment: %s\n' "$1" >&2 + exit 1 +} + +messagingctl=${MESSAGINGCTL_BIN:-} +if [[ "$messagingctl" != /* || ! -f "$messagingctl" || ! -x "$messagingctl" ]]; then + fail "MESSAGINGCTL_BIN must name the messagingctl built from this tree by absolute path (got '${messagingctl}')" +fi + +status=0 +output=$( + RSTACK_MESSAGINGCTL_BIN="$messagingctl" "${CARGO:-cargo}" test --locked -p registry-rstack-dev --lib \ + -- --ignored --exact "$test_name" 2>&1 | tee /dev/stderr +) || status=$? + +if ((status != 0)); then + fail "the role-assignment test run failed (exit ${status})" +fi +passed=$(grep -cx "test ${test_name} \.\.\. ok" <<<"$output" || true) +summaries=$(grep -c '^test result: ok\. 1 passed; 0 failed; 0 ignored;' <<<"$output" || true) +if [[ "$passed" != 1 || "$summaries" != 1 ]]; then + fail "expected exactly one passing run of ${test_name}; it was skipped, filtered out or run more than once" +fi +printf 'check-role-assignment: %s passed\n' "$test_name" >&2 diff --git a/products/messaging/scripts/test-check-role-assignment.sh b/products/messaging/scripts/test-check-role-assignment.sh new file mode 100755 index 0000000000..ca49c8369c --- /dev/null +++ b/products/messaging/scripts/test-check-role-assignment.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Self-test of `check-role-assignment.sh`. A stand-in cargo prints the output +# of one test run at a time, so this proves without a build that the check +# passes only on exactly one passing run of the named test, and that it hands +# the test the messagingctl it was given. +set -euo pipefail + +CDPATH='' +scripts_directory=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +check="$scripts_directory/check-role-assignment.sh" +sandbox=$(mktemp -d) +stand_in="$sandbox/cargo" +messagingctl="$sandbox/messagingctl" +arguments="$sandbox/arguments" +cleanup() { + rm -f "$stand_in" "$messagingctl" "$arguments" + rmdir "$sandbox" +} +trap cleanup EXIT + +test_name=dev_facts::tests::offline_messaging_native_facts_retain_actorless_owner_profile +printf '#!/bin/sh\nexit 0\n' >"$messagingctl" +chmod +x "$messagingctl" + +# The stand-in records its arguments and the binary it was handed, then prints +# STAND_IN_OUTPUT and exits with STAND_IN_EXIT. +cat >"$stand_in" <<'EOF' +#!/usr/bin/env bash +printf '%s\n' "$@" "RSTACK_MESSAGINGCTL_BIN=${RSTACK_MESSAGINGCTL_BIN:-}" >"$STAND_IN_ARGUMENTS" +printf '%b' "$STAND_IN_OUTPUT" +exit "${STAND_IN_EXIT:-0}" +EOF +chmod +x "$stand_in" + +failures=0 + +run_check() { + local output=$1 exit_status=$2 binary=$3 + CARGO="$stand_in" MESSAGINGCTL_BIN="$binary" STAND_IN_ARGUMENTS="$arguments" \ + STAND_IN_OUTPUT="$output" STAND_IN_EXIT="$exit_status" "$check" >/dev/null 2>&1 +} + +expect() { + local want=$1 label=$2 output=$3 exit_status=${4:-0} binary=${5-$messagingctl} + local got=pass + run_check "$output" "$exit_status" "$binary" || got=fail + if [[ "$got" == "$want" ]]; then + printf 'ok: %s\n' "$label" + else + printf 'FAIL: %s (expected %s, got %s)\n' "$label" "$want" "$got" >&2 + failures=$((failures + 1)) + fi +} + +one_pass="running 1 test\ntest ${test_name} ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 211 filtered out\n" + +expect pass "one passing run of the named test" "$one_pass" +expect fail "no test ran" "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 212 filtered out\n" +expect fail "the test was ignored" "running 1 test\ntest ${test_name} ... ignored\n\ntest result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 211 filtered out\n" +expect fail "the test failed" "running 1 test\ntest ${test_name} ... FAILED\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 211 filtered out\n" 101 +expect fail "cargo failed after printing a pass" "$one_pass" 101 +expect fail "another test passed instead" "running 1 test\ntest dev_facts::tests::another ... ok\n\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 211 filtered out\n" +expect fail "two test binaries each ran it" "${one_pass}${one_pass}" +expect fail "no messagingctl was given" "$one_pass" 0 "" +expect fail "a relative messagingctl" "$one_pass" 0 "target/debug/messagingctl" +expect fail "a missing messagingctl" "$one_pass" 0 "$sandbox/missing" + +run_check "$one_pass" 0 "$messagingctl" +expected_arguments=$(printf '%s\n' test --locked -p registry-rstack-dev --lib -- --ignored --exact "$test_name" "RSTACK_MESSAGINGCTL_BIN=$messagingctl") +if [[ "$(cat "$arguments")" == "$expected_arguments" ]]; then + printf 'ok: runs the one ignored test exactly, with the messagingctl it was given\n' +else + printf 'FAIL: the test command was:\n%s\n' "$(cat "$arguments")" >&2 + failures=$((failures + 1)) +fi + +if ((failures > 0)); then + printf '%d role-assignment check case(s) failed\n' "$failures" >&2 + exit 1 +fi +printf 'all role-assignment check cases passed\n' diff --git a/products/messaging/scripts/test-dev.sh b/products/messaging/scripts/test-dev.sh index 35988c702d..8dcceed00d 100755 --- a/products/messaging/scripts/test-dev.sh +++ b/products/messaging/scripts/test-dev.sh @@ -64,13 +64,27 @@ if [[ "$delivered" != 1 ]]; then fi dev_log "Mailpit holds 1 message" -callbacks=$(curl --silent --show-error --fail-with-body "$dev_metrics" | - python3 -c 'import sys +# The callback commits the delivery status before recording its metric. +deadline=$((SECONDS + settle_seconds)) +callbacks= +while :; do + remaining=$((deadline - SECONDS)) + if ((remaining <= 0)); then + break + fi + callbacks=$(curl --silent --show-error --fail-with-body --max-time "$remaining" "$dev_metrics" | + python3 -c 'import sys for line in sys.stdin: if line.startswith("messaging_provider_callbacks_total{outcome=\"applied\"}"): print(line.split()[-1])') + if [[ "$callbacks" == 1 ]]; then + break + fi + sleep 0.5 +done if [[ "$callbacks" != 1 ]]; then - printf 'test-dev: %s signed callbacks were applied, expected 1\n' "${callbacks:-no}" >&2 + printf 'test-dev: after %s seconds, observed %s applied signed callbacks, expected exactly 1\n' \ + "$settle_seconds" "${callbacks:-no count for}" >&2 exit 1 fi dev_log "1 signed delivery callback applied" diff --git a/products/messaging/scripts/test_dev_callback_metric.py b/products/messaging/scripts/test_dev_callback_metric.py new file mode 100644 index 0000000000..a59ca7b6a0 --- /dev/null +++ b/products/messaging/scripts/test_dev_callback_metric.py @@ -0,0 +1,73 @@ +"""Exercise the delivery check with scripted responses from the dev session.""" + +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).with_name("test-dev.sh") +SESSION = r"""dev_prepare() { dev_project=fixture; } +dev_start() { + dev_api=http://api + dev_mailpit=http://mailpit + dev_metrics=http://metrics +} +dev_stop() { :; } +dev_log() { printf '%s\n' "$1"; } +dev_header() { printf 'header-file\n'; } +dev_member() { cat; } +sleep() { SECONDS=$((SECONDS + 10)); } +curl() { + case " $* " in + *" Idempotency-Key: dev-e2e-sms "*) printf 'sms\n' ;; + *" Idempotency-Key: dev-e2e-email "*) printf 'email\n' ;; + *" http://api/v1/messages/sms "*) printf 'delivered\n' ;; + *" http://api/v1/messages/email "*) printf 'submitted\n' ;; + *" http://mailpit/api/v1/messages "*) printf '1\n' ;; + *" http://metrics "*) + local value=$FIRST_COUNT + if [[ -f "$TEST_READ" ]]; then value=$NEXT_COUNT; fi + : >"$TEST_READ" + printf 'messaging_provider_callbacks_total{outcome="applied"} %s\n' "$value" + ;; + *) printf 'Unexpected request\n' >&2; return 2 ;; + esac +} +""" + + +class CallbackMetricWait(unittest.TestCase): + def run_delivery_check(self, first, subsequent): + with tempfile.TemporaryDirectory() as directory: + scratch = Path(directory) + shutil.copyfile(SCRIPT, scratch / SCRIPT.name) + (scratch / "dev-session.sh").write_text(SESSION) + return subprocess.run( + ["bash", str(scratch / SCRIPT.name)], + env=dict(os.environ, FIRST_COUNT=first, NEXT_COUNT=subsequent, TEST_READ=str(scratch / "read")), + capture_output=True, + text=True, + timeout=5, + ) + + def test_waits_when_delivered_precedes_the_applied_counter(self): + result = self.run_delivery_check("0", "1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("1 signed delivery callback applied", result.stdout) + + def test_times_out_with_the_last_observed_count(self): + result = self.run_delivery_check("0", "0") + self.assertEqual(result.returncode, 1) + self.assertIn("after 30 seconds, observed 0 applied signed callbacks, expected exactly 1", result.stderr) + + def test_refuses_a_count_above_one(self): + result = self.run_delivery_check("0", "2") + self.assertEqual(result.returncode, 1) + self.assertIn("after 30 seconds, observed 2 applied signed callbacks, expected exactly 1", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/platform/AGENTS.md b/products/platform/AGENTS.md index ec9675ce6f..cb87d43503 100644 --- a/products/platform/AGENTS.md +++ b/products/platform/AGENTS.md @@ -8,11 +8,18 @@ into the platform just to remove superficially similar code. Platform owns the session service's runtime file, in-memory sessions, browser sign-in and sign-out, private per-call gateway check and Envoy -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` -adds its binary to numbered releases from v0.51.0. +fragments. Among workspace crates and every other `registry-*` package, +`registry-session` reaches only `registry-platform-*` crates. Only +`registry-cli-docs` may reach Session, to read its command tree. The +[`check-session-dependencies.py`](scripts/check-session-dependencies.py) gate +enforces both directions over normal and build dependencies and each package's +own dev-dependencies, so a test cannot link what the package may not, and +names the path of every reach it refuses. Session 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` adds its binary to numbered releases from +v0.51.0. +`SESSION_IMAGE_FIRST_RELEASE` adds its container image from v0.52.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 887e23322a..2e4d59f2a5 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,95 @@ ## Unreleased +- In `dev.yaml`, `preview.coordinatorFunctions` selects functions callable only by Coordinator. + The generated `defineFunction` binding passes the authenticated caller kind as its third + argument. Coordinator calls receive a request without the `Authorization` header and a + credential-free client that refuses registry operations before dispatch. + +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + +- BREAKING: Provisioning and `rstack dev` refuse `sslmode=verify-ca` in administrator URLs. + Use `sslmode=verify-full` to verify the server certificate chain and hostname. + +- PostgreSQL URLs accept `sslmode=verify-full` for transports that verify the server certificate chain and hostname. Unsupported modes, including `verify-ca`, receive a value-free diagnostic naming `sslmode` and the accepted values. + +- BREAKING: Generated configuration posture summaries in JSON reports now use + sentence wording, starting with an uppercase letter and omitting the final + period. Migration: replace matches on the `summary` text with exact matches + on the setting's stable `code` field. For example, match `code` equal to + `platform.posture.jwt-access-token` in `explicitProductionSettings`. + Use `summary` for display and `pointer` to locate the setting. + +- A refused token whose `aud` claim does not name the issuer entry's + `audience`, or whose `exp` time has passed, now carries a fixed remedy on + the operator's `request refused` log line, naming the `aud` claim and the + entry's `audience`, or the `exp` claim. Every runtime that verifies tokens + through the shared issuer set logs it. The remedy names keys and claims, + never a value. + +- Add `rstack dev export-preview PROJECT --output DIRECTORY`. It checks and builds a project's service preview without starting a service, and writes exactly the preview manifest, each compiled function and every file of the manifest's `staticOutput` into a new directory, refusing an existing path or a project without a preview. It prints the bundle digest beside the manifest's `declarationDigest`. The bundle digest is the lowercase hex SHA-256 of a compact UTF-8 JSON array of `["path","sha256"]` pairs, one per file, with the path relative to the bundle using `/` and the file's lowercase hex SHA-256, sorted by the bytes of the path. Two exports of the same source give the same bytes wherever the project and the state directory are. The business-registration reference host pins this digest, computed the same way over every bundle file. + +- The preview manifest leaves out `product.project`, the absolute path of the BReg project it was built from, so its bytes no longer depend on the build location. Nothing read the member. + +- `createHolderActionHandler` takes an optional `{ onOutcome }` hook that receives one outcome per answer: its class, its checked attempt key and its HTTP status, never a submitted or prepared value or the credential. The hook may be async; a throw or rejection is logged and leaves the answer unchanged. + +- BREAKING: every provision tool reads `caBundleRef` (`/database/caBundleRef`, + or `/store/caBundleRef` for `adapterctl job-provision`) with the one CA + bundle reader the runtimes and `rstack dev` use, `pem_roots` in + `registry-platform-postgres`, when it reads the runtime file. A bundle that + holds no usable certificate is refused at the member in both modes, with + `platform.provision.ca-bundle-no-certificate`, `ca-bundle-invalid-pem` or + `ca-bundle-unusable-certificate`. `--print-sql` no longer plans over such a + bundle, and apply reports these codes at the member where it reported + `platform.provision.admin-ca-invalid` with an empty path. + `admin-ca-invalid` remains for a TLS provider or platform root failure. + Migration: scripts that match `admin-ca-invalid` for a bad bundle match the + `ca-bundle-*` codes. The reader ignores text outside the certificate + blocks in any encoding, so provision now accepts a bundle with a Latin-1 + comment, as the runtimes did. It also skips a leading byte-order mark, so + every runtime and provision tool now trusts the first certificate of a + BOM-prefixed bundle, which the runtimes refused or skipped before. Every + provision tool now words a secret or public-document refusal with its + reason and the fix the error names. + +- BREAKING: every `provision` tool reports a database member's secret or + public-document refusal with one shared code per refusal kind, at the + member's pointer: `platform.provision.secret-reference-invalid`, + `secret-provider-disabled`, `secret-providers-invalid`, + `secret-unavailable`, `secret-file-unsafe`, `public-document-unsafe`, + `public-document-private-key`, + `secret-unreadable` and `secret-value-invalid`, all under + `platform.provision.`. A URL secret that is not UTF-8 text is + `secret-value-invalid`, with a message that names the encoding, and a + secret provider refusal carries the same code at `/secretProviders`, except + in `bregctl`, which reports it as a refused runtime file. Migration: scripts that match these refusals by code + replace `config.refused` (`bregctl`, `documentsctl`, `messagingctl`, + `schedulingctl`, `adapterctl provision` and `adapterctl job-provision`), + `coordinator.runtime-config.refused` (`coordinatorctl`), + `casework.runtime.secret-unavailable` (`caseworkctl`), and + `evidence.store-provision.secret-unavailable`, + `evidence.store-provision.url-invalid` and + `evidence.store-provision.secret-provider` (`evidencectl store-provision`) + with the new codes. `bregctl provision` reports an unreadable database URL + or CA bundle at its member rather than as `breg.runtime.secret` with an + empty path, and `caseworkctl provision` writes the plain member pointer + rather than prefixing it with `runtime.yaml:`. The codes are listed in the + errors reference. + +- A `provision` tool's human output names the fix for a refused secret file + or public document once, on its `next:` line. The JSON `message` no longer + repeats the `suggestedAction`. Runtime refusals keep the fix in their one + message. + +- BREAKING for Rust callers of `registry-platform-config`: `SecretError` removes + `PublicDocumentNotText`. Migration: remove its arm from exhaustive matches + and handle invalid CA bundles through the caller's CA bundle errors. + +- Publish the `ghcr.io/registrystack/registry-session` container image and its candidate-bound security evidence from v0.52.0. + ## 0.51.0 - 2026-12-03 - `rstack dev check` refuses incompatible owner reports and mismatched identity facts. diff --git a/products/platform/CONFIG-CONVENTIONS.md b/products/platform/CONFIG-CONVENTIONS.md index 6d898bdb73..6b883f7245 100644 --- a/products/platform/CONFIG-CONVENTIONS.md +++ b/products/platform/CONFIG-CONVENTIONS.md @@ -815,6 +815,11 @@ example `documents.runtime.insecure-url`). The spellings that predate this are listed under [recorded exceptions](#recorded-exceptions-outside-the-lint-register). +Write summaries for explicit production settings and development settings as +sentences beginning with an uppercase letter. Omit the final period because +the notice adds it. The configuration conventions lint checks authored setting +summaries. The report uses the authored text. + **CFG-DIAG-4 (MUST). Exit codes:** 0 when no error was reported (warnings allowed), 1 when the input was refused, 2 for a usage error, 3 when something the command depends on was unavailable or an internal error stopped it. An diff --git a/products/platform/README.md b/products/platform/README.md index 75f437c85e..d4d51d36b3 100644 --- a/products/platform/README.md +++ b/products/platform/README.md @@ -19,7 +19,8 @@ Platform also owns the [session service](../../crates/registry-session/README.md 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. Numbered releases ship its -binary from v0.51.0, as `SESSION_FIRST_RELEASE` sets. +binary from v0.51.0 and its image from v0.52.0, as `SESSION_FIRST_RELEASE` and +`SESSION_IMAGE_FIRST_RELEASE` set. ## Crates diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 4609123107..0e7e80e36f 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -2563,7 +2563,7 @@ formats: whenOmitted: closed - pointer: /metricsListener/networkExposure whenOmitted: closed - - pointer: /authentication/apiKeyRef + - pointer: /authentication whenOmitted: refused - pointer: /authentication/oidc/issuers/*/allowedClients whenOmitted: refused diff --git a/products/platform/examples/service-previews/business-registration/functions/register-business/index.ts b/products/platform/examples/service-previews/business-registration/functions/register-business/index.ts index 555350fb31..b5ffd21a1c 100644 --- a/products/platform/examples/service-previews/business-registration/functions/register-business/index.ts +++ b/products/platform/examples/service-previews/business-registration/functions/register-business/index.ts @@ -1,9 +1,15 @@ import { RegistryError } from '@registrystack/client/core' import { defineFunction } from '../../generated/server.js' +import { prepare } from './prepare.js' import { makeRegistrationHandler } from './register.js' +// The reference host imports only this export. Under rstack dev, the default export below +// prepares the input the same way and calls BReg through the preview's own client. +export { prepare } + export default defineFunction(async (request, businesses) => { - const handler = makeRegistrationHandler(async ({ input, idempotencyKey }) => { + const handler = makeRegistrationHandler(async ({ input: submitted, idempotencyKey }) => { + const input = prepare(submitted) try { const result = await businesses.invoke('register-business', input, { accessProfile: 'business-registrar', diff --git a/products/platform/examples/service-previews/business-registration/functions/register-business/prepare.ts b/products/platform/examples/service-previews/business-registration/functions/register-business/prepare.ts new file mode 100644 index 0000000000..ea0482ed0c --- /dev/null +++ b/products/platform/examples/service-previews/business-registration/functions/register-business/prepare.ts @@ -0,0 +1,10 @@ +export type Registration = { legalName: string; registrationNumber: string } + +/** + * Prepare register-business's input from the page's two fields. It is pure, so a retry of the + * same attempt prepares the same input. The reference host runs only this export, with its own + * reviewed client and the caller's credential; this function never sees either. + */ +export function prepare({ legalName, registrationNumber }: Registration): Registration { + return { legalName: legalName.trim(), registrationNumber: registrationNumber.trim() } +} 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 index 69bcc49cf5..19d2fd9dcf 100644 --- 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 @@ -1,8 +1,6 @@ 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. +// The function host authenticates the page gateway or Coordinator before invoking the binding. +// This function returns an assessment of the content the Coordinator read. export default defineFunction(async (request) => handleAssessment(request)) 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 index e227053bba..6a1664d582 100644 --- 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 @@ -1,7 +1,6 @@ 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. +// This function hashes the content the Coordinator read and returns the digest. +// The function host authenticates the page gateway or Coordinator before invoking the binding. export default defineFunction(async (request) => handleDigest(request)) diff --git a/products/platform/fixtures/client-response-tolerance/evidence.json b/products/platform/fixtures/client-response-tolerance/evidence.json new file mode 100644 index 0000000000..1b4e766c4f --- /dev/null +++ b/products/platform/fixtures/client-response-tolerance/evidence.json @@ -0,0 +1,199 @@ +{ + "definitions": { + "additive": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[],\"futureMember\":{\"hint\":true}}", + "duplicate": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[],\"futureMember\":{\"hint\":true,\"hint\":false}}", + "missingRequired": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"futureMember\":{\"hint\":true}}" + }, + "requestBatch": { + "additive": "{\"schema\":\"registry.evidence-request-batch/v1\",\"type\":\"EvidenceRequestBatchResponse\",\"items\":[{\"result\":\"evidence-not-available\",\"futureMember\":{\"hint\":true}},{\"result\":\"evidence-not-available\"}],\"futureBatchMember\":{\"version\":2}}", + "duplicate": "{\"schema\":\"registry.evidence-request-batch/v1\",\"type\":\"EvidenceRequestBatchResponse\",\"items\":[{\"result\":\"evidence-not-available\",\"futureMember\":{\"hint\":true,\"hint\":false}},{\"result\":\"evidence-not-available\"}],\"futureBatchMember\":{\"version\":2}}", + "missingRequired": "{\"schema\":\"registry.evidence-request-batch/v1\",\"type\":\"EvidenceRequestBatchResponse\",\"futureBatchMember\":{\"version\":2}}" + }, + "holderBatch": { + "additive": "{\"schema\":\"registry.sd-jwt-vc-batch-envelope/v1\",\"type\":\"SdJwtVcBatchEnvelope\",\"credentials\":[\"credential-for-key-0\",\"credential-for-key-1\"],\"futureMember\":{\"hint\":true}}", + "duplicate": "{\"schema\":\"registry.sd-jwt-vc-batch-envelope/v1\",\"type\":\"SdJwtVcBatchEnvelope\",\"credentials\":[\"credential-for-key-0\",\"credential-for-key-1\"],\"futureMember\":{\"hint\":true,\"hint\":false}}", + "missingRequired": "{\"schema\":\"registry.sd-jwt-vc-batch-envelope/v1\",\"type\":\"SdJwtVcBatchEnvelope\",\"futureMember\":{\"hint\":true}}" + }, + "problems": [ + { + "name": "future conflict", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future-conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future-conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "invalid-request", + "code": "request.future-conflict", + "problemType": "https://id.registrystack.org/problems/registry-evidence/request/future-conflict" + }, + { + "name": "future unprocessable request", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/evidence/future-unavailable\",\"title\":\"Example problem title\",\"status\":422,\"detail\":\"Example problem detail.\",\"code\":\"evidence.future-unavailable\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "not-available", + "code": "evidence.future-unavailable", + "problemType": "https://id.registrystack.org/problems/registry-evidence/evidence/future-unavailable" + }, + { + "name": "future rate limit", + "status": 429, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/evidence/future-rate-limit\",\"title\":\"Example problem title\",\"status\":429,\"detail\":\"Example problem detail.\",\"code\":\"evidence.future-rate-limit\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "denied", + "code": "evidence.future-rate-limit", + "problemType": "https://id.registrystack.org/problems/registry-evidence/evidence/future-rate-limit" + }, + { + "name": "future service failure", + "status": 503, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/service/future-unavailable\",\"title\":\"Example problem title\",\"status\":503,\"detail\":\"Example problem detail.\",\"code\":\"service.future-unavailable\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "unavailable", + "code": "service.future-unavailable", + "problemType": "https://id.registrystack.org/problems/registry-evidence/service/future-unavailable" + }, + { + "name": "reworded registered refusal", + "status": 403, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/evidence/denied\",\"title\":\"Example problem title\",\"status\":403,\"detail\":\"Example problem detail.\",\"code\":\"evidence.denied\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "denied", + "code": "evidence.denied", + "problemType": "https://id.registrystack.org/problems/registry-evidence/evidence/denied" + }, + { + "name": "registered code with a different status", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/evidence/denied\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"evidence.denied\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "registered code with a different type", + "status": 403, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/auth/invalid-credential\",\"title\":\"Example problem title\",\"status\":403,\"detail\":\"Example problem detail.\",\"code\":\"evidence.denied\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "invalid code spelling", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future_conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future_conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "repeated reason hyphen", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future--conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future--conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "trailing reason hyphen", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future-conflict-\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future-conflict-\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "repeated family hyphen", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/future--request/conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"future--request.conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "trailing family hyphen", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/future-request-/conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"future-request-.conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "missing required title", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future-conflict\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future-conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true}}", + "kind": "protocol" + }, + { + "name": "duplicate ignored member", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future-conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future-conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"hint\":true,\"hint\":false}}", + "kind": "protocol" + }, + { + "name": "registered development assertion refusal", + "status": 401, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/platform/task-grant/development-assertion\",\"title\":\"Example problem title\",\"status\":401,\"detail\":\"Example problem detail.\",\"code\":\"platform.task-grant.development-assertion\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\"}", + "kind": "denied", + "code": "platform.task-grant.development-assertion", + "problemType": "https://id.registrystack.org/problems/registry-evidence/platform/task-grant/development-assertion" + }, + { + "name": "development assertion code with wrong status", + "status": 403, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/platform/task-grant/development-assertion\",\"title\":\"Example problem title\",\"status\":403,\"detail\":\"Example problem detail.\",\"code\":\"platform.task-grant.development-assertion\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\"}", + "kind": "protocol" + }, + { + "name": "development assertion code with wrong type", + "status": 401, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/platform/task/development-assertion\",\"title\":\"Example problem title\",\"status\":401,\"detail\":\"Example problem detail.\",\"code\":\"platform.task-grant.development-assertion\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\"}", + "kind": "protocol" + }, + { + "name": "future qualified conflict", + "status": 409, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-evidence/request/future-family/conflict\",\"title\":\"Example problem title\",\"status\":409,\"detail\":\"Example problem detail.\",\"code\":\"request.future-family.conflict\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\"}", + "kind": "invalid-request", + "code": "request.future-family.conflict", + "problemType": "https://id.registrystack.org/problems/registry-evidence/request/future-family/conflict" + } + ], + "wrongShapes": [ + { + "target": "definitions", + "name": "object-valued assurance profile", + "body": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":{\"local\":null},\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[],\"futureMember\":{\"hint\":true}}" + }, + { + "target": "definitions", + "name": "positional definition", + "body": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[[\"status\",\"urn:example:status\",\"urn:example:revision\",\"criterion\",null,\"urn:example:type\",\"urn:example:purpose\",[\"signed-jws\"],[],[],[]]],\"futureMember\":{\"hint\":true}}" + }, + { + "target": "definitions", + "name": "object-valued definition kind", + "body": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[{\"handle\":\"status\",\"requirement\":\"urn:example:status\",\"configurationRevision\":\"urn:example:revision\",\"kind\":{\"criterion\":null},\"evidenceType\":\"urn:example:type\",\"purpose\":\"urn:example:purpose\",\"responseFormats\":[\"signed-jws\"],\"referenceFrameworks\":[],\"subjects\":[],\"concepts\":[]}],\"futureMember\":{\"hint\":true}}" + }, + { + "target": "requestBatch", + "name": "positional request batch", + "body": "[\"registry.evidence-request-batch/v1\",\"EvidenceRequestBatchResponse\",[{\"result\":\"evidence-not-available\",\"futureMember\":{\"hint\":true}},{\"result\":\"evidence-not-available\"}]]" + }, + { + "target": "requestBatch", + "name": "object-valued request batch type", + "body": "{\"schema\":\"registry.evidence-request-batch/v1\",\"type\":{\"EvidenceRequestBatchResponse\":null},\"items\":[{\"result\":\"evidence-not-available\",\"futureMember\":{\"hint\":true}},{\"result\":\"evidence-not-available\"}],\"futureBatchMember\":{\"version\":2}}" + }, + { + "target": "requestBatch", + "name": "positional flattened JWS in request batch", + "body": "{\"schema\":\"registry.evidence-request-batch/v1\",\"type\":\"EvidenceRequestBatchResponse\",\"items\":[{\"result\":\"evidence\",\"evidence\":[\"a\",\"b\",\"c\"]},{\"result\":\"evidence-not-available\"}],\"futureBatchMember\":{\"version\":2}}" + }, + { + "target": "holderBatch", + "name": "positional holder batch", + "body": "[\"registry.sd-jwt-vc-batch-envelope/v1\",\"SdJwtVcBatchEnvelope\",[\"credential-for-key-0\",\"credential-for-key-1\"]]" + }, + { + "target": "jwks", + "name": "positional published JWKS", + "body": "[[]]" + }, + { + "target": "jwks", + "name": "non-object published JWK", + "body": "{\"keys\":[[]]}" + }, + { + "target": "definitions", + "name": "null subjectBindingMode", + "body": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[{\"handle\":\"status\",\"requirement\":\"urn:example:status\",\"configurationRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"kind\":\"criterion\",\"evidenceType\":\"urn:example:type\",\"purpose\":\"fixture-routing\",\"responseFormats\":[\"signed-jws\"],\"referenceFrameworks\":[\"urn:example:framework\"],\"subjects\":[{\"role\":\"subject\",\"cardinality\":\"one\",\"selector\":{\"profile\":\"fixture-reference\",\"valueOrigin\":\"request\",\"fields\":[{\"type\":\"date\",\"name\":\"reference\"}]}}],\"concepts\":[{\"handle\":\"status\",\"concept\":\"urn:example:concept:status\",\"required\":true,\"form\":{\"type\":\"boolean\"}}],\"subjectBindingMode\":null}],\"maximumHolderBoundBatchSize\":1}" + }, + { + "target": "definitions", + "name": "null channel", + "body": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[{\"handle\":\"status\",\"requirement\":\"urn:example:status\",\"configurationRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"kind\":\"criterion\",\"evidenceType\":\"urn:example:type\",\"purpose\":\"fixture-routing\",\"responseFormats\":[\"signed-jws\"],\"referenceFrameworks\":[\"urn:example:framework\"],\"subjects\":[{\"role\":\"subject\",\"cardinality\":\"one\",\"selector\":{\"profile\":\"fixture-reference\",\"valueOrigin\":\"request\",\"fields\":[{\"type\":\"date\",\"name\":\"reference\"}]}}],\"concepts\":[{\"handle\":\"status\",\"concept\":\"urn:example:concept:status\",\"required\":true,\"form\":{\"type\":\"boolean\"}}],\"channel\":null}],\"maximumHolderBoundBatchSize\":1}" + } + ], + "definitionsWithoutModes": "{\"schema\":\"registry.evidence-definitions/v1\",\"assuranceProfile\":\"local\",\"audience\":\"urn:example:client:audience:relying-party\",\"issuedBy\":\"urn:example:client:issuer\",\"providedBy\":\"urn:example:client:provider\",\"definitions\":[{\"handle\":\"status\",\"requirement\":\"urn:example:status\",\"configurationRevision\":\"sha256:1111111111111111111111111111111111111111111111111111111111111111\",\"kind\":\"criterion\",\"evidenceType\":\"urn:example:type\",\"purpose\":\"fixture-routing\",\"responseFormats\":[\"signed-jws\"],\"referenceFrameworks\":[\"urn:example:framework\"],\"subjects\":[{\"role\":\"subject\",\"cardinality\":\"one\",\"selector\":{\"profile\":\"fixture-reference\",\"valueOrigin\":\"request\",\"fields\":[{\"type\":\"date\",\"name\":\"reference\"}]}}],\"concepts\":[{\"handle\":\"status\",\"concept\":\"urn:example:concept:status\",\"required\":true,\"form\":{\"type\":\"boolean\"}}]}],\"maximumHolderBoundBatchSize\":1}" +} diff --git a/products/platform/generated/dev/dev.v1alpha1.schema.json b/products/platform/generated/dev/dev.v1alpha1.schema.json index 9ce15fb8db..2a729aa52b 100644 --- a/products/platform/generated/dev/dev.v1alpha1.schema.json +++ b/products/platform/generated/dev/dev.v1alpha1.schema.json @@ -545,8 +545,17 @@ "$ref": "#/$defs/Routes", "description": "BReg paths exposed to the page of the single `actor`, grouped by method." }, + "coordinatorFunctions": { + "default": [], + "description": "Declared functions callable only by Coordinator. These names must be distinct from functions.", + "items": { + "$ref": "#/$defs/LocalId" + }, + "type": "array", + "uniqueItems": true + }, "functions": { - "description": "Declared functions to expose on the loopback preview origin.", + "description": "Declared functions callable by the page and Coordinator.", "items": { "$ref": "#/$defs/LocalId" }, diff --git a/products/platform/journeys/README.md b/products/platform/journeys/README.md index 99ad1feebf..97c665056a 100644 --- a/products/platform/journeys/README.md +++ b/products/platform/journeys/README.md @@ -34,7 +34,7 @@ identity provider. | File | Holds | |---|---| | `products.yaml` | The product column: the sixteen runtimes that load a runtime file, with their crate, binary, tool, and whether they use PostgreSQL or verify tokens. Ten are primary and six are supporting. A supporting runtime starts beside its parent, so a journey records it as unreached. | -| `first-hour-pass-rule.yaml` | What counts as a pass for a first hour: six hard conditions, ten counters with a threshold for each path, and the model that turns effort into reader time. | +| `first-hour-pass-rule.yaml` | Six hard conditions, ten counter definitions and per-path reference values, and the reader-time model. | | `concepts.yaml` | The closed list of concepts that counter 6 counts. | | `expected-failures.yaml` | The ratchet table for Keycloak (`own-provider`), `rstack-dev`, and `promote`. Every cell (a journey and a product) is listed once, as an expected failure, as unreached, or as a pass. | | `expected-failures-thunderid.yaml` | The separate same-schema ratchet table for `--issuer thunderid` (`own-provider-thunderid`). Every primary token-verifying product is covered; intentional exclusions (`discovery` and the six supporting runtimes) are recorded under `unreached`. | @@ -162,20 +162,72 @@ change that fixes a cell deletes the row in the same commit and adds the cell to `passes`. A fix that is not recorded fails the run, and so does a new failure that the table does not list. -On the own-provider and rstack-dev paths, each completed cell reports a -first-hour comparison against all ten thresholds. ThunderID uses the -own-provider limits. The comparison is **NOT MET** if any value is missing, -unreadable, or outside its threshold. The log shows the comparison and the -functional outcome. The sanitized `public-cell-receipts//cell.json` -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. +Own-provider and rstack-dev cells report adopter effort, actionable diagnostics, +and machine time. Both own-provider issuers use the 30-minute T1 and 60-minute +T2 budgets. The managed path uses 10 and 30 modeled minutes. The sanitized +`public-cell-receipts//cell.json` includes the functional outcome and +the three results, plus the units, measured values and statuses of the ten +counters. Each cell in `summary.json` carries the same projection in +`firstHour`. + +- Effort compares counters 1–8 and checks all six hard conditions. A breached + condition or an exceeded effort limit yields **NOT MET**. When the evidence + needed to decide effort is missing, the verdict is **UNAVAILABLE** unless a + measured failure already decides it. +- Diagnostics compare counter 10 against the required number of distinct + controls. The receipt names the live issuer or isolated test that supplied + each credit. A checked control without actionable guidance remains visible + in `liveChecks`. Older raw receipts can preserve a live count without a + control identifier. The projection displays it as `unattributedLiveCount`. +- Machine time (counter 9) is informational. The receipt reports elapsed + minutes to T1 with the existing reference value. + +Each product cell reads the maintained prose in +[first-hour-reading.md](first-hour-reading.md). Its raw counters record the +section IDs as `readingSections` alongside `documentationWords`, with the +source revision in `run.json`. This is a fixed recipe input for modeled +reading effort. A live harness run measures machine behavior without measuring +a human reader. Explicit `--typed ''` marks a harness-only command or HTTP +control whose output is still recorded but whose command and characters are +excluded from reader effort. Generated fixture contents carry no typing charge. + +Managed retention charges the JSON request syntax as +`curl -H @HEADER_FILE -H 'Idempotency-Key:journey-keep' --json @keep-body.json URL`. +`HEADER_FILE` stands for the path reported by `rstack dev token`. `--json` +sends the named body file with `Content-Type: application/json`. Document Store reserves with +`curl -H @HEADER_FILE -H 'Idempotency-Key:journey-document-reservation' --json @document-reserve.json DOCUMENTS_URL` +and uploads with +`curl -X PUT -H @HEADER_FILE -H 'Content-Type: application/pdf' --data-binary @retained.pdf UPLOAD_URL` +at the returned upload path. The fixture sink reads verify that the expected +events arrived and carry no typing charge. Own-provider T1 snapshots machine +time at the successful GET. Later diagnostic controls contribute to the cell's +total machine time and any measured counter 10 credit. + +The ThunderID wrong-audience control earns live credit when the refusal log +names the `aud` claim and audience configuration. The runner matches the trace +where both sides expose one. On Adapter and Documents the live control must add +exactly one matching line between snapshots. The managed Casework scope +control remains opt-in and requires its correlated scope claim and required +scope. + +The product table records verified isolated checks for wrong audience, missing +scope and expired token. The scoped suites verify ordinary product refusals and +operator guidance in fixtures. These credits carry the check name and can be +reused across issuer paths. Live issuer credit comes from the current journey. +When both sources verify one control, the receipt shows both sources for a +single credit. [Product table](products.yaml) + +T1 is captured at the first successful authenticated read. If the first +operation is a write, its authenticated readback can provide T1. T2 requires +an accepted write, a restart, a readback and, on paths that exercise a hook, +delivery. The product table gives the T2 recipe status for each path. +Managed BReg, Coordinator, Documents and Messaging have a recipe. A path +marked `recipe-gap` still needs the documented sequence. A path marked +`recipe` without a snapshot has unavailable measurement evidence. Render's +stateless rendering and Discovery's public index mark T2 as inapplicable on +both paths. Discovery's public read also makes authenticated T1 and the +bearer diagnostics inapplicable. Supporting runtimes share their parent's +journey and have no standalone first-hour assessment. Threshold outcomes are report-only in CI. The functional ratchet controls journey acceptance, and comparison code errors fail the harness. Promote @@ -225,8 +277,10 @@ It checks that: that exist in `crates/` - the `rstackDevPlan` flag matches the products `rstack dev` can plan - the Keycloak image equals the pin in the portability journey -- the pass rule has the six hard conditions, ten numbered counters with both - thresholds, and the full reader-time model +- the threshold table has the six hard conditions, ten numbered counters + with both path values, and the full reader-time model +- the product table records T2 applicability and recipe coverage per path + and points each isolated diagnostic credit to its scoped check - the concept list has unique, well-formed entries - every journey and product cell appears exactly once, every step belongs to its journey, every code is valid, every failure row names a listed change, diff --git a/products/platform/journeys/first-hour-pass-rule.yaml b/products/platform/journeys/first-hour-pass-rule.yaml index 6ea4c25625..b0ff00fff2 100644 --- a/products/platform/journeys/first-hour-pass-rule.yaml +++ b/products/platform/journeys/first-hour-pass-rule.yaml @@ -3,7 +3,7 @@ # One first hour is one product, one path (own-provider or rstack-dev) and one # reader. The rule is fixed before the first measured run. A number changes only # by a reviewed edit to this file that says why, never to make a measured run -# pass. +# pass. Issue #2902 retains the path-specific T1 and T2 time budgets. schema: registry.first-hour-pass-rule/v1 @@ -55,7 +55,7 @@ counters: ownProvider: 2 - id: 3 name: lines-written-to-t1 - how: Lines the reader types into those files. + how: "New or changed lines the reader types into those files. Reused lines such as starter comments are excluded." unit: lines rstackDev: 0 ownProvider: 25 diff --git a/products/platform/journeys/first-hour-reading.md b/products/platform/journeys/first-hour-reading.md new file mode 100644 index 0000000000..b76c0ed783 --- /dev/null +++ b/products/platform/journeys/first-hour-reading.md @@ -0,0 +1,78 @@ +# First-hour recipe reading + +The drivers count the prose in the named sections they reach. These sections +describe the reader-facing portions of the commands and fixtures in each driver. +Each section is read once per product cell. A section describes the route even +when a later command is refused. + +## rstack-dev + +Start from the product's starter project. Check the generated development plan if the starter cannot use the managed plan directly. Start the project and use the reported local address. For a protected route, ask the development issuer for the named reader's bearer token and send it in an Authorization header. Keep the token file private. + +## own-provider + +Prepare the starter package and runtime file before serving. Choose the issuer, audience, allowed caller and required scopes. Provide the declared secret references and, for products with durable state, separate database credentials for setup and serving. Start the service in development posture and wait for readiness before obtaining credentials and calling the API. + +## keycloak + +Use the realm's caller client and the product's resource audience. Select the client's service-account grants and request the product scopes when obtaining the access token. Use the same issuer in the runtime and the token request. + +## thunderid + +Choose the product resource audience and the caller allowed to request it. Assign and request the product scopes. Configure the issuer for signed access tokens and the scope claim the issuer supplies. Where the route requires a person, sign in as the fixture user. + +## breg + +Use the editor's record read authority. Address the starter register and record in the URL and read the authorized record. Keep the record identifier for the later retained read. + +## casework + +Use the staff profile to list review policies on the managed path. Use the requester profile on the own-provider path. Select the profile in the request, since the service and human callers have distinct authority. + +## messaging + +Use the configured sender profile and an authorized caller. Send the starter reminder with its reviewed template, destination and idempotency key. Read the receipt with the same request and key when the managed starter has already submitted it. + +## evidence + +Use an authorized caller to read the available assertion definitions. Check that the selected issuer admits that caller. The starter binds a fixture source for the service to use when answering an assertion request. + +## scheduling + +Read the catalogue with the catalogue reader's token. Booking authority is a separate task grant with the resource, scope, and offering location fixed by the approved task. + +## documents + +Use the custodian caller and read the configured custody policies. The staff profile is separate from the custodian's document access. Keep the policy identifier for a subsequent reservation. + +## coordinator + +Use the admitted caller for the starter workflow and read the published workflow metadata. Keep the workflow identifier and version when creating or reading a run. + +## adapter + +Start the fixture source and use an allowed caller. Read the effective contract on the managed path. Submit the starter JSON request to the configured operation on the own-provider path. The facade uses its own binding when it calls the source. + +## render + +Package the starter bundle and use the authorized render caller. Read the document types on the managed path. On the own-provider path, select a declared type, send the fixture fields and issuance time, and check the returned PDF. + +## discovery + +Use the generated starter index and the public read route. This publication has no bearer-token step, so its public response does not supply an authenticated-read endpoint. + +## breg-keep + +Create a contact with the editor, wait for the signed creation event and retain its record identifier. Restart the managed process and read that same contact back using the editor's new token. + +## coordinator-keep + +Start a run with the pinned workflow version and a caller-chosen idempotency key. Restart the managed process and read the previously created run by its returned identifier. + +## documents-keep + +Reserve a version using the custody policy, the content digest and the byte length calculated from the file. Upload the bytes at the returned path and check delivery of the ready event. After restart, use the same document identifier to retrieve the exact ready version. + +## messaging-keep + +Send a second reminder with a distinct idempotency key. Retain the receipt identifier, restart the managed process and read that same receipt with the authenticated caller. diff --git a/products/platform/journeys/first-hour-receipt.jq b/products/platform/journeys/first-hour-receipt.jq index f081e1133d..a61d147ccc 100644 --- a/products/platform/journeys/first-hour-receipt.jq +++ b/products/platform/journeys/first-hour-receipt.jq @@ -5,29 +5,125 @@ def valid($unit): else . == floor and ($unit != "of-three" or . <= 3) end; +def hard_conditions($cell; $inapplicable): + ($cell.total | objects // {}) as $total + | ($cell.blockers | arrays // []) as $blockers + | ([$cell.code] + [$blockers[] | objects | .code]) as $codes + | ([$blockers[] | objects | .assist]) as $assists + | (($cell.outcome == "pass" or $cell.outcome == "assisted") + and ($cell.blockers | type) == "array" + and all($blockers[]; type == "object" and (.assist | type) == "string") + and ($total.assistsUsed | valid("count")) + and $total.assistsUsed == ($blockers | length) + and ($total.assistsUsed > 0) == ($cell.outcome == "assisted")) as $completed + | { + certificate: (($total.certificatesMade | valid("count") and . > 0) + or ($codes | index("journey.needs.certificate") != null) + or ($assists | index("certificate") != null)), + "token-hook-or-mapper": (any($codes[]; . == "journey.needs.claim-mapper" or . == "journey.needs.token-hook") + or any($assists[]; . == "mapper" or . == "token-hook")), + "provisioning-sql": (($codes | index("journey.needs.hand-written-sql") != null) + or ($assists | index("sql") != null)), + "image-build": (($codes | index("journey.needs.image-build") != null) + or ($assists | index("image-build") != null)), + "signature-verifier": (($codes | index("journey.needs.signature-verifier") != null) + or ($assists | index("signature-verifier") != null)), + "no-refusal": (($total.refusalsMet | valid("count") and . > 0) + or any($codes[] | strings; startswith("http.") or startswith("product.") + or . == "journey.needs.claim-mapper") + or any(([$cell] + $blockers)[] | objects; + .step == "start" and .code == "journey.needs.certificate")) + } as $violations + | $conditions | map( + . as $id | {key: $id, value: + (if $inapplicable then "inapplicable" + elif ($violations | has($id) | not) then error("unknown first-hour hard condition \($id)") + elif $violations[$id] then "violated" + elif $completed + and ($id != "certificate" or ($total.certificatesMade | valid("count"))) + and ($id != "no-refusal" or ($total.refusalsMet | valid("count"))) + then "held" else "unavailable" end)} + ) | from_entries; + +def diagnostic_evidence($cell; $product; $inapplicable): + if $inapplicable then {credits: {}, liveChecks: {}, unattributedLiveCount: null} + else + ["wrong-audience", "missing-scope", "expired-token"] as $controls + | ($cell.diagnosticChecks | objects // {}) as $observations + | ($product.verifiedIsolatedDiagnostics // {} | to_entries) as $isolated + | ($controls | map(. as $id | $observations[$id] as $status + | select($status == "verified" or $status == "unverified") + | {key: $id, value: $status}) | from_entries) as $live + | ($controls | map( + . as $id + | ((if $live[$id] == "verified" then [{kind: "live-issuer", issuer: $issuer}] else [] end) + + [$isolated[] | select(any(.value[]; . == $id)) | {kind: "isolated-test", check: .key}]) + | select(length > 0) | {key: $id, value: .} + ) | from_entries) as $credits + | { + credits: $credits, + liveChecks: $live, + unattributedLiveCount: (if $cell.diagnosticChecks == null + and ($cell.passRule | type) == "object" + then ($cell.passRule["errors-that-say-what-to-change"] | select(valid("of-three"))) // null + else null end) + } + end; + +def counter($rule; $actual; $status): + $rule | {actual: (if ($actual | valid($rule.unit)) then $actual else null end), unit, threshold, direction, + status: (if $status != null then $status + elif $actual == null then "missing" + elif ($actual | valid($rule.unit) | not) then "invalid" + elif $rule.id == 9 then "informational" + elif (if .direction == "at-least" then $actual < .threshold + else $actual > .threshold end) then "outside-threshold" + else "within-threshold" end)}; + # Decode only the input as data. Errors in the comparison itself must propagate. -(try fromjson catch null) as $cell -| (if ($cell | type) == "object" then $cell.outcome else null end) as $outcome -| (["pass", "fail", "unreached", "assisted"] | index($outcome) != null) as $known -| (if $known then $cell.passRule else null end) as $measurements -| ($known and ($measurements == null or ($measurements | type) == "object")) as $readable +(try fromjson catch null | objects // {}) as $decoded +| ($decoded.outcome // null) as $outcome +| (any("pass", "fail", "unreached", "assisted"; . == $outcome)) as $known +| (if $known then $decoded else {} end) as $cell +| ($known and ($cell.passRule == null or ($cell.passRule | type) == "object")) as $readable +| (first($products.products[] | select(.id == $cell.product)) // {}) as $product +| ($product.tier == "supporting" or $product.verifiesTokens == false) as $inapplicable +| (if $product.tier == "supporting" then "inapplicable-supporting" else ($product.t2[$column] // "unknown") end) as $t2 +| hard_conditions($cell; $inapplicable) as $hard +| diagnostic_evidence($cell; $product; $inapplicable) as $diagnostics +| (if ($diagnostics.credits | length) > 0 or ($diagnostics.liveChecks | length) > 0 + then $diagnostics.credits | length else null end) as $diagnostic_count | ($limits | map( . as $rule - | (if $readable then $measurements[$rule.name] else null end) as $actual - | ($actual | valid($rule.unit)) as $valid - | {key: $rule.name, value: { - actual: (if $valid then $actual else null end), - threshold, direction, - status: (if $readable | not then "invalid" - elif $actual == null then "missing" - elif $valid | not then "invalid" - elif (if .direction == "at-least" then $actual < .threshold - else $actual > .threshold end) then "outside-threshold" - else "within-threshold" end) - }} + | (if $inapplicable or ($rule.id == 8 and ($t2 | startswith("inapplicable-"))) then "inapplicable" + elif $rule.id == 8 and $t2 == "recipe-gap" then "recipe-gap" + elif $rule.id == 8 and $product.id != null and $t2 != "recipe" then "invalid" + elif ($readable | not) and ($rule.id != 10 or $diagnostic_count == null) then "invalid" + else null end) as $status + | (if $status != null then null + elif $rule.id == 10 then $diagnostic_count + else $cell.passRule[$rule.name] end) as $actual + | {key: $rule.name, value: counter($rule; $actual; $status)} ) | from_entries) as $counters +| ([$limits[] | select(.id <= 8) | $counters[.name].status]) as $effort | { outcome: (if $known then $outcome else "unknown" end), - verdict: (if all($counters[]; .status == "within-threshold") then "MET" else "NOT MET" end), + verdicts: { + effort: (if $inapplicable then "INAPPLICABLE" + elif any($effort[]; . == "outside-threshold") or any($hard[]; . == "violated") then "NOT MET" + elif all($effort[]; . == "within-threshold" or . == "inapplicable") + and all($hard[]; . == "held") and $product.id != null then "MET" + else "UNAVAILABLE" end), + diagnostics: ($counters["errors-that-say-what-to-change"].status + | if . == "within-threshold" then "MET" + elif . == "outside-threshold" then "NOT MET" + elif . == "inapplicable" then "INAPPLICABLE" else "UNAVAILABLE" end), + machineTime: ($counters["machine-time-to-t1"].status + | if . == "informational" then "INFORMATIONAL" + elif . == "inapplicable" then "INAPPLICABLE" else "UNAVAILABLE" end) + }, + t2Recipe: $t2, + hardConditions: $hard, + diagnosticEvidence: $diagnostics, counters: $counters } diff --git a/products/platform/journeys/lib.sh b/products/platform/journeys/lib.sh index bc226f9649..70e6404359 100644 --- a/products/platform/journeys/lib.sh +++ b/products/platform/journeys/lib.sh @@ -328,12 +328,25 @@ journey__first_hour_rule() { } journey__first_hour_receipt() { - local column limits + local column limits conditions issuer products="${_journey_products_json:-}" column="$(journey__first_hour_column "$1")" || return 1 + case "$1" in + rstack-dev) issuer=rstack-dev ;; + own-provider) issuer=keycloak ;; + own-provider-thunderid) issuer=thunderid ;; + esac + if [[ -z "$products" ]]; then + journey__yaml_json "$JOURNEY_TABLES_DIR/products.yaml" products + journey__require_schema "$products" registry.journey-products/v1 "$JOURNEY_TABLES_DIR/products.yaml" + fi limits="$(jq -ec --arg column "$column" '.counters | map({ - name, unit, threshold: .[$column], direction: (.direction // "at-most") + id, name, unit, threshold: .[$column], + direction: (if .id == 9 then "informational" else (.direction // "at-most") end) })' <<<"$_journey_first_hour_rule")" || return 1 - jq -eRs --argjson limits "$limits" -f "$JOURNEY_LIB_DIR/first-hour-receipt.jq" "$2" + conditions="$(jq -ec '.hardConditions | map(.id)' <<<"$_journey_first_hour_rule")" || return 1 + jq -eRs --arg column "$column" --arg issuer "$issuer" --argjson limits "$limits" \ + --argjson conditions "$conditions" --argjson products "$products" \ + -f "$JOURNEY_LIB_DIR/first-hour-receipt.jq" "$2" } journey__require_schema() { @@ -1549,11 +1562,12 @@ journey_cell_begin() { _jc_lines=0 _jc_chars=0 _jc_doc_words=0 + _jc_reading_sections='' _jc_idp=0 _jc_certs=0 _jc_refusals=0 _jc_production_refusals=null - _jc_named=null + _jc_diagnostic_checks='{}' _jc_assist_count=0 _jc_seconds=0.000 _jc_concepts='' @@ -1603,6 +1617,7 @@ journey__declare_concepts() { } journey__count_command() { + [[ -n "$1" ]] || return 0 _jc_steps=$((_jc_steps + 1)) _jc_chars=$((_jc_chars + ${#1})) } @@ -2209,35 +2224,40 @@ journey__touch_file() { } } -# journey_write_file PATH [--concepts A,B] < CONTENT: a file the reader -# creates by hand. Counts the file, its lines and its characters. +# journey_write_file PATH [--append] [--concepts A,B] < CONTENT: text the +# reader writes by hand. Count only the supplied text, even when appending. journey_write_file() { - local path=${1:-} counts + local path=${1:-} counts mode=">:raw" [[ $# -eq 0 ]] || shift journey__require_cell journey__require_running journey__require_resolved journey__work_path "$path" + if [[ "${1:-}" == --append ]]; then + [[ -f "$path" ]] || journey__script_error "cannot append to $path: it does not exist" + mode=">>:raw" + shift + fi if [[ "${1:-}" == --concepts ]]; then - [[ $# -ge 2 ]] || journey__script_error "--concepts needs a list" + [[ $# -eq 2 ]] || journey__script_error "--concepts needs a list" journey__declare_concepts "$2" elif [[ $# -gt 0 ]]; then journey__script_error "journey_write_file: unknown option $1" fi counts="$(perl -e ' local $/; my $text = ; $text = "" unless defined $text; - open my $out, ">:raw", $ARGV[0] or die "cannot write $ARGV[0]: $!\n"; + open my $out, $ARGV[1], $ARGV[0] or die "cannot write $ARGV[0]: $!\n"; print {$out} $text; close $out or die "cannot write $ARGV[0]: $!\n"; my $lines = () = $text =~ /\n/g; $lines++ if length($text) && $text !~ /\n\z/; - printf "%d %d\n", $lines, length $text;' "$path")" || journey_harness_failure "cannot write $path" + printf "%d %d\n", $lines, length $text;' "$path" "$mode")" || journey_harness_failure "cannot write $path" journey__touch_file "$path" _jc_lines=$((_jc_lines + ${counts% *})) _jc_chars=$((_jc_chars + ${counts#* })) } # journey_edit_file PATH SEARCH REPLACE [--concepts A,B]: an edit the reader -# makes by hand. SEARCH must occur exactly once. Counts the file, the lines of -# REPLACE and its characters. +# makes by hand. SEARCH must occur exactly once. Count new or changed lines +# and their characters. Reused lines, including starter comments, cost no typing. journey_edit_file() { local path=${1:-} search=${2:-} replace=${3:-} counts [[ $# -ge 3 ]] || journey__script_error "journey_edit_file needs PATH SEARCH REPLACE" @@ -2263,10 +2283,27 @@ journey_edit_file() { substr($text, index($text, $search), length $search) = $replace; open my $out, ">:raw", $path or die "cannot write $path: $!\n"; print {$out} $text; close $out or die "cannot write $path: $!\n"; - my $lines = () = $replace =~ /\n/g; $lines++ if length($replace) && $replace !~ /\n\z/; - printf "%d %d\n", $lines, length $replace;' "$path" "$search" "$replace")" || + my %existing; + for my $line ($search =~ /[^\n]*\n|[^\n]+$/g) { + chomp $line; + $existing{$line}++; + } + my ($lines, $characters) = (0, 0); + for my $line ($replace =~ /[^\n]*\n|[^\n]+$/g) { + my $content = $line; + chomp $content; + if ($existing{$content}) { + $existing{$content}--; + next; + } + $lines++; + $characters += length $line; + } + printf "%d %d\n", $lines, $characters;' "$path" "$search" "$replace")" || journey__script_error "cannot edit $path" - journey__touch_file "$path" + if [[ "$search" != "$replace" ]]; then + journey__touch_file "$path" + fi _jc_lines=$((_jc_lines + ${counts% *})) _jc_chars=$((_jc_chars + ${counts#* })) } @@ -2422,9 +2459,8 @@ 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. The -# production-refusals counter records the initial comparison once and adds -# its measured count to the total refusals. +# documentation-words or refusals. 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 @@ -2440,29 +2476,44 @@ journey_count() { _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)) - ;; *) journey__script_error "journey_count: unknown counter $counter" ;; esac } +# journey_diagnostic CONTROL verified|unverified: record an issuer control +# after the ordinary request was refused. Only an actionable answer credits it. +journey_diagnostic() { + local control=${1:-} status=${2:-} + journey__require_cell + case "$control" in + wrong-audience | missing-scope | expired-token) ;; + *) journey__script_error "unknown planted mistake $control" ;; + esac + [[ "$status" == verified || "$status" == unverified ]] || + journey__script_error "journey_diagnostic needs verified or unverified" + _jc_diagnostic_checks="$(jq -c --arg control "$control" --arg status "$status" \ + 'if .[$control] == "verified" then . else .[$control] = $status end' <<<"$_jc_diagnostic_checks")" || + journey_harness_failure "cannot record the $control diagnostic" +} + journey__counters_json() { local _jr_json _jr_json="$(jq -cn \ --argjson steps "$_jc_steps" --argjson files "$_jc_files" --argjson lines "$_jc_lines" \ --argjson characters "$_jc_chars" --argjson words "$_jc_doc_words" --argjson idp "$_jc_idp" \ - --argjson certificates "$_jc_certs" --argjson refusals "$_jc_refusals" --argjson named "$_jc_named" \ + --argjson certificates "$_jc_certs" --argjson refusals "$_jc_refusals" --argjson checks "$_jc_diagnostic_checks" \ --argjson assists "$_jc_assist_count" --argjson seconds "$_jc_seconds" \ - --arg concepts "$_jc_concepts" --arg files_list "$_jc_touched" --argjson model "$_journey_model_json" \ + --arg reading "$_jc_reading_sections" --arg concepts "$_jc_concepts" --arg files_list "$_jc_touched" --argjson model "$_journey_model_json" \ '($concepts | split("\n") | map(select(length > 0))) as $c | { steps: $steps, filesTouched: $files, files: ($files_list | split("\n") | map(select(length > 0))), linesWritten: $lines, charactersTyped: $characters, documentationWords: $words, + readingSections: ($reading | split("\n") | map(select(length > 0))), identityProviderChanges: $idp, certificatesMade: $certificates, concepts: $c, conceptCount: ($c | length), refusalsMet: $refusals, assistsUsed: $assists, - errorsThatSayWhatToChange: $named, machineSeconds: $seconds, + errorsThatSayWhatToChange: (if ($checks | length) == 0 then null + else [$checks[] | select(. == "verified")] | length end), + machineSeconds: $seconds, readerMinutesModelled: (( $characters / $model.typingCharactersPerMinute + $words / $model.readingWordsPerMinute @@ -2474,6 +2525,49 @@ journey__counters_json() { printf -v "$1" '%s' "$_jr_json" } +# Count the maintained prose assigned to the current step. Record the section +# IDs in the receipt so the estimate can be reproduced at the run revision. +journey_read_recipe() { + local section words + journey__require_cell + for section in "$@"; do + journey__in_list "$section" "$_jc_reading_sections" && continue + words=$(perl -e ' + my ($section, $path) = @ARGV; + open my $doc, "<", $path or die "cannot read $path: $!\n"; + my ($active, $count) = (0, 0); + while (<$doc>) { + if (/^## (.+)\s*$/) { + $active = ($1 eq $section); + next; + } + $count += () = /\S+/g if $active; + } + die "missing recipe section $section\n" unless $count; + print $count; + ' "$section" "$JOURNEY_LIB_DIR/first-hour-reading.md") || + journey_harness_failure "cannot count recipe reading for $section" + journey_count documentation-words "$words" + _jc_reading_sections+="$section"$'\n' + done +} + +# Count actionable audience refusals, scoped to TRACE when supplied. Products +# use either structured JSON or tracing's text formatter for operator logs. +journey_audience_remedies() { + local trace=$1 + shift + jq -Rn --arg trace "$trace" ' + def text_fields: + gsub("\u001b\\[[0-9;]*m"; "") + | capture("request refused decision=\"(?refused)\" failed_check=\"(?token-audience)\" suppressed=[0-9]+ remedy=\"(?[^\"]*)\" trace_id=(?[0-9a-f]{32})( |$)"); + reduce (inputs as $line | ($line | try fromjson catch null) + | if . == null then $line | text_fields else .fields end + | select(($trace == "" or .trace_id == $trace) + and .decision == "refused" and .failed_check == "token-audience" + and ((.remedy // "") | contains("aud claim") and contains("audience")))) as $entry (0; . + 1)' "$@" +} + # journey_reached t1|t2: the open cell reached an end point of the pass rule # (t1: the first 2xx authenticated read; t2: the hour). Snapshots the counters. journey_reached() { @@ -2496,7 +2590,7 @@ journey_reached() { # A cell that neither failed nor was unreached must have passed the journey's # last step. journey_cell_end() { - local outcome total receipt public verdict + local outcome total receipt public first_hour journey__require_cell journey__require_resolved if [[ $_jc_failed -eq 1 ]]; then @@ -2517,7 +2611,7 @@ journey_cell_end() { --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" \ + --argjson total "$total" --argjson diagnosticChecks "$_jc_diagnostic_checks" \ 'def opt: if . == "" then null else . end; { product: $product, outcome: $outcome, step: ($step | opt), code: ($code | opt), reason: ($reason | opt), @@ -2533,7 +2627,9 @@ 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 } - } + (if $journey == "promote" then {$productionRefusals} else {} end)' \ + } + (if $journey == "promote" then {$productionRefusals} + elif ($diagnosticChecks | length) > 0 then {$diagnosticChecks} + 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" @@ -2542,9 +2638,11 @@ journey_cell_end() { mkdir -p -- "$public" || journey_harness_failure "cannot create the public first-hour directory" printf '%s\n' "$receipt" >"$public/cell.json" || journey_harness_failure "cannot write the public first-hour cell of $_jc_product" - verdict="$(jq -er '.verdict | select(. == "MET" or . == "NOT MET")' <<<"$receipt")" || - journey_harness_failure "cannot read the first-hour verdict of $_jc_product" - journey__say "$_jc_product first-hour comparison: $verdict (functional outcome: $outcome)" + first_hour="$(jq -er ' + "effort: \(.verdicts.effort), diagnostics: \(.verdicts.diagnostics), machine time: \(.verdicts.machineTime)" + + (if .t2Recipe == "recipe-gap" then " (T2 recipe gap)" else "" end)' <<<"$receipt")" || + journey_harness_failure "cannot read the first-hour verdicts of $_jc_product" + journey__say "$_jc_product first-hour $first_hour (functional outcome: $outcome)" fi _journey_done_cells+="$_jc_product"$'\n' _jc_open=0 @@ -2578,15 +2676,21 @@ journey__verdicts() { # journey_finish: compare every cell with the mode's requirement, write # summary.json, print one line per cell and exit with the journey's status. journey_finish() { - local product cells verdicts rows strict='' code=0 missing='' + local product cells verdicts rows strict='' code=0 missing='' collect='.' local -a files=() line=() [[ $_jc_open -eq 0 ]] || journey__script_error "the cell of $_jc_product is still open at journey_finish" for product in "${JOURNEY_PRODUCTS[@]}"; do journey__in_list "$product" "$_journey_done_cells" || missing+=" $product" files+=("$JOURNEY_OUT/$product/cell.json") + if journey__first_hour_column "$JOURNEY_NAME" >/dev/null; then + files+=("$JOURNEY_OUT/public-cell-receipts/$product/cell.json") + fi done [[ -z "$missing" ]] || journey__script_error "the journey recorded no cell for:$missing" - cells="$(jq -s '.' "${files[@]}")" || journey_harness_failure "cannot read the cell files" + if journey__first_hour_column "$JOURNEY_NAME" >/dev/null; then + collect='[range(0; length; 2) as $i | .[$i] + {firstHour: .[$i + 1]}]' + fi + cells="$(jq -s "$collect" "${files[@]}")" || journey_harness_failure "cannot read the cell files" journey__verdicts "$cells" verdicts jq -n --arg journey "$JOURNEY_NAME" --arg run "$JOURNEY_RUN_ID" --arg mode "$JOURNEY_MODE" \ --argjson strict "$JOURNEY_STRICT" --arg assists "$JOURNEY_ASSISTS" --argjson cells "$verdicts" \ diff --git a/products/platform/journeys/own-provider.sh b/products/platform/journeys/own-provider.sh index 54bfa29d68..5711a1ac25 100755 --- a/products/platform/journeys/own-provider.sh +++ b/products/platform/journeys/own-provider.sh @@ -1183,7 +1183,7 @@ step_prepare() { 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" + journey_write_file "$RUNTIME_FILE" --append < <(printf '\n%s' "$hook_dest") ;; casework) reader_command prepare --concepts project -- "$TOOL_BIN" init "$PROJECT" @@ -1471,7 +1471,7 @@ step_issuer() { " uri: $TID_ISSUER/oauth2/jwks" jwks-uri edit "$RUNTIME_FILE" " - ES256" " - RS256" # Prove default production posture still refuses local assurance. - journey_step issuer -- assert_evidence_production_refuses "evidencectl check" -- \ + journey_step issuer --typed '' -- assert_evidence_production_refuses "evidencectl check" -- \ "$TOOL_BIN" check "$PROJECT" --target "$RUNTIME_FILE" --format json || journey_harness_failure "Evidence production check did not refuse local assurance" # Continue under explicit development posture as Evidence's local contract requires. @@ -1486,7 +1486,7 @@ step_issuer() { journey_harness_failure "cannot copy Evidence bundle to $installed" seal_directory "$installed" # Prove runtime default production check also still refuses local posture settings. - journey_step issuer -- assert_evidence_production_refuses "evidence check" -- \ + journey_step issuer --typed '' -- assert_evidence_production_refuses "evidence check" -- \ "$SERVER_BIN" check --runtime-config "$candidate/runtime.yaml" || journey_harness_failure "Evidence runtime production check did not refuse local posture" mkdir -p -- "$PROJECT/.generated/audit" @@ -1623,36 +1623,35 @@ breg_schema_test_credentials() { fi 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"; - } + 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" - ) + } + 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" >"$credentials_file" || + journey_harness_failure "cannot prepare the BReg schema test credentials" } # database_step STEP TYPED -- COMMAND...: a database step and its blockers. @@ -1848,7 +1847,7 @@ step_start() { 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 -- \ + journey_ready start adapter-source --typed '' --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" fi @@ -2053,7 +2052,7 @@ check_wrong_kind() { token_has_scalar_audience WRONG_KIND_TOKEN "$AUDIENCE" || journey_harness_failure "the Documents wrong-kind ThunderID token lacks string scalar audience $AUDIENCE" else - journey_http call --form grant_type=client_credentials --form client_id=case-portal \ + journey_http call --typed '' --form grant_type=client_credentials --form client_id=case-portal \ --form-secret client_secret=client-documents-wrong-kind \ --capture-secret .access_token WRONG_KIND_TOKEN POST "$token_url" || journey_harness_failure "Keycloak refused the Documents wrong-kind service credentials" @@ -2063,7 +2062,7 @@ check_wrong_kind() { ;; *) return 0 ;; esac - journey_http call --bearer WRONG_KIND_TOKEN --expect-status 403 GET "http://127.0.0.1:$PORT$path" && + journey_http call --typed '' --bearer WRONG_KIND_TOKEN --expect-status 403 GET "http://127.0.0.1:$PORT$path" && [[ "$JOURNEY_HTTP_PROBLEM_CODE" == "$problem" ]] || journey_harness_failure "$CELL returned HTTP $JOURNEY_HTTP_STATUS ($JOURNEY_HTTP_PROBLEM_CODE) for the wrong-kind service account" } @@ -2072,6 +2071,7 @@ check_wrong_kind() { # must refuse closed on missing bearer and on a real ThunderID token minted for # a different audience. check_thunderid_negative_auth() { + local trace before=0 local -a options=() case "$CELL" in messaging) @@ -2086,10 +2086,38 @@ check_thunderid_negative_auth() { --data-file "$WORK/adapter-call-body.json") ;; esac - journey_http call --expect-status 401 "${options[@]+"${options[@]}"}" "$CALL_METHOD" "http://127.0.0.1:$PORT$CALL_PATH" || + journey_http call --typed '' --expect-status 401 "${options[@]+"${options[@]}"}" "$CALL_METHOD" "http://127.0.0.1:$PORT$CALL_PATH" || journey_harness_failure "$CELL did not refuse a missing bearer with HTTP 401 (got HTTP $JOURNEY_HTTP_STATUS)" - journey_http call --bearer WRONG_AUDIENCE_TOKEN --expect-status 401 "${options[@]+"${options[@]}"}" "$CALL_METHOD" "http://127.0.0.1:$PORT$CALL_PATH" || + # These two products do not expose a correlatable trace in both places. + # Each isolated fixture server receives only this control between snapshots. + case "$CELL" in + adapter | documents) before=$(thunderid_audience_count '') ;; + esac + journey_http call --typed '' --bearer WRONG_AUDIENCE_TOKEN --expect-status 401 "${options[@]+"${options[@]}"}" "$CALL_METHOD" "http://127.0.0.1:$PORT$CALL_PATH" || journey_harness_failure "$CELL did not refuse a wrong-audience ThunderID token with HTTP 401 (got HTTP $JOURNEY_HTTP_STATUS)" + case "$CELL" in + adapter | documents) trace='' ;; + *) trace=$(jq -er '.traceId | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || { + journey_diagnostic wrong-audience unverified + return 0 + } ;; + esac + if journey_poll 5 -- thunderid_audience_logged "$trace" "$before"; then + journey_diagnostic wrong-audience verified + else + journey_diagnostic wrong-audience unverified + fi +} + +thunderid_audience_count() { + refresh_server_log + journey_audience_remedies "$1" "$SERVER_LOG_OUT" "$SERVER_LOG_ERR" +} + +thunderid_audience_logged() { + local after + after=$(thunderid_audience_count "$1") || return 1 + [[ "$after" -eq $(($2 + 1)) ]] } # Match the claims check to the trace from the control's HTTP response. @@ -2106,7 +2134,7 @@ breg_no_mapper_control() { 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 call --typed '' --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") || @@ -2138,6 +2166,7 @@ step_call() { esac call_request || status=$? if [[ $status -eq 0 ]]; then + [[ "$CALL_METHOD" != GET ]] || journey_reached t1 if [[ "$ISSUER_KIND" == thunderid ]]; then check_thunderid_negative_auth REACHED_AUTH_PRODUCTS+=("$CELL") @@ -2147,7 +2176,6 @@ step_call() { breg_no_mapper_control fi journey_pass call - [[ "$CALL_METHOD" != GET ]] || journey_reached t1 return 0 fi [[ "$JOURNEY_HTTP_STATUS" != 000 ]] || @@ -2291,14 +2319,13 @@ assert_casework_task_grant_binding_refusal() { documents_hook() { local receipt=$WORK/document-hook.json fixture=$WORK/rejected.pdf local origin=http://127.0.0.1:$PORT upload document version digest receiver_out='' - journey_write_file "$fixture" < <(printf '%%PDF-1.7\n%%%%EOF\n') + printf '%%PDF-1.7\n%%%%EOF\n' >"$fixture" digest=$(perl -MDigest::SHA -e 'print Digest::SHA->new(256)->addfile($ARGV[0], "b")->hexdigest' "$fixture") - journey_write_file "$WORK/reserve.json" < <( - jq -cn --arg subject "$DOCUMENTS_SUBJECT" --arg digest "sha256:$digest" \ - --argjson length "$(wc -c <"$fixture")" \ - '{policyId:"institutional-custody", custodian:{subject:$subject}, - expectedDigest:$digest, length:$length, mediaType:"application/pdf"}' - ) + jq -cn --arg subject "$DOCUMENTS_SUBJECT" --arg digest "sha256:$digest" \ + --argjson length "$(wc -c <"$fixture")" \ + '{policyId:"institutional-custody", custodian:{subject:$subject}, + expectedDigest:$digest, length:$length, mediaType:"application/pdf"}' >"$WORK/reserve.json" || + journey_harness_failure "cannot prepare the document reservation" journey_start hook receiver -- python3 "$PROJECTS_DIR/documents-receiver.py" "$DOCUMENTS_RECEIVER_PORT" "$fixture" \ "$SECRETS/documents-content-verifier-authorization" "$SECRETS/documents-owning-system-events-hmac" "$receipt" || journey_harness_failure "the Documents verifier and hook receiver exited" @@ -2311,16 +2338,16 @@ documents_hook() { journey_http hook --bearer ACCESS_TOKEN --header 'Content-Type: application/pdf' \ --data-file "$fixture" PUT "$origin$upload" || journey_harness_failure "the Documents upload failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" - journey_ready hook receiver --timeout 45 -- test -s "$receipt" || + journey_ready hook receiver --typed '' --timeout 45 -- test -s "$receipt" || journey_harness_failure "the receiver did not accept the signed Documents hook" # shellcheck disable=SC2016 # jq binds its own variables - journey_step hook -- jq -e --arg document "$document" --arg version "$version" \ + journey_step hook --typed '' -- jq -e --arg document "$document" --arg version "$version" \ '.source == "urn:registrystack:documents:civil-registry-documents" and .type == "document-version-rejected" and .data == {documentId:$document,versionId:$version,policyId:"institutional-custody",policyVersion:"1"}' "$receipt" || journey_harness_failure "the signed hook did not describe the rejected Documents upload" journey_stop hook receiver || journey_harness_failure "the Documents receiver ignored SIGTERM" - journey_step hook -- assert_signed_hook_acceptance "$receiver_out" /document-events document-version-rejected || + journey_step hook --typed '' -- assert_signed_hook_acceptance "$receiver_out" /document-events document-version-rejected || journey_harness_failure "the Documents signed hook acceptance record did not confirm HMAC receiver authority without inbound credential headers" } @@ -2334,7 +2361,7 @@ breg_hook() { "$BREG_HOOK_PORT" /events contact-created "$SECRETS/breg-contact-sink-hmac" "$receipt" || journey_harness_failure "the BReg hook receiver exited" receiver_out=$JOURNEY_STEP_STDOUT - journey_ready hook breg-hook-receiver --timeout 30 -- \ + journey_ready hook breg-hook-receiver --typed '' --timeout 30 -- \ curl --silent --show-error --fail --output /dev/null "http://127.0.0.1:$BREG_HOOK_PORT/ready" || journey_harness_failure "the BReg hook receiver did not answer /ready" journey_http hook --expect-status 201 --bearer ACCESS_TOKEN \ @@ -2344,10 +2371,10 @@ breg_hook() { --capture .data.recordId record_id \ POST "$origin/v1/records/contacts" || journey_harness_failure "BReg contact creation failed (HTTP $JOURNEY_HTTP_STATUS, $JOURNEY_HTTP_PROBLEM_CODE)" - journey_ready hook breg-hook-receiver --timeout 45 -- test -s "$receipt" || + journey_ready hook breg-hook-receiver --typed '' --timeout 45 -- test -s "$receipt" || journey_harness_failure "the BReg hook receiver did not accept the signed contact-created hook" # shellcheck disable=SC2016 # jq binds its own variables - journey_step hook -- jq -e --arg record "$record_id" \ + journey_step hook --typed '' -- jq -e --arg record "$record_id" \ '.type == "contact-created" and .data.recordId == $record and .data.recordType == "contact" @@ -2356,13 +2383,13 @@ breg_hook() { "$receipt" || journey_harness_failure "the signed BReg hook did not describe the created contact" 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_step hook --typed '' -- 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_step hook --typed '' -- 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 @@ -2650,21 +2677,21 @@ JSON "$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 -- \ + journey_ready hook comp-hook-receiver --typed '' --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" - journey_ready hook comp-breg --timeout 90 -- \ + journey_ready hook comp-breg --typed '' --timeout 90 -- \ curl --silent --show-error --fail --output /dev/null "$breg_url/ready" || journey_harness_failure "composed BReg did not become ready" journey_start hook comp-casework --settle 2 -- "$cw_bin" --posture development --runtime-config "$cw_rt" serve || journey_harness_failure "composed Casework failed to start" comp_cw_out=$JOURNEY_STEP_STDOUT - journey_ready hook comp-casework --timeout 90 -- \ + journey_ready hook comp-casework --typed '' --timeout 90 -- \ curl --silent --show-error --fail --output /dev/null "$cw_url/ready" || journey_harness_failure "composed Casework did not become ready" # Verify Casework serves its live task-authority JWKS document (used by ThunderID exchange). @@ -2675,7 +2702,7 @@ JSON 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 -- \ + journey_ready hook comp-scheduling --typed '' --timeout 90 -- \ curl --silent --show-error --fail --output /dev/null "$sched_url/ready" || journey_harness_failure "composed Scheduling did not become ready" fi @@ -2818,11 +2845,11 @@ JSON journey_process_log comp-casework comp_cw_err casework_refusal_counts "$comp_cw_out" total_refusals_before binding_refusals_before || journey_harness_failure "cannot read composed Casework refusal baseline from $comp_cw_out" - journey_step hook -- assert_wrong_agent_grant_refused "$JOURNEY_ISSUER_BIN" "$comp_tid_root" "$task_conn" other-agent "$grant_id" || + journey_step hook --typed '' -- assert_wrong_agent_grant_refused "$JOURNEY_ISSUER_BIN" "$comp_tid_root" "$task_conn" other-agent "$grant_id" || journey_harness_failure "wrong agent other-agent did not produce the exact Casework grant refusal (see $JOURNEY_STEP_STDERR)" # shellcheck disable=SC2034 # journey_process_log sets comp_cw_err while refreshing comp_cw_out journey_process_log comp-casework comp_cw_err - journey_step hook -- assert_casework_task_grant_binding_refusal "$comp_cw_out" "$total_refusals_before" "$binding_refusals_before" || + journey_step hook --typed '' -- assert_casework_task_grant_binding_refusal "$comp_cw_out" "$total_refusals_before" "$binding_refusals_before" || journey_harness_failure "composed Casework did not log the exact task-grant-binding refusal for other-agent (see $JOURNEY_STEP_STDERR)" # 12) Exchange the approved grant for task-agent via ThunderID RFC 8693 exchange @@ -2942,16 +2969,16 @@ JSON 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_ready hook comp-hook-receiver --typed '' --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" \ + journey_step hook --typed '' -- 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_step hook --typed '' -- 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 @@ -3035,6 +3062,7 @@ walk_product() { journey_cell_end return 0 fi + journey_read_recipe own-provider "$ISSUER_KIND" "$product" journey_workdir "$product" WORK PROJECT=$WORK/$product recipe "$product" diff --git a/products/platform/journeys/products.yaml b/products/platform/journeys/products.yaml index 25d7eb2139..44d9404cc1 100644 --- a/products/platform/journeys/products.yaml +++ b/products/platform/journeys/products.yaml @@ -12,6 +12,10 @@ # # usesPostgres, verifiesTokens and rstackDevPlan describe `main`. A change # that changes one edits the row in the same commit. +# t2 describes the maintained write, restart and readback recipe by path. +# verifiedIsolatedDiagnostics links each documented control to a scoped check +# with a recorded passing result. Maintain the credits with the checks and the +# diagnostics they assert. schema: registry.journey-products/v1 @@ -33,6 +37,12 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-breg/tests/authentication_refusals.rs#every_authentication_refusal_is_counted_logged_and_unchanged_on_the_wire: [wrong-audience, expired-token] + crates/registry-breg/tests/concealment_refusals.rs#every_concealed_read_refusal_is_counted_logged_and_unchanged_on_the_wire: [missing-scope] - id: casework tier: primary binary: casework @@ -43,6 +53,11 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe-gap + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-casework/tests/refusal_golden.rs#authentication_and_profile_refusals_match_the_checked_in_answers: [wrong-audience, missing-scope, expired-token] - id: messaging tier: primary binary: messaging @@ -53,6 +68,11 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-messaging/src/http.rs#each_refusal_is_counted_and_logged_under_the_check_that_failed: [wrong-audience, missing-scope, expired-token] - id: evidence tier: primary binary: evidence @@ -63,6 +83,12 @@ products: usesPostgres: false verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe-gap + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-evidence/src/refusal_recording_tests.rs#every_refusal_is_counted_logged_once_by_its_check_and_answered_as_before: [wrong-audience, expired-token] + crates/registry-evidence/src/refusal_recording_tests.rs#a_scope_refusal_logs_the_declared_values_and_none_of_the_tokens: [missing-scope] - id: scheduling tier: primary binary: scheduling @@ -73,6 +99,11 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe-gap + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-scheduling/tests/postgres_commitments.rs#catalogue_fault_controls_name_the_claim_or_setting_to_change: [wrong-audience, missing-scope, expired-token] - id: documents tier: primary binary: documents @@ -83,6 +114,12 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-documents/tests/refusal_golden.rs#every_refusal_is_counted_and_logged_under_the_check_it_failed: [wrong-audience, expired-token] + crates/registry-documents/tests/refusal_golden.rs#a_scope_refusal_line_names_the_declared_values_and_none_of_the_tokens: [missing-scope] - id: coordinator tier: primary binary: coordinator @@ -93,6 +130,11 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-coordinator/tests/refusal_golden.rs#production_caller_refusals_match_the_golden: [wrong-audience, missing-scope, expired-token] - id: adapter tier: primary binary: adapter @@ -103,6 +145,12 @@ products: usesPostgres: true verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: recipe-gap + ownProvider: recipe-gap + verifiedIsolatedDiagnostics: + crates/registry-adapter/tests/facade_refusals.rs#every_refusal_keeps_its_answer_and_is_counted_and_logged_under_its_check: [wrong-audience, expired-token] + crates/registry-adapter/tests/facade_refusals.rs#a_served_scope_refusal_logs_the_verifying_issuers_scope_claim: [missing-scope] - id: render tier: primary binary: registry-render @@ -113,6 +161,11 @@ products: usesPostgres: false verifiesTokens: true rstackDevPlan: true + t2: + rstackDev: inapplicable-stateless + ownProvider: inapplicable-stateless + verifiedIsolatedDiagnostics: + crates/registry-render/src/server.rs#each_refusal_is_counted_and_logged_under_its_check: [wrong-audience, missing-scope, expired-token] - id: discovery tier: primary binary: discovery @@ -123,6 +176,9 @@ products: usesPostgres: false verifiesTokens: false rstackDevPlan: true + t2: + rstackDev: inapplicable-public-index + ownProvider: inapplicable-public-index - id: breg-mcp tier: supporting parent: breg diff --git a/products/platform/journeys/rstack-dev.sh b/products/platform/journeys/rstack-dev.sh index a9a9a8b442..9c5029ea4a 100755 --- a/products/platform/journeys/rstack-dev.sh +++ b/products/platform/journeys/rstack-dev.sh @@ -436,8 +436,7 @@ write_keep() { 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") + options+=(--expect-status 202) ;; scheduling) local config @@ -462,11 +461,17 @@ write_keep() { esac local saved_id - printf '%s\n' "$body" | journey_write_file "$work/keep-body.json" - local step=keep write_path=$path + case "$product" in + coordinator | messaging) printf '%s\n' "$body" >"$work/keep-body.json" ;; + *) journey_write_file "$work/keep-body.json" <<<"$body" ;; + esac + local step=keep write_path=$path reader_url [[ "$product" != breg ]] || step=hook [[ "$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" + printf -v reader_url '%q' "$url$write_path" + journey_http "$step" "${options[@]}" --data-file "$work/keep-body.json" --capture "$field" saved_id \ + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-keep' --json @keep-body.json $reader_url" \ + "$method" "$url$write_path" || unexpected_answer "$step" case "$product" in breg | coordinator | messaging) KEEP_PATH=$path/$saved_id ;; casework) KEEP_PATH=$path/$saved_id ;; @@ -504,8 +509,10 @@ run_url() { # registered as a secret and is never written to a saved file. issue_token() { local step=$1 run=$2 person=$3 variable=$4 status=0 header_file line - journey_step "$step" --concepts test-person,header-file,short-lived-token \ - --typed "rstack dev token $run --as $person" -- rstack_dev token "$run" --as "$person" || status=$? + local -a reader_options=(--concepts "test-person,header-file,short-lived-token" + --typed "rstack dev token $run --as $person") + if [[ "${5:-}" == control ]]; then reader_options=(--typed ''); fi + journey_step "$step" "${reader_options[@]}" -- rstack_dev token "$run" --as "$person" || status=$? [[ $status -eq 0 ]] || return "$status" header_file=$(jq -er '.credentials[0].header_file' "$JOURNEY_STEP_STDOUT") || journey_harness_failure "the token report names no header file; see $JOURNEY_STEP_STDOUT" @@ -515,32 +522,47 @@ 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. +# Reuse the generated staff identity. Current plans narrow its derived scopes +# with a token fixture. Released plans with direct grants use a shared inert scope. prepare_casework_scope_probe() { perl -0pi -e ' + if ($runtime) { + if ($role_based) { + my $scope = qr/^( staff:\n(?:^ {4}[^\n]*\n)*? requiredScopes: \[)casework:staff\]$/m; + s/$scope/${1}casework:staff, casework:diagnostic-control]/ or die "expected generated Casework staff scopes\n"; + } + next; + } + $runtime = 1; 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"; + $role_based = ($staff =~ /^ roles:/m); + if ($role_based) { + $control .= " tokenFixtures:\n casework:\n scopes: [casework:diagnostic-control]\n"; + } else { + $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 || + issue_token call "$run" staff-missing-scope control control || journey_harness_failure "cannot issue the Casework missing-scope control" - journey_http call --expect-status 403 --bearer control GET "$url$path" || + journey_http call --typed '' --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 + | .traceId | strings | select(test("^[0-9a-f]{32}$"))' "$JOURNEY_STEP_STDOUT") || { + journey_diagnostic missing-scope unverified + return 0 + } # shellcheck disable=SC2016 # jq binds $trace. if journey_poll 5 -- jq -Rse --arg trace "$trace" ' first(split("\n")[] | fromjson? | .fields | @@ -548,7 +570,9 @@ record_casework_scope_probe() { 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 + journey_diagnostic missing-scope verified + else + journey_diagnostic missing-scope unverified fi } @@ -574,6 +598,7 @@ walk_product() { journey_cell_end return 0 fi + journey_read_recipe rstack-dev "$product" journey_workdir "$product" work project=$work/project @@ -620,7 +645,7 @@ walk_product() { 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" || + prepare_casework_scope_probe "$project/dev.yaml" "$project/casework.yaml" || journey_harness_failure "cannot prepare the Casework missing-scope control" fi ;; @@ -689,7 +714,7 @@ walk_product() { 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") + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:send-a-reminder-sms' --json @call-body.json $url$CALL_PATH") ;; esac journey_http call "${call_options[@]}" "$CALL_METHOD" "$url$CALL_PATH" || status=$? @@ -711,6 +736,9 @@ walk_product() { # The BReg and Documents writes also test retention after restart. case "$product" in + breg | coordinator | documents | messaging) journey_read_recipe "$product-keep" ;; + esac + case "$product" in breg) local sink write_keep "$product" "$work" "$project" "$url" "$run" @@ -720,7 +748,7 @@ walk_product() { 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 + journey_http hook --typed '' 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 @@ -769,18 +797,21 @@ walk_product() { journey_harness_failure "the keep start of $product did not skip every authored journey" issue_token keep "$RUN" "$KEEP_PERSON" token2 local -a keep_options=(--bearer token2) - local method=GET + local method=GET keep_url if [[ "$product" == casework ]]; then KEEP_PATH+='?accessProfile=requester' fi + keep_url="$(run_url "$product")$KEEP_PATH" if [[ "$product" == adapter ]]; then # The sole write route returns its retained response for the # same request and key even with the upstream offline. method=POST - keep_options+=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-keep' --data-file "$work/keep-body.json") + keep_options+=(--header 'Content-Type: application/json' --header 'Idempotency-Key: journey-keep' + --data-file "$work/keep-body.json" + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-keep' --json @keep-body.json $keep_url") fi status=0 - journey_http keep "${keep_options[@]}" "$method" "$(run_url "$product")$KEEP_PATH" || status=$? + journey_http keep "${keep_options[@]}" "$method" "$keep_url" || status=$? if [[ $status -ne 0 ]]; then if [[ "$JOURNEY_HTTP_STATUS" == 404 ]]; then journey_fail keep journey.keep.state-lost @@ -804,7 +835,7 @@ walk_product() { journey_reached t1 fi if [[ -n "$audit" ]]; then - journey_step keep -- audit_was_appended "$work/audit-before-restart.jsonl" "$audit" + journey_step keep --typed '' -- 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. @@ -913,7 +944,7 @@ 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 + journey_http hook --typed '' 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" } @@ -931,21 +962,22 @@ documents_ready_hook() { 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') + printf '%%PDF-1.7\n%%%%EOF\n' >"$pdf" 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"}' - ) + jq -cn --arg digest "$digest" --argjson length "$(wc -c <"$pdf")" \ + '{policyId:"institutional-custody", custodian:{subject:"starter-citizen"}, + expectedDigest:$digest, length:$length, mediaType:"application/pdf"}' >"$reserve" || + journey_harness_failure "cannot prepare the document reservation" journey_http hook --expect-status 201 --bearer "$bearer" --header 'Content-Type: application/json' \ --header 'Idempotency-Key: journey-document-reservation' --data-file "$reserve" \ + --typed "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-document-reservation' --json @document-reserve.json $origin/v1/documents" \ --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' \ + --typed "curl -X PUT -H @HEADER_FILE -H 'Content-Type: application/pdf' --data-binary @retained.pdf $origin$upload" \ --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", diff --git a/products/platform/journeys/test_journey_tables.py b/products/platform/journeys/test_journey_tables.py index 24fc980d49..d4b6146a72 100644 --- a/products/platform/journeys/test_journey_tables.py +++ b/products/platform/journeys/test_journey_tables.py @@ -73,12 +73,39 @@ def test_schema_and_row_keys(self): "usesPostgres", "verifiesTokens", "rstackDevPlan", } for product in self.products: - allowed = keys | ({"parent"} if product["tier"] == "supporting" else set()) + allowed = keys | ({"parent"} if product["tier"] == "supporting" else {"t2"}) + if product["tier"] == "primary" and product["verifiesTokens"]: + allowed.add("verifiedIsolatedDiagnostics") self.assertEqual(set(product), allowed, product["id"]) self.assertIn(product["tier"], TIERS, product["id"]) for flag in ("usesPostgres", "verifiesTokens", "rstackDevPlan"): self.assertIsInstance(product[flag], bool, f"{product['id']}.{flag}") + def test_t2_recipe_scope_by_path(self): + for product in self.products: + if product["tier"] != "primary": + continue + product_id = product["id"] + special = {"render": "inapplicable-stateless", "discovery": "inapplicable-public-index"} + managed = "recipe" if product_id in {"breg", "coordinator", "documents", "messaging"} else "recipe-gap" + self.assertEqual(product["t2"], { + "rstackDev": special.get(product_id, managed), + "ownProvider": special.get(product_id, "recipe-gap"), + }, product_id) + + def test_verified_isolated_diagnostics_name_existing_scoped_checks(self): + for product in self.products: + checks = product.get("verifiedIsolatedDiagnostics", {}) + controls = [] + for source, verified in checks.items(): + filename, test = source.split("#", 1) + self.assertTrue(filename.startswith(f'crates/{product["crate"]}/'), source) + self.assertRegex((REPO / filename).read_text(encoding="utf-8"), rf"fn {re.escape(test)}\(") + controls.extend(verified) + expected = ["expired-token", "missing-scope", "wrong-audience"] + self.assertEqual(sorted(controls), expected if checks else []) + self.assertEqual(bool(checks), product["tier"] == "primary" and product["verifiesTokens"]) + def test_sixteen_unique_runtimes(self): ids = [p["id"] for p in self.products] self.assertEqual(len(ids), len(set(ids)), "duplicate product id") @@ -153,6 +180,7 @@ def test_scheduling_rejects_missing_proof_even_when_stop_passes(self): recipe() { :; } journey_workdir() { WORK=/unused; } journey_cell_begin() { :; } +journey_read_recipe() { :; } journey_cell_end() { printf '%s\n' 'cell ended'; } journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } journey_unreached() { printf '%s\n' "$1 unreached"; } @@ -276,6 +304,12 @@ def test_the_rstack_dev_path_is_never_looser_than_own_provider(self): self.assertLessEqual(counter["rstackDev"], counter["ownProvider"], f"counter {counter['id']}") + def test_each_path_has_its_first_hour_time_budget(self): + counters = {rule["name"]: rule for rule in self.rule["counters"]} + for endpoint, managed, own_provider in (("t1", 10, 30), ("t2", 30, 60)): + rule = counters[f"reader-time-to-{endpoint}-modelled"] + self.assertEqual((rule["rstackDev"], rule["ownProvider"]), (managed, own_provider)) + def test_reader_time_model_constants(self): model = self.rule["readerTimeModel"] self.assertEqual( @@ -399,6 +433,54 @@ def test_scripts_stay_inside_the_allowed_tools(self): self.assertIsNone(FORBIDDEN_IN_SCRIPTS.search(code), f"{script.name}:{number}: {line.strip()}") self.assertIsNone(FORBIDDEN_DOCKER.search(code), f"{script.name}:{number}: {line.strip()}") + def test_first_hour_recipe_reading_covers_every_supported_product(self): + recipe = (TABLES / "first-hour-reading.md").read_text(encoding="utf-8") + sections = re.findall(r"^## ([a-z0-9-]+)\n+([^#]+?)(?=^## |\Z)", recipe, re.M | re.S) + by_id = dict(sections) + self.assertEqual(len(sections), len(by_id)) + expected = { + "rstack-dev", "own-provider", "keycloak", "thunderid", + "breg-keep", "coordinator-keep", "documents-keep", "messaging-keep", + } | { + row["id"] for row in load("products.yaml")["products"] if row["tier"] == "primary" + } + self.assertEqual(set(by_id), expected) + for key, prose in sections: + self.assertGreater(len(prose.split()), 5, key) + for driver, function in [ + ("rstack-dev.sh", "documents_ready_hook"), + ("own-provider.sh", "documents_hook"), + ]: + script = (TABLES / driver).read_text(encoding="utf-8") + self.assertIn("journey_read_recipe", script) + hook = script.split(f"{function}() {{", 1)[1].split("\n}", 1)[0] + self.assertNotIn("journey_write_file", hook, driver) + + def test_audience_remedy_requires_the_rejected_requests_trace(self): + script = (TABLES / "lib.sh").read_text(encoding="utf-8") + function = "journey_audience_remedies" + definition = function + "() {" + script.split(function + "() {", 1)[1].split("\n}", 1)[0] + "\n}" + remedy = "The token's aud claim does not name the audience this issuer entry declares." + trace = "a" * 32 + good = {"trace_id": trace, "decision": "refused", "failed_check": "token-audience", "remedy": remedy} + for format_name in ("json", "text"): + for change in ({}, {"trace_id": "b" * 32}, {"remedy": ""}, {"failed_check": "token-time"}): + fields = good | change + if format_name == "json": + log = json.dumps({"fields": fields}) + "\n" + else: + log = ( + '\x1b[32mINFO\x1b[0m scheduling: request refused decision="refused" ' + f'failed_check="{fields["failed_check"]}" suppressed=0 ' + f'remedy="{fields["remedy"]}" trace_id={fields["trace_id"]}\n' + ) + result = subprocess.run( + ["bash", "-c", definition + '\n' + function + ' "$1" /dev/stdin', "test", trace], + input=log, text=True, capture_output=True, check=False, + ) + self.assertEqual(result.returncode, 0, (format_name, change, result.stderr)) + self.assertEqual(int(result.stdout), int(not change), (format_name, change)) + def test_realm_import_has_no_protocol_mappers(self): realm = TABLES / "keycloak" / "realm.json" if realm.is_file(): @@ -1123,10 +1205,10 @@ def test_planted_scope_counts_only_the_correlated_actionable_diagnostic(self): STATE_DIR=$1 JOURNEY_STEP_STDOUT=$1/response.json issue_token() { :; } -journey_http() { [[ "$*" == "call --expect-status 403 --bearer control GET http://localhost/read" ]]; } +journey_http() { [[ "$1" == call && "$2" == --typed && -z "$3" && "$4" == --expect-status && "$5" == 403 && "$6" == --bearer && "$7" == control && "$8" == GET && "$9" == http://localhost/read ]]; } journey_harness_failure() { printf '%s\n' "$1" >&2; exit 3; } journey_poll() { shift 2; "$@"; } -journey_count() { printf '%s\n' "${2:-1}"; } +journey_diagnostic() { printf '%s %s\n' "$1" "$2"; } record_casework_scope_probe sample http://localhost /read "$1" """ trace = "01a2333e0412314aaf6d6dbbe6fd98c0" @@ -1137,8 +1219,11 @@ def test_planted_scope_counts_only_the_correlated_actionable_diagnostic(self): }), 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")): + for label, overrides, status in ( + ("matching", {}, "verified"), + ("other trace", {"trace_id": "other"}, "unverified"), + ("missing remedy", {"required_scope": ""}, "unverified"), + ): with self.subTest(label=label): (logs / "casework-runtime.log").write_text(json.dumps({"fields": { "trace_id": trace, "failed_check": "scope", "scope_claim": "scope", @@ -1148,7 +1233,7 @@ def test_planted_scope_counts_only_the_correlated_actionable_diagnostic(self): ["bash", "-eu", "-c", probe.group(0) + driver, "casework-scope-count", directory], text=True, timeout=5, ) - self.assertEqual(result.strip(), count) + self.assertEqual(result.strip(), f"missing-scope {status}") def test_planted_scope_fixture_preserves_staff_authority_and_only_omits_required_scope(self): source = (TABLES / "rstack-dev.sh").read_text(encoding="utf-8") @@ -1174,6 +1259,28 @@ def test_planted_scope_fixture_preserves_staff_authority_and_only_omits_required self.assertTrue(control_scopes and set(control_scopes) < set(scopes)) self.assertEqual(people["supervisor"], {"client": "supervisor"}) + def test_planted_scope_fixture_uses_the_generated_staff_role(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) + staff = {"client": "staff", "roles": ["staff"], "subject": "staff"} + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "dev.yaml" + path.write_text(yaml.safe_dump({"people": {"staff": staff}}), encoding="utf-8") + runtime = path.with_name("casework.yaml") + runtime.write_text("accessProfiles:\n staff:\n requiredScopes: [casework:staff]\n", encoding="utf-8") + subprocess.run( + ["bash", "-eu", "-c", prepare.group(0) + '\nprepare_casework_scope_probe "$1" "$2"', + "casework-scope-probe", str(path), str(runtime)], check=True, timeout=5, + ) + people = yaml.safe_load(path.read_text(encoding="utf-8"))["people"] + self.assertEqual(people["staff"], staff) + control = people["staff-missing-scope"] + self.assertEqual(control.pop("tokenFixtures"), {"casework": {"scopes": ["casework:diagnostic-control"]}}) + self.assertEqual(control, staff) + profile = yaml.safe_load(runtime.read_text(encoding="utf-8"))["accessProfiles"]["staff"] + self.assertEqual(profile["requiredScopes"], ["casework:staff", "casework:diagnostic-control"]) + 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")] @@ -1231,7 +1338,7 @@ 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", + "walk_product", "recipe", "write_keep", "hook_received", "breg_hook_matches", "managed_hook_url", "check_managed_hook", "documents_ready_hook", "documents_ready_matches", ): @@ -1280,7 +1387,7 @@ def walk(self, product, delivered): } run_url() { printf '%s\n' 'http://127.0.0.1:49192'; } issue_token() { measure_reader_action "$1"; } -write_keep() { +fake_write_keep() { KEEP_PERSON=$PERSON KEEP_PATH=/retained KEEP_EXPECT=retained-id @@ -1302,7 +1409,7 @@ def walk(self, product, delivered): return fi case "$delivered" in - yes | missing-on-read) record=retained-id ;; + yes | missing-on-read | measure-keep) record=retained-id ;; wrong-record) record=other-id ;; *) printf '%s\n' '[]'; return ;; esac @@ -1350,6 +1457,18 @@ def walk(self, product, delivered): esac } journey_http() { + if [[ "$delivered" == measure-keep ]]; then + local typed="curl -X ${@: -2:1} ${!#}" + local -a arguments=("$@") + local i + for ((i=1; i < ${#arguments[@]}-2; i++)); do + case "${arguments[i]}" in + --typed) typed=${arguments[i+1]}; break ;; + esac + done + journey_step "$1" --typed "$typed" -- true + printf 'typed: %s\n' "$typed" >>"$trace" + fi JOURNEY_STEP_STDOUT=$scratch/response.json if [[ "$CELL" == documents ]]; then case "${!#}" in @@ -1380,6 +1499,12 @@ def walk(self, product, delivered): fi ;; hook) + if [[ "${@: -2:1} ${!#}" == 'POST http://127.0.0.1:49192/v1/records/contacts' ]]; then + [[ -f "$work/keep-body.json" ]] + saved_id=retained-id + printf 'write %s\n' "$CELL" >>"$trace" + return + fi [[ "${!#}" == http://127.0.0.1:49191/received ]] printf '%s\n' 'read sink' >>"$trace" if [[ "$delivered" == missing-on-read ]]; then @@ -1410,6 +1535,9 @@ def walk(self, product, delivered): options=() [[ "$delivered" != first-hour ]] || options+=(--timed) +if [[ "$delivered" != measure-keep ]]; then + write_keep() { fake_write_keep "$@"; } +fi 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" @@ -1423,6 +1551,10 @@ def walk(self, product, delivered): if [[ "$delivered" == first-hour ]]; then jq -r '.toT1.steps' "$scratch/run/$product/cell.json" >>"$trace" fi +if [[ "$delivered" == measure-keep ]]; then + jq -c '[.toT2.linesWritten, .toT2.filesTouched, .toT2.steps, .toT2.charactersTyped]' \ + "$scratch/run/$product/cell.json" >>"$trace" +fi journey_finish """ with tempfile.TemporaryDirectory() as directory: @@ -1488,6 +1620,24 @@ def test_breg_passes_hook_after_payload_arrives(self): 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_retention_charges_the_authored_body_and_write_but_not_the_sink(self): + result, _, trace = self.walk("breg", "measure-keep") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("read sink", trace) + self.assert_retention_counters(trace, lines=1, files=1, body_bytes=95) + self.assertEqual([line.removeprefix("typed: ") for line in trace if line.startswith("typed: ")][1:3], [ + ( + "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-keep' --json @keep-body.json " + "http://127.0.0.1:49192/v1/records/contacts" + ), + "", + ]) + + def assert_retention_counters(self, trace, *, lines, files, body_bytes): + commands = [line.removeprefix("typed: ") for line in trace if line.startswith("typed: ") and line != "typed: "] + commands.extend(("write_starter ./project", "rstack dev stop start-run")) + self.assertEqual(json.loads(trace[-1]), [lines, files, len(commands), sum(map(len, commands)) + body_bytes]) + def test_breg_does_not_pass_hook_without_payload(self): for delivered in ("no", "wrong-record", "missing-on-read"): with self.subTest(delivered=delivered): @@ -1512,6 +1662,23 @@ def test_documents_keeps_the_same_ready_version_after_one_upload(self): self.assertEqual(trace, ["reserve document", "upload document", "poll sink", "read sink", "read ready document", "read ready document"]) + def test_documents_retention_charges_the_reservation_and_upload_syntax(self): + result, _, trace = self.walk("documents", "measure-keep") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("read sink", trace) + self.assertEqual([line.removeprefix("typed: ") for line in trace if line.startswith("typed: ")][1:4], [ + ( + "curl -H @HEADER_FILE -H 'Idempotency-Key:journey-document-reservation' --json @document-reserve.json " + "http://127.0.0.1:49192/v1/documents" + ), + ( + "curl -X PUT -H @HEADER_FILE -H 'Content-Type: application/pdf' --data-binary @retained.pdf " + "http://127.0.0.1:49192/v1/uploads/abcd/content" + ), + "", + ]) + self.assert_retention_counters(trace, lines=0, files=0, body_bytes=0) + def test_documents_refuses_unmatched_capture_or_readback(self): for delivered, diagnostic in ( ("no-sink", "did not report its hook sink"), @@ -1528,6 +1695,48 @@ def test_documents_refuses_unmatched_capture_or_readback(self): self.assertEqual(trace, []) +class OwnProviderFirstRead(unittest.TestCase): + def test_t1_stops_at_the_read_and_total_retains_control_time_and_credit(self): + script = (TABLES / "own-provider.sh").read_text(encoding="utf-8") + match = re.search(r"^step_call\(\) \{\n.*?^\}\n", script, re.M | re.S) + self.assertIsNotNone(match) + driver = r""" +source "$1/lib.sh" +CELL=breg ISSUER_KIND=thunderid CALL_METHOD=GET +REACHED_AUTH_PRODUCTS=() +call_request() { + journey__count_command 'curl reader-route' + journey__add_step_time call 0 2 +} +check_thunderid_negative_auth() { + journey__add_step_time call 0 3 + journey_diagnostic wrong-audience verified +} +check_wrong_kind() { :; } +journey_init own-provider-thunderid --default-expected "$1/expected-failures-thunderid.yaml" -- --product breg --out "$2/run" +journey_cell_begin breg +step_call +journey_pass stop +journey_cell_end +journey_finish +""" + with tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", match.group(0) + driver, + "own-provider-t1", str(TABLES), directory], + env={**os.environ, "JOURNEY_TABLES_DIR": str(TABLES)}, + capture_output=True, text=True, timeout=15, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + cell = json.loads((Path(directory) / "run/breg/cell.json").read_text()) + self.assertEqual(cell["toT1"]["machineSeconds"], 2) + self.assertEqual(cell["total"]["machineSeconds"], 5) + self.assertEqual(cell["toT1"]["steps"], cell["total"]["steps"]) + self.assertEqual(cell["toT1"]["charactersTyped"], cell["total"]["charactersTyped"]) + self.assertIsNone(cell["toT1"]["errorsThatSayWhatToChange"]) + self.assertEqual(cell["passRule"]["errors-that-say-what-to-change"], 1) + + 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()) @@ -2034,49 +2243,199 @@ class FirstHourReceiptTests(unittest.TestCase): def setUpClass(cls): cls.rows = load("first-hour-pass-rule.yaml")["counters"] - def project(self, receipt, path): + def project(self, receipt, path, tables=TABLES): return subprocess.run( ["bash", "-eu", "-c", 'source "$1/lib.sh"; journey__first_hour_rule "$1/first-hour-pass-rule.yaml"; ' + 'journey__first_hour_receipt "$2" /dev/stdin', "bash", str(HERE), path], input=receipt, capture_output=True, text=True, + env={**os.environ, "JOURNEY_TABLES_DIR": str(tables)}, ) - def test_every_threshold_is_reported(self): - for path, column in (("rstack-dev", "rstackDev"), ("own-provider", "ownProvider"), - ("own-provider-thunderid", "ownProvider")): - limits = {row["name"]: row[column] for row in self.rows} - receipt = {"outcome": "pass", "passRule": limits} - passing = self.project(json.dumps(receipt), path) - self.assertEqual(passing.returncode, 0, passing.stderr) - self.assertEqual(json.loads(passing.stdout)["verdict"], "MET") - for row in self.rows: - name, limit = row["name"], row[column] - exceeded = limit - 1 if row.get("direction") == "at-least" else limit + 1 - for value, status in ((None, "missing"), ("1", "invalid"), (True, "invalid"), - (-1, "invalid"), (exceeded, "outside-threshold")): - with self.subTest(path=path, name=name, value=value): - counters = dict(limits) - if value is None: - del counters[name] - else: - counters[name] = value - result = self.project(json.dumps(dict(receipt, passRule=counters)), path) - self.assertEqual(result.returncode, 0, result.stderr) - report = json.loads(result.stdout) - self.assertEqual(report["verdict"], "NOT MET") - self.assertEqual(report["counters"][name], { - "actual": value if status == "outside-threshold" else None, - "threshold": limit, "direction": row.get("direction", "at-most"), - "status": status, - }) - - def test_unreadable_and_missing_measurements_are_reported(self): + def cell(self, column="rstackDev", **fields): + # Shape of receipts written before per-control provenance was recorded. + return { + "product": "breg", "outcome": "pass", "blockers": [], + "total": {"assistsUsed": 0, "certificatesMade": 0, "refusalsMet": 0}, + "passRule": {row["name"]: row[column] for row in self.rows}, + **fields, + } + + def report(self, receipt, path="rstack-dev"): + result = self.project(json.dumps(receipt), path) + self.assertEqual(result.returncode, 0, result.stderr) + return json.loads(result.stdout) + + def test_effort_counters_and_units(self): + for row in self.rows[:8]: + name, limit = row["name"], row["rstackDev"] + for value, status, verdict in ((limit, "within-threshold", "MET"), + (None, "missing", "UNAVAILABLE"), + ("1", "invalid", "UNAVAILABLE"), + (True, "invalid", "UNAVAILABLE"), + (-1, "invalid", "UNAVAILABLE"), + (limit + 1, "outside-threshold", "NOT MET")): + with self.subTest(name=name, value=value): + receipt = self.cell() + receipt["passRule"][name] = value + report = self.report(receipt) + self.assertEqual(report["verdicts"]["effort"], verdict) + self.assertEqual(report["counters"][name], { + "actual": value if status in {"within-threshold", "outside-threshold"} else None, + "threshold": limit, "direction": "at-most", "unit": row["unit"], "status": status, + }) + + def test_provider_time_budgets_and_t2_recipe_gap(self): + name = "reader-time-to-t1-modelled" + for path in ("own-provider", "own-provider-thunderid"): + with self.subTest(path=path): + receipt = self.cell("ownProvider") + receipt["passRule"][name] = 30 + receipt["passRule"]["reader-time-to-t2-modelled"] = None + report = self.report(receipt, path) + self.assertEqual(report["counters"][name]["status"], "within-threshold") + self.assertEqual(report["counters"]["reader-time-to-t2-modelled"], { + "actual": None, "threshold": 60, "direction": "at-most", + "status": "recipe-gap", "unit": "minutes", + }) + self.assertEqual(report["t2Recipe"], "recipe-gap") + self.assertEqual(report["verdicts"]["effort"], "UNAVAILABLE") + receipt["passRule"][name] = 30.01 + report = self.report(receipt, path) + self.assertEqual(report["verdicts"]["effort"], "NOT MET") + self.assertEqual(report["t2Recipe"], "recipe-gap") + + def test_t2_recipe_gap_missing_snapshot_and_inapplicability_are_distinct(self): + for product, scope, status, verdict in ( + ("breg", "recipe", "missing", "UNAVAILABLE"), + ("casework", "recipe-gap", "recipe-gap", "UNAVAILABLE"), + ("render", "inapplicable-stateless", "inapplicable", "MET"), + ("discovery", "inapplicable-public-index", "inapplicable", "INAPPLICABLE"), + ("adapter-job", "inapplicable-supporting", "inapplicable", "INAPPLICABLE"), + ): + with self.subTest(product=product): + receipt = self.cell(product=product) + receipt["passRule"]["reader-time-to-t2-modelled"] = None + report = self.report(receipt) + self.assertEqual(report["verdicts"]["effort"], verdict) + self.assertEqual(report["t2Recipe"], scope) + self.assertEqual(report["counters"]["reader-time-to-t2-modelled"]["status"], status) + + def test_all_six_hard_conditions_can_block_effort(self): + for condition, data in ( + ("certificate", {"total": {"assistsUsed": 0, "certificatesMade": 1, "refusalsMet": 0}}), + ("token-hook-or-mapper", {"outcome": "assisted", "blockers": [{"assist": "mapper"}], + "total": {"assistsUsed": 1, "certificatesMade": 0, "refusalsMet": 0}}), + ("provisioning-sql", {"outcome": "fail", "code": "journey.needs.hand-written-sql"}), + ("image-build", {"outcome": "fail", "code": "journey.needs.image-build"}), + ("signature-verifier", {"outcome": "fail", "code": "journey.needs.signature-verifier"}), + ("no-refusal", {"outcome": "fail", "code": "http.403.scope", + "total": {"assistsUsed": 0, "certificatesMade": 0, "refusalsMet": 1}}), + ): + with self.subTest(condition=condition): + report = self.report(self.cell(**data)) + self.assertEqual(set(report["hardConditions"]), set(HARD_CONDITIONS)) + self.assertEqual(report["hardConditions"][condition], "violated") + self.assertEqual(report["verdicts"]["effort"], "NOT MET") + + def test_missing_hard_condition_evidence_cannot_pass(self): + for fields in ({"outcome": "unreached"}, {"outcome": "fail", "code": "journey.keep.lost-record"}, + {"total": {}}, {"blockers": None}, {"outcome": "assisted"}): + with self.subTest(fields=fields): + report = self.report(self.cell(**fields)) + self.assertEqual(report["verdicts"]["effort"], "UNAVAILABLE") + self.assertIn("unavailable", report["hardConditions"].values()) + + def test_machine_time_and_diagnostics_are_independent_from_effort(self): + name = "machine-time-to-t1" + receipt = self.cell() + receipt["passRule"][name] = 7.25 + report = self.report(receipt) + self.assertEqual(report["verdicts"], { + "effort": "MET", "diagnostics": "MET", "machineTime": "INFORMATIONAL", + }) + self.assertEqual(report["counters"][name]["actual"], 7.25) + self.assertEqual(report["counters"][name]["unit"], "minutes") + self.assertEqual(report["counters"][name]["status"], "informational") + receipt["passRule"][name] = None + report = self.report(receipt) + self.assertEqual(report["verdicts"]["effort"], "MET") + self.assertEqual(report["verdicts"]["machineTime"], "UNAVAILABLE") + + def test_legacy_aggregate_does_not_invent_per_control_provenance(self): + receipt = self.cell() + receipt["passRule"]["errors-that-say-what-to-change"] = 1 + report = self.report(receipt) + self.assertEqual(report["diagnosticEvidence"]["unattributedLiveCount"], 1) + self.assertEqual(report["diagnosticEvidence"]["liveChecks"], {}) + self.assertEqual(report["counters"]["errors-that-say-what-to-change"]["actual"], 3) + sources = [source["kind"] for row in report["diagnosticEvidence"]["credits"].values() + for source in row] + self.assertEqual(sources, ["isolated-test"] * 3) + + def test_live_and_isolated_credits_are_deduplicated_by_named_control(self): + receipt = self.cell("ownProvider", diagnosticChecks={ + "wrong-audience": "verified", "missing-scope": "unverified", + "expired-token": "verified", "other-control": "verified", + }) + report = self.report(receipt, "own-provider-thunderid") + evidence = report["diagnosticEvidence"] + self.assertEqual(set(evidence["credits"]), {"wrong-audience", "missing-scope", "expired-token"}) + self.assertEqual(evidence["liveChecks"], { + "wrong-audience": "verified", "missing-scope": "unverified", "expired-token": "verified", + }) + for control in ("wrong-audience", "expired-token"): + self.assertEqual(evidence["credits"][control][0], {"kind": "live-issuer", "issuer": "thunderid"}) + self.assertEqual(evidence["credits"][control][1]["kind"], "isolated-test") + self.assertEqual([source["kind"] for source in evidence["credits"]["missing-scope"]], ["isolated-test"]) + self.assertEqual(report["counters"]["errors-that-say-what-to-change"]["actual"], 3) + self.assertEqual(report["verdicts"]["diagnostics"], "MET") + + def test_unavailable_zero_and_partial_diagnostics_keep_their_own_verdict(self): + with tempfile.TemporaryDirectory() as temp: + (Path(temp) / "products.yaml").write_text( + "schema: registry.journey-products/v1\n" + "products:\n" + " - id: breg\n" + " tier: primary\n" + " verifiesTokens: true\n" + " t2:\n" + " rstackDev: recipe\n" + " ownProvider: recipe-gap\n", + encoding="utf-8", + ) + for observations, count, status, verdict in ( + ({}, None, "missing", "UNAVAILABLE"), + ({"wrong-audience": "unverified"}, 0, "outside-threshold", "NOT MET"), + ({"wrong-audience": "verified"}, 1, "outside-threshold", "NOT MET"), + ): + with self.subTest(observations=observations): + receipt = self.cell(diagnosticChecks=observations) + result = self.project(json.dumps(receipt), "rstack-dev", tables=temp) + self.assertEqual(result.returncode, 0, result.stderr) + report = json.loads(result.stdout) + self.assertEqual(report["verdicts"]["effort"], "MET") + self.assertEqual(report["verdicts"]["diagnostics"], verdict) + self.assertEqual(report["counters"]["errors-that-say-what-to-change"], { + "actual": count, "threshold": 3, "direction": "at-least", + "status": status, "unit": "of-three", + }) + + def test_diagnostics_inapplicable_for_public_index_and_supporting_runtimes(self): + for product in ("discovery", "breg-mcp"): + with self.subTest(product=product): + report = self.report(self.cell(product=product)) + self.assertEqual(report["verdicts"]["diagnostics"], "INAPPLICABLE") + self.assertEqual(report["verdicts"]["machineTime"], "INAPPLICABLE") + self.assertEqual(report["diagnosticEvidence"]["credits"], {}) + + def test_unreadable_inputs_are_reported(self): for contents, outcome, status in ( ("", "unknown", "invalid"), ("garbled", "unknown", "invalid"), ("{} {}", "unknown", "invalid"), + ('{"outcome":["pass"],"product":"breg"}', "unknown", "invalid"), ('{"outcome":"pass","passRule":[]}', "pass", "invalid"), ('{"outcome":"pass"}', "pass", "missing"), ): @@ -2086,7 +2445,7 @@ def test_unreadable_and_missing_measurements_are_reported(self): self.assertEqual(result.stderr, "") report = json.loads(result.stdout) self.assertEqual(report["outcome"], outcome) - self.assertEqual(report["verdict"], "NOT MET") + self.assertEqual(report["verdicts"]["effort"], "UNAVAILABLE") self.assertEqual(len(report["counters"]), 10) self.assertTrue(all(counter["actual"] is None and counter["status"] == status for counter in report["counters"].values())) @@ -2116,10 +2475,12 @@ def test_projection_contains_only_public_measurements(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(all(value not in result.stdout for value in private_values)) report = json.loads(result.stdout) - self.assertEqual(set(report), {"outcome", "verdict", "counters"}) + self.assertEqual(set(report), { + "outcome", "verdicts", "counters", "t2Recipe", "hardConditions", "diagnosticEvidence", + }) self.assertEqual(set(report["counters"]), set(limits)) self.assertEqual(report["outcome"], "fail") - self.assertEqual(report["verdict"], "MET") + self.assertEqual(report["verdicts"]["effort"], "UNAVAILABLE") if __name__ == "__main__": diff --git a/products/platform/journeys/test_lib.sh b/products/platform/journeys/test_lib.sh index b5bb73992d..79489509cf 100644 --- a/products/platform/journeys/test_lib.sh +++ b/products/platform/journeys/test_lib.sh @@ -765,6 +765,22 @@ driver_files() { journey_reached t1 journey_edit_file "$dir/alpha.yaml" 'cd: 2' 'cd: 20' --concepts issuer ;; + decisions) + printf '%s\n' '# starter guidance' 'audience: old' 'scopeClaim: scope' >"$dir/alpha.yaml" + journey_count documentation-words 40 + journey_step start --typed '' -- printf 'generated fixture' + journey_edit_file "$dir/alpha.yaml" \ + $'# starter guidance\naudience: old\nscopeClaim: scope' \ + $'# starter guidance\naudience: chosen\nscopeClaim: scope' --concepts audience + journey_edit_file "$dir/alpha.yaml" 'scopeClaim: scope' 'scopeClaim: scope' + journey_reached t1 + journey_write_file "$dir/alpha.yaml" --append < <(printf 'hook: sink\n') + ;; + recipe) + journey_read_recipe rstack-dev rstack-dev breg + journey_reached t1 + journey_read_recipe breg-keep + ;; outside) journey_write_file "$JOURNEY_OUT/alpha.yaml" "$dir/first-hour-pass-rule.yaml" <<'YAML' # lib.sh reads only readerTimeModel; the flow mapping below is outside the @@ -2012,11 +2037,33 @@ case_files() { check_equal "both concepts are counted" 'runtime-file issuer' "$(json '.total.concepts | join(" ")' "$cell")" check_equal "t1 snapshots the lines written by then" 3 "$(json '.passRule."lines-written-to-t1"' "$cell")" check_equal "and the concepts met by then" 1 "$(json '.passRule."concepts-met-to-t1"' "$cell")" - check_equal "journey_count adds to the errors that say what to change" 2 "$(json '.passRule."errors-that-say-what-to-change"' "$cell")" + check_equal "counter 10 counts each verified live control only once" 2 "$(json '.passRule."errors-that-say-what-to-change"' "$cell")" check_equal "and to the identity-provider changes" 1 "$(json '.passRule."identity-provider-changes"' "$cell")" check_equal "the reader time to t1 follows the model (18/200 + 3*30/60 + 1*60/60)" 2.59 "$(json '.passRule."reader-time-to-t1-modelled"' "$cell")" check_equal "the reader time to t2 follows the model (24/200 + 4*30/60 + 2*60/60)" 4.12 "$(json '.passRule."reader-time-to-t2-modelled"' "$cell")" + begin_case reader-decisions + drive 0 SCENARIO=files FILES_MODE=decisions -- --product alpha + cell="$out/alpha/cell.json" + check_equal "an automated step records output without charging a command" 0 "$(json '.toT1.steps' "$cell")" + check_equal "unchanged starter lines are free and the changed line counts" 1 "$(json '.toT1.linesWritten' "$cell")" + check_equal "only the newly authored line contributes typing" 17 "$(json '.toT1.charactersTyped' "$cell")" + check_equal "the audience choice counts" audience "$(json '.total.concepts | join(" ")' "$cell")" + check_equal "reading still contributes to the reader model" 1.79 "$(json '.passRule."reader-time-to-t1-modelled"' "$cell")" + + check_equal "an adopter-authored append adds only the new line" 2 "$(json '.total.linesWritten' "$cell")" + check_equal "append stays in the already touched file" 1 "$(json '.total.filesTouched' "$cell")" + check_equal "new and existing text both remain in the file" \ + $'# starter guidance\naudience: chosen\nscopeClaim: scope\nhook: sink' "$(contents "$out/work/alpha/alpha.yaml")" + + begin_case recipe-reading + drive 0 SCENARIO=files FILES_MODE=recipe -- --product alpha + cell="$out/alpha/cell.json" + check_equal "read sections are recorded once at the measured endpoint" 'rstack-dev breg' "$(json '.toT1.readingSections | join(" ")' "$cell")" + check_equal "the next endpoint adds only its own reading" 'rstack-dev breg breg-keep' "$(json '.toT2.readingSections | join(" ")' "$cell")" + check "maintained prose contributes measured input" test "$(json '.toT1.documentationWords' "$cell")" -gt 0 + check "T2 reading adds words beyond T1" test "$(json '.toT2.documentationWords' "$cell")" -gt "$(json '.toT1.documentationWords' "$cell")" + begin_case file-refusals drive 3 SCENARIO=files FILES_MODE=outside -- --product alpha check "a reader's file outside work/ is refused" has "must be under" "$last_err" @@ -2058,15 +2105,21 @@ case_real_tables() { 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")" - check "the log reports the first-hour verdict" has "breg first-hour comparison: NOT MET" "$last_err" - check_equal "the projected verdict is visible" "NOT MET" "$(json .verdict "$out/public-cell-receipts/breg/cell.json")" - check_equal "absent planted-error measurement is missing" missing "$(json '.counters["errors-that-say-what-to-change"].status' "$out/public-cell-receipts/breg/cell.json")" - check_equal "missing T2 is reported" missing "$(json '.counters["reader-time-to-t2-modelled"].status' "$out/public-cell-receipts/breg/cell.json")" - - begin_case real-table-outside-first-hour-threshold - drive 0 TEST_JOURNEY=rstack-dev SCENARIO=replay REPLAY_COUNTERS=2 JOURNEY_TABLES_DIR= -- --expected "$lib_dir/expected-failures.yaml" --strict - check_equal "measured zero is below the required minimum" outside-threshold "$(json '.counters["errors-that-say-what-to-change"].status' "$out/public-cell-receipts/breg/cell.json")" - check_equal "measured zero remains visible" 0 "$(json '.counters["errors-that-say-what-to-change"].actual' "$out/public-cell-receipts/breg/cell.json")" + check "the log reports the separate verdicts" has "breg first-hour effort: UNAVAILABLE, diagnostics: MET, machine time: UNAVAILABLE" "$last_err" + check_equal "missing measured T2 with a maintained recipe is reported" missing "$(json '.counters["reader-time-to-t2-modelled"].status' "$out/public-cell-receipts/breg/cell.json")" + check_equal "the summary carries the sanitized measurements and verdicts unchanged" true \ + "$(jq -e --slurpfile receipt "$out/public-cell-receipts/breg/cell.json" '.cells[] | select(.product == "breg") | .firstHour == $receipt[0]' "$out/summary.json")" + check_equal "Discovery public index has an inapplicable T2" inapplicable-public-index \ + "$(json '.cells[] | select(.product == "discovery") | .firstHour.t2Recipe' "$out/summary.json")" + + begin_case real-table-first-hour-diagnostic-deduplication + drive 0 TEST_JOURNEY=rstack-dev SCENARIO=replay REPLAY_COUNTERS=1 JOURNEY_TABLES_DIR= -- --expected "$lib_dir/expected-failures.yaml" --strict + check_equal "verified live evidence survives repeated observations of the same control" 1 \ + "$(json '.passRule["errors-that-say-what-to-change"]' "$out/casework/cell.json")" + check_equal "the public receipt credits the control once, with both sources" 2 \ + "$(json '.diagnosticEvidence.credits["missing-scope"] | length' "$out/public-cell-receipts/casework/cell.json")" + check_equal "counter 10 is the number of distinct verified controls" 3 \ + "$(json '.counters["errors-that-say-what-to-change"].actual' "$out/public-cell-receipts/casework/cell.json")" } cleanup_work() { diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index efa9adfd0f..7b55053dab 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -2306,6 +2306,48 @@ def quantity_units(self) -> None: # Source lint ---------------------------------------------------------------- + def setting_summaries(self) -> None: + """Check the prose shared by posture reports and notices.""" + setting = re.compile( + r"\b(?Pstruct\s+)?(?:ExplicitProductionSetting|DevelopmentSetting)\s*\{" + ) + literal = re.compile( + r'\s*(?:"(?P(?:[^"\\]|\\.)*)"' + r'|r(?P#{0,255})"(?P.*?)"(?P=hashes))', + re.DOTALL, + ) + for directory, _ in self.rust.crates.values(): + paths = sorted((directory / "src").rglob("*.rs")) + for path, code in conformance.production_code(paths).items(): + matches = list(setting.finditer(code)) + if not matches: + continue + text = path.read_text(encoding="utf-8") + for match in matches: + if match["declaration"]: + continue + opening = match.end() - 1 + end = conformance.matching_brace(code, opening) + body = code[opening + 1:end] + # The setting declarations have a key. Report projections + # with the same type name carry a pointer instead. + if not re.search(r"\bkey\s*:", body): + continue + field = re.search(r"\bsummary\s*:", body) + if field is None: + continue + start = opening + 1 + field.end() + value = literal.match(text, start, end) + summary = (value["ordinary"] or value["raw"] or "") if value else "" + if summary[:1].isupper() and not summary.rstrip().endswith("."): + continue + line = text.count("\n", 0, opening + 1 + field.start()) + 1 + location = path.relative_to(self.root).as_posix() + self.report.errors.append( + f"{location}:{line}: Setting summary must start with an uppercase letter " + "and omit the trailing period." + ) + def source_rules(self) -> None: seen: set[tuple[Path, str]] = set() for entry in self.formats: @@ -2762,6 +2804,7 @@ def run(root: Path, base: str | None = None, strict: bool = False) -> Report: lint.quantity_units() lint.retired_spellings() lint.source_rules() + lint.setting_summaries() entries = lint.load_register() lint.reconcile(entries, strict) lint.ratchet(entries, base) diff --git a/products/platform/scripts/check-session-dependencies.py b/products/platform/scripts/check-session-dependencies.py new file mode 100644 index 0000000000..3f0e7e38de --- /dev/null +++ b/products/platform/scripts/check-session-dependencies.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Check the Registry Session linked dependency boundary.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from collections import defaultdict +from pathlib import Path + + +SESSION = "registry-session" +# The catalogue reads the Session CLI command tree without starting the service. +CLI_DOCS = "registry-cli-docs" + + +def shortest_paths( + starts: dict[str, str], edges: dict[str, set[str]] +) -> dict[str, list[str]]: + """Breadth-first paths from each start, keyed by the package each reaches.""" + paths = {package: [origin, package] for package, origin in starts.items()} + pending = sorted(starts) + while pending: + following = [] + for package in pending: + for target in sorted(edges.get(package, ())): + if target not in paths: + paths[target] = [*paths[package], target] + following.append(target) + pending = following + return paths + + +def render(path: list[str], dev_edges: set[tuple[str, str]]) -> str: + rendered = path[0] + for source, target in zip(path, path[1:]): + arrow = " -dev-> " if (source, target) in dev_edges else " -> " + rendered += arrow + target + return rendered + + +def violations(metadata: dict) -> list[str]: + names = {package["id"]: package["name"] for package in metadata["packages"]} + members = set(metadata["workspace_members"]) + resolve = metadata.get("resolve") + if not resolve or not resolve["nodes"]: + raise ValueError("cargo metadata did not include a resolved dependency graph") + + session_ids = [member for member in members if names[member] == SESSION] + if len(session_ids) != 1: + return [f"workspace must contain exactly one {SESSION} package"] + session_id = session_ids[0] + + # Every workspace member, and every registry crate Cargo resolves from an + # excluded path, git or a registry, is held to the boundary. + checked = { + package for package, name in names.items() + if package in members or name.startswith("registry-") + } + + # A package's own dev-dependencies count, so a test cannot link what the + # package may not. The dev-dependencies of a crate it reaches are not + # followed: Cargo never builds them into the package being checked. + every: dict[str, set[str]] = defaultdict(set) + linked: dict[str, set[str]] = defaultdict(set) + linked_reverse: dict[str, set[str]] = defaultdict(set) + dev_edges: set[tuple[str, str]] = set() + for node in resolve["nodes"]: + for dependency in node["deps"]: + source, target = node["id"], dependency["pkg"] + kinds = {kind["kind"] for kind in dependency["dep_kinds"]} + every[source].add(target) + if kinds - {"dev"}: + linked[source].add(target) + linked_reverse[target].add(source) + else: + dev_edges.add((source, target)) + + dev_names = {(names[source], names[target]) for source, target in dev_edges} + + def show(path: list[str]) -> str: + return render([names[package] for package in path], dev_names) + + failures = [] + forward = shortest_paths( + {target: session_id for target in every[session_id]}, linked + ) + if not any(names[package].startswith("registry-platform-") for package in forward): + failures.append( + f"{SESSION} reaches no registry-platform-* package; the resolved graph is incomplete" + ) + for package in sorted(forward, key=lambda package: names[package]): + name = names[package] + if package in checked and not name.startswith("registry-platform-"): + failures.append( + f"{SESSION} reaches {name}, outside registry-platform-*: {show(forward[package])}" + ) + + # Paths run backwards from Session here; reversed, each reads from the + # dependent to Session. + linking = shortest_paths( + {source: session_id for source in linked_reverse[session_id]}, linked_reverse + ) + linking[session_id] = [session_id] + for package in sorted(checked - {session_id}, key=lambda package: names[package]): + if names[package] == CLI_DOCS: + continue + if package in linking: + path = list(reversed(linking[package])) + else: + through = [target for target in every[package] if target in linking] + if not through: + continue + nearest = min(through, key=lambda target: (len(linking[target]), names[target])) + path = [package, *reversed(linking[nearest])] + failures.append( + f"{names[package]} reaches {SESSION}, and only {CLI_DOCS} may: {show(path)}" + ) + return failures + + +def load_metadata(repository_root: Path, fixture: Path | None) -> dict: + if fixture is not None: + return json.loads(fixture.read_text(encoding="utf-8")) + completed = subprocess.run( + ["cargo", "metadata", "--locked", "--all-features", "--format-version", "1"], + cwd=repository_root, + check=False, + capture_output=True, + text=True, + ) + if completed.returncode != 0: + raise ValueError( + f"cargo metadata failed (exit {completed.returncode}):\n{completed.stderr.rstrip()}" + ) + return json.loads(completed.stdout) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--metadata", type=Path, help="read a Cargo metadata fixture") + args = parser.parse_args() + repository_root = Path(__file__).resolve().parents[3] + try: + failures = violations(load_metadata(repository_root, args.metadata)) + except (OSError, ValueError, KeyError) as error: + print(f"Session dependency check could not inspect Cargo metadata: {error}", file=sys.stderr) + return 2 + if failures: + for failure in failures: + print(f"dependency-direction violation: {failure}", file=sys.stderr) + return 1 + print("Registry Session linked dependencies preserve the platform boundary.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/products/platform/scripts/service-preview-supervisor-probes.mjs b/products/platform/scripts/service-preview-supervisor-probes.mjs index 85e7551433..b41c0dfb4d 100644 --- a/products/platform/scripts/service-preview-supervisor-probes.mjs +++ b/products/platform/scripts/service-preview-supervisor-probes.mjs @@ -115,15 +115,19 @@ if (!ready.ok) throw new Error('BReg was not ready.') await ready.body?.cancel() const authorization = await stat(preview.authorizationFile) if (!authorization.isFile() || (authorization.mode & 0o077) !== 0) throw new Error('Expected private authorization.') -const server = createServer((_request, response) => response.writeHead(503).end()) +// The supervisor must observe a failed poll, and its pooled connection must +// close so Node can exit with the listener still open and unreferenced. +const server = createServer((_request, response) => response.writeHead(503, { connection: 'close' }).end()) +const firstProbe = new Promise(resolve => server.once('request', resolve)) await new Promise((resolve, reject) => { server.once('error', reject) server.listen(port, '127.0.0.1', resolve) }) -server.unref() await writeFile(${JSON.stringify(marker)}, JSON.stringify({ origin, breg: breg.baseUrl, runId, authorizationFile: preview.authorizationFile, }), { flag: 'wx' }) +await firstProbe +server.unref() throw new Error('Synthetic preview initialization refusal.') `) await writeFile(join(dirname(entry), 'fail-startup.d.mts'), 'export {}\n') diff --git a/products/platform/scripts/test-service-previews.mjs b/products/platform/scripts/test-service-previews.mjs index 1350a80d32..cc237dc78f 100644 --- a/products/platform/scripts/test-service-previews.mjs +++ b/products/platform/scripts/test-service-previews.mjs @@ -3,8 +3,8 @@ import { execFile } from 'node:child_process' 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' -import { dirname, isAbsolute, join } from 'node:path' +import { homedir, tmpdir } from 'node:os' +import { basename, dirname, isAbsolute, join, relative } from 'node:path' import { promisify } from 'node:util' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -13,6 +13,7 @@ import { editAfterBuild, editBeforeCapture, failedStart } from './service-previe const execute = promisify(execFile) const sourceExamples = fileURLToPath(new URL('../examples/service-previews/', import.meta.url)) +const referenceHost = fileURLToPath(new URL('../../../deploy/examples/business-registration/', import.meta.url)) const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu async function command(program, args, env = process.env) { @@ -200,6 +201,35 @@ async function business(page, url, expectedName = 'Harbour Bicycle Cooperative') return { matchingRecords: records.length, revision: Number(record.revisionId) } } +async function functionFreeBusiness(browser, url) { + const page = await browser.newPage() + try { + await page.goto(url.href) + assert.equal(await page.title(), 'Function-free registration') + const result = await page.evaluate(async () => { + const prefix = '/registry/businesses/v1' + const registrationNumber = 'BR-BROWSER-FUNCTION-FREE-001' + const headers = { 'Registry-Client': 'page', 'Content-Type': 'application/json' } + const action = await fetch(prefix + '/actions/register-business', { + method: 'POST', + headers: { ...headers, 'Idempotency-Key': 'register-function-free-browser' }, + body: JSON.stringify({ input: { legalName: 'Function Free Cooperative', registrationNumber } }), + }) + const records = await fetch(prefix + '/records/businesses', { headers }) + const { items } = await records.json() + const unavailable = await fetch('/api/functions/register-business', { method: 'POST', headers }) + return { + actionStatus: action.status, listStatus: records.status, functionStatus: unavailable.status, + matches: items.filter(record => record.domainData.registrationNumber === registrationNumber).length, + } + }) + assert.deepEqual(result, { actionStatus: 200, listStatus: 200, functionStatus: 404, matches: 1 }) + return result + } finally { + await page.close() + } +} + // 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), { @@ -311,13 +341,20 @@ async function permitRetry(page, applicantUrl) { // 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) { +async function permitReview(browser, url, report, coordinatorOnly) { 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)')) + if (coordinatorOnly) { + const refused = await actorCall(applicantUrl, '/api/functions/digest-application', { + method: 'POST', headers: { 'X-Registry-Preview-Caller-Kind': 'coordinator' }, + }) + assert.equal(refused.status, 404, 'The applicant cannot call a Coordinator-only function.') + assert.deepEqual(refused.body, { message: 'Unknown preview route' }) + } 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' }) @@ -536,6 +573,117 @@ async function exercise(browser, url, journey) { } } +async function exportBundle({ rstack, devArgs, env, project, output, state }) { + await mkdir(state, { recursive: true, mode: 0o700 }) + const report = JSON.parse(await command(rstack, devArgs('export-preview', project, '--output', output), + { ...env, RSTACK_DEV_STATE_DIR: state })) + assert.equal(report.status, 'exported') + assert.equal(report.output, output) + assert.match(report.bundleDigest, /^[0-9a-f]{64}$/u) + assert.deepEqual(await readdir(state), [], 'The export left its build directory behind.') + return report +} + +async function exportPageOnlyPreview({ rstack, devArgs, env, project, scratch }) { + const before = await treeDigest(project) + const output = join(scratch, 'export-page-only') + const state = join(scratch, 'export-page-only-state') + const report = await exportBundle({ rstack, devArgs, env, project, output, state }) + const manifest = JSON.parse(await readFile(join(output, 'manifest.json'), 'utf8')) + const sha256 = bytes => createHash('sha256').update(bytes).digest('hex') + assert.deepEqual(manifest.functions, []) + assert.equal(manifest.declarationDigest, sha256(await readFile(join(project, 'service.yaml')))) + assert.equal(manifest.declarationDigest, report.declarationDigest) + const staticOutput = 'project/web/dist' + assert.equal(manifest.staticOutput, staticOutput) + const files = ['manifest.json', ...['app.js', 'index.html', 'service.css'].map(name => `${staticOutput}/${name}`)] + assert.deepEqual(report.files, files) + const entries = (await readdir(output, { recursive: true, withFileTypes: true })).map(entry => { + const path = relative(output, join(entry.parentPath, entry.name)) + assert.ok(files.includes(path) ? entry.isFile() : entry.isDirectory(), `Unexpected bundle entry type for ${path}.`) + return path + }) + assert.deepEqual(entries.sort(), [...files, 'project', 'project/web', staticOutput].sort()) + // The bundle digest hashes the compact JSON array of file hashes in path byte order. + const hashes = await Promise.all(files.map(async file => [file, sha256(await readFile(join(output, file)))])) + assert.equal(sha256(JSON.stringify(hashes)), report.bundleDigest) + assert.equal(await treeDigest(project), before, 'The export modified the authored project.') + return { exported: true, bundleDigest: report.bundleDigest } +} + +// Export the business-registration preview twice, from two copies of the +// project at different paths and from state directories at different depths, +// and require identical bytes, one digest, no host path in any exported file, +// a refused existing output, and a reference host that serves the bundle as +// exported under the digest rstack printed. +export async function exportPreview({ rstack, devArgs, env, project, copy, scratch, bregctl }) { + const before = await treeDigest(project) + const exports = [] + for (const [name, source, state] of [ + ['first', project, join(scratch, 'export-first-state')], + ['second', copy, join(scratch, 'export', 'deeper', 'second-state')], + ]) { + const output = join(scratch, `export-${name}`) + const report = await exportBundle({ rstack, devArgs, env, project: source, output, state }) + exports.push({ output, report }) + } + const [first, second] = exports + assert.equal(first.report.bundleDigest, second.report.bundleDigest) + assert.deepEqual(first.report.files, second.report.files) + for (const file of first.report.files) { + assert.ok((await readFile(join(first.output, file))).equals(await readFile(join(second.output, file))), file) + } + const manifest = await readFile(join(first.output, 'manifest.json'), 'utf8') + assert.equal(JSON.parse(manifest).declarationDigest, first.report.declarationDigest) + const hostPaths = [scratch, basename(scratch), homedir(), project, copy] + for (const { output, report } of exports) { + for (const file of report.files) { + const text = await readFile(join(output, file), 'latin1') + for (const path of hostPaths) assert.ok(!text.includes(path), `${file} names the host path ${path}.`) + // A bundler path comment that climbs out of the staged project names + // the host's directories. + assert.doesNotMatch(text, /^\s*\/\/ (?:\.\.\/)+/mu, `${file} has a path comment outside the build.`) + } + } + await assert.rejects(command(rstack, devArgs('export-preview', project, '--output', first.output), env)) + const withoutPreview = fileURLToPath(new URL('../../breg/examples/minimal/', import.meta.url)) + const refusal = join(scratch, 'export-without-preview') + await assert.rejects(execute(rstack, devArgs('export-preview', withoutPreview, '--output', refusal), { env }), + error => JSON.parse(error.stdout).error.message.includes('declares no preview')) + await assert.rejects(stat(refusal), { code: 'ENOENT' }) + assert.equal(await treeDigest(project), before, 'The export modified the authored project.') + + const host = join(scratch, 'reference-host') + await mkdir(host) + for (const name of ['package.json', 'package-lock.json', 'host.mjs']) { + await cp(join(referenceHost, name), join(host, name)) + } + await command('npm', ['ci', '--prefix', host, '--ignore-scripts', '--no-audit', '--no-fund']) + const generated = join(scratch, 'reference-host-client') + await command(process.execPath, [join(referenceHost, 'tests', 'build-host-client.mjs'), project, generated], + { ...env, RSTACK_BREGCTL_BIN: bregctl }) + await cp(join(generated, 'host-client.mjs'), join(host, 'host-client.mjs')) + + const { bundleDigest, startHost } = await import(pathToFileURL(join(host, 'host.mjs')).href) + assert.equal(await bundleDigest(first.output), first.report.bundleDigest) + const served = await startHost(first.output, first.report.bundleDigest, + { functionsPort: 0, pagesPort: 0, report: () => {} }) + try { + const page = await fetch(served.pagesOrigin, { signal: AbortSignal.timeout(2_000) }) + assert.equal(page.status, 200) + const staticOutput = JSON.parse(manifest).staticOutput + assert.ok(Buffer.from(await page.arrayBuffer()).equals(await readFile(join(first.output, staticOutput, 'index.html')))) + const anonymous = await fetch(new URL('/functions/register-business', served.functionsOrigin), { + method: 'POST', + signal: AbortSignal.timeout(2_000), + }) + assert.equal(anonymous.status, 401, 'The exported function must require a caller in the reference host.') + } finally { + await served.close() + } + return { name: 'business-registration', exported: true, bundleDigest: first.report.bundleDigest } +} + async function main() { const inputs = process.argv.slice(2) assert.ok(inputs.length === 3 && inputs.every(isAbsolute), @@ -594,23 +742,27 @@ async function main() { url = loopback(report.preview ?? report.application) assert.equal(loopback(status.preview ?? status.application).href, url.href) const marker = join(dirname(report.logs), 'application-preview-function-origin') - privateOrigin = await readPrivateOrigin(marker) - assert.notEqual(privateOrigin.origin, url.origin) - const anonymous = await fetch(new URL(`/functions/${functionName}`, privateOrigin), { - method: 'POST', - signal: AbortSignal.timeout(2_000), - redirect: 'error', - }) - assert.equal(anonymous.status, 401, 'The private function must require a caller.') - await anonymous.body?.cancel() - const wrongOrigin = await fetch(new URL(`/api/functions/${functionName}`, url), { - method: 'POST', - headers: { Origin: 'https://other.invalid', 'Registry-Client': 'page' }, - signal: AbortSignal.timeout(2_000), - redirect: 'error', - }) - assert.equal(wrongOrigin.status, 403, 'The preview gateway allowed a different browser origin.') - await wrongOrigin.body?.cancel() + if (functionName === null) { + await assert.rejects(stat(marker), { code: 'ENOENT' }) + } else { + privateOrigin = await readPrivateOrigin(marker) + assert.notEqual(privateOrigin.origin, url.origin) + const anonymous = await fetch(new URL(`/functions/${functionName}`, privateOrigin), { + method: 'POST', + signal: AbortSignal.timeout(2_000), + redirect: 'error', + }) + assert.equal(anonymous.status, 401, 'The private function must require a caller.') + await anonymous.body?.cancel() + const wrongOrigin = await fetch(new URL(`/api/functions/${functionName}`, url), { + method: 'POST', + headers: { Origin: 'https://other.invalid', 'Registry-Client': 'page' }, + signal: AbortSignal.timeout(2_000), + redirect: 'error', + }) + assert.equal(wrongOrigin.status, 403, 'The preview gateway allowed a different browser origin.') + await wrongOrigin.body?.cancel() + } result = await drive(browser, url, journey, report) } finally { const stopped = await dev('stop', report.run_id, '--clean') @@ -622,7 +774,7 @@ async function main() { keepScratch = false } const actorOrigins = Object.values(report.previewActors ?? {}).map(loopback) - for (const address of [url, privateOrigin, ...actorOrigins]) { + for (const address of [url, ...(privateOrigin ? [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.') @@ -631,8 +783,28 @@ async function main() { try { await mkdir(state, { mode: 0o700 }) + let pageOnlyResult + if (!managed) { + const pageOnly = await installProject('business-registration', 'function-free-business-registration') + const service = join(pageOnly, 'service.yaml') + const plan = join(pageOnly, 'dev.yaml') + await rm(join(pageOnly, 'functions'), { recursive: true }) + await writeFile(service, (await readFile(service, 'utf8')).replace('functions: [register-business]\n', '')) + await writeFile(plan, (await readFile(plan, 'utf8')).replace( + ' functions: [register-business]', ' post: [/v1/actions/register-business]\n functions: []', + )) + await writeFile(join(pageOnly, 'web', 'src', 'page.ts'), 'document.title = "Function-free registration"\n') + const exported = await exportPageOnlyPreview({ rstack, devArgs, env, project: pageOnly, scratch }) + const { result } = await runProject(pageOnly, null, null, undefined, functionFreeBusiness) + pageOnlyResult = { name: 'function-free-business-registration', ...result, ...exported } + } const medicalProject = await installProject('medical-renewal') const businessProject = await installProject('business-registration') + const businessCopy = await installProject('business-registration', join('copies', 'elsewhere', 'business-registration')) + const bregctl = managed + ? join(roots[0], 'current', 'components', 'breg', 'bregctl', 'bregctl') + : env.RSTACK_BREGCTL_BIN ?? 'bregctl' + const exported = await exportPreview({ rstack, devArgs, env, project: businessProject, copy: businessCopy, scratch, bregctl }) const medical = await runProject(medicalProject, 'renew', renewal) const registered = await runProject(businessProject, 'register-business', business) assert.notEqual(medical.volume, registered.volume) @@ -643,8 +815,23 @@ async function main() { let permit if (!skipPermit) { const permitProject = await installProject('permit-review') + // Exercise the new authoring and binding only with the source build. + // Managed candidate runs use the examples and capabilities they shipped. + if (!managed) { + const plan = join(permitProject, 'dev.yaml') + await writeFile(plan, (await readFile(plan, 'utf8')).replace( + ' functions: [assess-permit, digest-application]', + ' functions: []\n coordinatorFunctions: [assess-permit, digest-application]', + )) + const digest = join(permitProject, 'functions', 'digest-application', 'index.ts') + await writeFile(digest, (await readFile(digest, 'utf8')).replace( + 'async (request) => handleDigest(request)', + 'async (request, _client, caller) => caller === "coordinator" && !request.headers.has("authorization")' + + ' ? handleDigest(request) : new Response(null, { status: 403 })', + )) + } permit = await runProject(permitProject, 'assess-permit', null, undefined, - (browser, url, _journey, report) => permitReview(browser, url, report)) + (browser, url, _journey, report) => permitReview(browser, url, report, !managed)) assert.equal(new Set([medical.volume, registered.volume, permit.volume]).size, 3) } @@ -654,8 +841,11 @@ async function main() { permit ? { name: 'permit-review', ...permit.result, directAnonymousStatus: 401, wrongOriginStatus: 403 } : { name: 'permit-review', skipped: 'This release ships no Coordinator.' }, + exported, ] + if (pageOnlyResult) results.push(pageOnlyResult) + if (!managed) { const entry = join(businessProject, 'functions', 'register-business', 'index.ts') const source = await readFile(entry, 'utf8') @@ -699,7 +889,9 @@ async function main() { } } -main().catch(error => { - console.error(error.message) - process.exitCode = 1 -}) +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch(error => { + console.error(error.message) + process.exitCode = 1 + }) +} diff --git a/products/platform/scripts/test_check_config_conventions.py b/products/platform/scripts/test_check_config_conventions.py index 9bb795a855..fc84653937 100644 --- a/products/platform/scripts/test_check_config_conventions.py +++ b/products/platform/scripts/test_check_config_conventions.py @@ -1806,6 +1806,48 @@ def test_cfg_yaml_1_does_not_treat_bare_reader_new_as_shared_in_another_crate(se ) +class SettingSummaryTests(ConventionsTestCase): + def test_check_refuses_lowercase_and_trailing_period(self) -> None: + self.repo.write(PLATFORM_RS, """ +static LOWER: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.lower", + key: "lower", + summary: "admits an example", +}; +static PERIOD: DevelopmentSetting = registry_platform_config::DevelopmentSetting { + code: "platform.posture.period", + key: "period", + summary: "Admits an example.", + production: "Use the default.", +}; +""") + report = self.repo.run() + self.assertError(report, f"{PLATFORM_RS}:5: Setting summary must start with an uppercase letter") + self.assertError(report, f"{PLATFORM_RS}:10: Setting summary must start with an uppercase letter") + self.assertTrue(report.failed) + + def test_check_accepts_sentences_and_ignores_comments_and_test_settings(self) -> None: + self.repo.write(PLATFORM_RS, """ +struct ExplicitProductionSetting { key: &'static str, summary: &'static str } +static SETTING: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.valid", + key: "valid", + // summary: "commented out", + summary: r#"Admits access tokens typed JWT. ID tokens stay refused"#, +}; +// static COMMENT: ExplicitProductionSetting = ExplicitProductionSetting { +// key: "comment", summary: "ignored", +// }; +#[cfg(test)] +mod tests { + static TEST: ExplicitProductionSetting = ExplicitProductionSetting { + code: "platform.posture.fixture", key: "fixture", summary: "ignored", + }; +} +""") + self.assertEqual(self.repo.run().errors, []) + + class SourceLintTests(ConventionsTestCase): def plant(self, text: str) -> None: self.repo.write(CONFIG_RS, CONFIG_RS_TEXT + text) diff --git a/products/platform/scripts/test_check_session_dependencies.py b/products/platform/scripts/test_check_session_dependencies.py new file mode 100644 index 0000000000..d858f60ab3 --- /dev/null +++ b/products/platform/scripts/test_check_session_dependencies.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Exercise the Session dependency check with resolved Cargo graphs.""" + +import importlib.util +import subprocess +from pathlib import Path +from unittest import TestCase, main, mock + + +SCRIPT = Path(__file__).with_name("check-session-dependencies.py") +SPEC = importlib.util.spec_from_file_location("session_dependencies", SCRIPT) +assert SPEC and SPEC.loader +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + +SESSION = "registry-session" +PLATFORM = "registry-platform-config" +DOCS = "registry-cli-docs" +PRODUCT = "registry-breg" +REPORT = "registry-cli-report" +BRIDGE = "external-bridge" +# A registry crate Cargo resolves outside the workspace: an excluded path, git +# or registry package. +OUTSIDE = "registry-breg-wasm-sdk" + + +def metadata(*edges: tuple[str, str, str | None]) -> dict: + members = [SESSION, PLATFORM, DOCS, PRODUCT, REPORT, "tooling"] + packages = [*members, BRIDGE, OUTSIDE] + return { + "workspace_members": members, + "packages": [{"id": package, "name": package} for package in packages], + "resolve": { + "nodes": [ + { + "id": package, + "deps": [ + {"pkg": target, "dep_kinds": [{"kind": kind}]} + for source, target, kind in edges + if source == package + ], + } + for package in packages + ], + }, + } + + +class SessionDependencyTests(TestCase): + def test_platform_and_external_dependencies_and_cli_docs_are_allowed(self) -> None: + graph = metadata((SESSION, PLATFORM, None), (PLATFORM, BRIDGE, None), (DOCS, SESSION, None)) + self.assertEqual(MODULE.violations(graph), []) + + def test_own_dev_edges_count_but_reached_dev_edges_do_not(self) -> None: + graph = metadata((SESSION, PLATFORM, None), (SESSION, PRODUCT, "dev"), + (PLATFORM, REPORT, "dev"), (DOCS, SESSION, None), ("tooling", DOCS, "dev")) + self.assertEqual(MODULE.violations(graph), [ + ( + "registry-session reaches registry-breg, outside registry-platform-*: " + "registry-session -dev-> registry-breg" + ), + ( + "tooling reaches registry-session, and only registry-cli-docs may: " + "tooling -dev-> registry-cli-docs -> registry-session" + ), + ]) + + def test_session_rejects_products_and_cli_report_with_the_path_to_each(self) -> None: + graph = metadata((SESSION, PRODUCT, "build"), (SESSION, PLATFORM, None), + (PLATFORM, BRIDGE, None), (BRIDGE, REPORT, None)) + self.assertEqual(MODULE.violations(graph), [ + ( + "registry-session reaches registry-breg, outside registry-platform-*: " + "registry-session -> registry-breg" + ), + ( + "registry-session reaches registry-cli-report, outside registry-platform-*: " + "registry-session -> registry-platform-config -> external-bridge -> registry-cli-report" + ), + ]) + + def test_session_rejects_non_platform_workspace_crates_regardless_of_name(self) -> None: + graph = metadata((SESSION, PLATFORM, None), (SESSION, "tooling", None)) + self.assertEqual(MODULE.violations(graph), [ + "registry-session reaches tooling, outside registry-platform-*: " + "registry-session -> tooling", + ]) + + def test_registry_crates_outside_the_workspace_are_checked_both_ways(self) -> None: + graph = metadata((SESSION, PLATFORM, None), (PLATFORM, OUTSIDE, None)) + self.assertEqual(MODULE.violations(graph), [ + "registry-session reaches registry-breg-wasm-sdk, outside registry-platform-*: " + "registry-session -> registry-platform-config -> registry-breg-wasm-sdk", + ]) + graph = metadata((SESSION, PLATFORM, None), (OUTSIDE, SESSION, None)) + self.assertEqual(MODULE.violations(graph), [ + "registry-breg-wasm-sdk reaches registry-session, and only registry-cli-docs may: " + "registry-breg-wasm-sdk -> registry-session", + ]) + + def test_only_cli_docs_may_link_session_even_indirectly(self) -> None: + graph = metadata((SESSION, PLATFORM, None), (DOCS, SESSION, None), (PRODUCT, BRIDGE, None), + (BRIDGE, DOCS, "build"), ("tooling", SESSION, "build")) + self.assertEqual(MODULE.violations(graph), [ + ( + "registry-breg reaches registry-session, and only registry-cli-docs may: " + "registry-breg -> external-bridge -> registry-cli-docs -> registry-session" + ), + ( + "tooling reaches registry-session, and only registry-cli-docs may: " + "tooling -> registry-session" + ), + ]) + + def test_session_must_reach_a_platform_crate(self) -> None: + graph = metadata((DOCS, SESSION, None)) + self.assertEqual(MODULE.violations(graph), [ + "registry-session reaches no registry-platform-* package; " + "the resolved graph is incomplete", + ]) + + def test_missing_session_is_a_violation(self) -> None: + graph = metadata() + graph["workspace_members"].remove(SESSION) + self.assertEqual(MODULE.violations(graph), [ + "workspace must contain exactly one registry-session package", + ]) + + def test_unresolved_metadata_is_rejected(self) -> None: + graph = metadata() + graph["resolve"] = None + with self.assertRaisesRegex(ValueError, "resolved dependency graph"): + MODULE.violations(graph) + + def test_cargo_failure_reports_cargo_stderr(self) -> None: + failed = subprocess.CompletedProcess( + args=["cargo"], returncode=101, stdout="", + stderr="error: the lock file needs to be updated but --locked was passed\n", + ) + with mock.patch.object(MODULE.subprocess, "run", return_value=failed): + with self.assertRaisesRegex( + ValueError, r"(?s)exit 101.*the lock file needs to be updated" + ): + MODULE.load_metadata(Path("."), None) + + +if __name__ == "__main__": + main() diff --git a/products/render/CHANGELOG.md b/products/render/CHANGELOG.md index 2199d713e8..cc5f846c24 100644 --- a/products/render/CHANGELOG.md +++ b/products/render/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- BREAKING: Production `check`, `serve`, `healthcheck`, and `generate identity-facts` refuse + `authentication.apiKeyRef` with `render.posture.shared-api-key`. Shared keys require explicit + development posture and a loopback API listener. An otherwise permitted non-loopback + address fails with `render.runtime.shared-key-requires-loopback`. Migration: Configure `authentication.oidc`, + list the permitted clients, and supply OIDC access tokens for the Render audience with + `render:render`. For local key-based runs, declare development for every command that reads + the runtime file. The OpenFn example now expects `renderAccessToken` in place of + `renderApiKey`. + - BREAKING: Render reaches a seal's timestamp authority only at the destination the shared outbound selector chooses for its URL. Render resolves only the authority's host and refuses an answer that is @@ -19,7 +28,9 @@ - BREAKING: Generated Render clients use `documentType` in `path` arguments for rendering and sealing. Replace `type` when calling those operations. Operation names and concrete HTTP URLs stay the same. -- Render calls `authentication.apiKeyRef` the shared API key instead of the legacy API key, and states its lifecycle: a supported mode for a single trusted caller with no OIDC issuer, which never seals and whose audit entries all carry the same key fingerprint. The key name and behaviour are unchanged. The `render.forbidden` detail on the seal route, the `render.runtime.authentication` action and the `render.runtime.signing-requires-oidc` message now say shared API key. The problem and finding codes are unchanged, so only a reader that matches the old text exactly needs updating. +- Render calls `authentication.apiKeyRef` the shared API key instead of the legacy API key. + The seal refusal detail, `render.runtime.signing-requires-oidc` message and + `render.runtime.authentication` action text use the same terminology. ## 0.49.0 - 2026-12-01 diff --git a/products/render/README.md b/products/render/README.md index ef4e2c4487..ef4ccbb0bb 100644 --- a/products/render/README.md +++ b/products/render/README.md @@ -11,14 +11,14 @@ library. Render is a **pure function**: data in, PDF out, with no database. The optional HTTP adapter validates resource-bound access tokens through the shared OIDC -verifier or accepts one configured shared API key. Only the adapter fetches issuer +verifier or accepts one configured shared API key in loopback development. Only the adapter fetches issuer metadata and keys; CLI and library rendering remain offline. It runs three ways with the same rendering guarantees: - **CLI** — `registry-render compile --bundle … --data … --issued-at … --output …`, offline, zero config: branch printing, template authoring, CI. - **Service** — `registry-render serve`: one POST endpoint (`/v1/render/{documentType}`), - resource-token or shared API-key auth, supervised workers, and value-free audit entries + resource-token auth or a development-only shared key, supervised workers, and value-free audit entries written before every render and before every response. - **Seal** (optional): with a `signing` block in the runtime file, `serve` adds `POST /v1/seal/{documentType}`, which returns the rendered document with a PAdES diff --git a/products/render/SECURITY-MATRIX.md b/products/render/SECURITY-MATRIX.md new file mode 100644 index 0000000000..aa07d6c658 --- /dev/null +++ b/products/render/SECURITY-MATRIX.md @@ -0,0 +1,16 @@ +# Render authentication invariants + +The public [Render security model](../../docs/site/src/content/docs/security/render.mdx) +covers the rest of the serving boundary. + +| Risk | Enforcement | Executable proof | +| --- | --- | --- | +| A production caller renders with a shared bearer | The posture gate refuses `authentication.apiKeyRef` under default or explicit production posture with `render.posture.shared-api-key`. Serving can read the reference through `Gated::get` only with a development witness. | `serve::shared_key_requires_explicit_loopback_development` and `serve::production_shared_key_refusal_precedes_package_loading` | +| A shared key reaches a non-loopback API listener | Explicit development is required, and the runtime reader refuses otherwise permitted non-loopback API listeners. `serve` resolves bind expressions before this check. | `serve::shared_key_requires_explicit_loopback_development` | +| A shared key seals a document | The reader requires OIDC for signing. The seal route independently refuses shared credentials. | `serve_seal::the_shared_api_key_never_seals` and `server::tests::the_shared_api_key_is_refused_on_the_seal_route_at_request_time` | + +The retained development credential is replayable by its holders. All its calls +share one audit fingerprint. Production uses resource-bound OIDC tokens and +an operator-configured client policy. + +A same-host proxy, host networking, or a sidecar can expose a loopback listener remotely. The explicit development posture gates shared-key use. diff --git a/products/render/examples/runtime.yaml b/products/render/examples/runtime.yaml index 9b2774480a..0b41460a93 100644 --- a/products/render/examples/runtime.yaml +++ b/products/render/examples/runtime.yaml @@ -14,7 +14,12 @@ secretProviders: file: root: /run/secrets/registry-render authentication: - apiKeyRef: secret:file/render-api-key + oidc: + issuers: + main: + issuer: https://issuer.example.test + audience: urn:example:render + allowedClients: [portal] limits: renderTimeoutSeconds: 20 audit: diff --git a/products/render/generated/registry-render.openapi.json b/products/render/generated/registry-render.openapi.json index eaf6380bbc..737b416d9b 100644 --- a/products/render/generated/registry-render.openapi.json +++ b/products/render/generated/registry-render.openapi.json @@ -285,7 +285,7 @@ } }, "securitySchemes": { - "bearerAuth": { "type": "http", "scheme": "bearer", "description": "Resource-bound OIDC access token with the route's scope: render:render for documents and rendering, render:seal for sealing. Or the shared API key configured in authentication.apiKeyRef, which never seals." } + "bearerAuth": { "type": "http", "scheme": "bearer", "description": "Resource-bound OIDC access token with the route's scope: render:render for documents and rendering, render:seal for sealing. In explicit development posture on a loopback API listener, authentication.apiKeyRef also admits a shared API key for documents and rendering." } } } } diff --git a/products/render/integrations/openfn/README.md b/products/render/integrations/openfn/README.md index 646dc1d0b9..265db6fefd 100644 --- a/products/render/integrations/openfn/README.md +++ b/products/render/integrations/openfn/README.md @@ -9,12 +9,14 @@ step. Deployment shape: -1. Run the binary with a runtime file (verified package, loopback bind, API - key in an owner-only file, audit file or `stdout` destination): +1. Run the binary with a verified package, a loopback bind, an audit destination, + and `authentication.oidc` configured for the Render resource and the OpenFn client: `registry-render serve --runtime-config /etc/registry-render/runtime.yaml` -2. Put the API key *value* in the job's private configuration (kit - precedent: `notification.json`), beside the breg reader token and the - delivery adaptor's key. +2. Before each job invocation, have the caller obtain a short-lived access token + for the Render audience with `render:render`. Pass it as `renderAccessToken` in + the private job configuration, beside the BReg reader token and the delivery + adaptor's key. Replace any previous `renderApiKey` entry. The job forwards the + token and relies on its caller to refresh expired tokens. 3. Use `receipt-job.js` as the starting point: configuration validation, bridge-envelope destructuring, `parseAs: "json"`, status checks, minimized return. diff --git a/products/render/integrations/openfn/receipt-job.js b/products/render/integrations/openfn/receipt-job.js index 0ff8c3b55c..4046d5775c 100644 --- a/products/render/integrations/openfn/receipt-job.js +++ b/products/render/integrations/openfn/receipt-job.js @@ -10,12 +10,11 @@ // // Configuration (private job config, e.g. notification.json): // renderUrl: "http://127.0.0.1:3200" (loopback to registry-render serve) -// renderApiKey: "<32+ byte API key>" (the value; render's own -// runtime keeps its secret-file ref) +// renderAccessToken: "" // breg: { baseUrl, apiKey, accessProfile } (least-privilege reader) // delivery: { endpoint, apiKey } (email/SMS adaptor destination) fn(async state => { - const { renderUrl, renderApiKey, breg, delivery, expectedSource, eventTypes } = state.configuration; + const { renderUrl, renderAccessToken, breg, delivery, expectedSource, eventTypes } = state.configuration; const { event, data } = state.data; // breg's record API exposes field ids under camelCase HTTP property names; // the template's JSON Schema uses the kebab-case spellings. This table is @@ -28,7 +27,7 @@ fn(async state => { bidiNote: 'bidi-note', }; if (typeof renderUrl !== 'string' || !/^https?:\/\/[\w.-]+(:\d+)?$/.test(renderUrl) || - typeof renderApiKey !== 'string' || !/^[\x21-\x7e]{32,256}$/.test(renderApiKey) || + typeof renderAccessToken !== 'string' || renderAccessToken.length > 8192 || !/^[A-Za-z0-9._~+/-]+=*$/.test(renderAccessToken) || typeof breg?.baseUrl !== 'string' || !/^https?:\/\/[\w.-]+(:\d+)?$/.test(breg.baseUrl) || typeof breg?.apiKey !== 'string' || !/^[\x21-\x7e]{16,2048}$/.test(breg.apiKey) || typeof breg?.accessProfile !== 'string' || !/^[a-z][a-z0-9-]*$/.test(breg.accessProfile) || @@ -68,7 +67,7 @@ fn(async state => { const rendered = await util.request('POST', `${renderUrl}/v1/render/receipt`, { headers: { - authorization: `Bearer ${renderApiKey}`, + authorization: `Bearer ${renderAccessToken}`, 'content-type': 'application/json', accept: 'application/json', // pdfBase64 for transport 'idempotency-key': state.eventEffectId, // correlation only; rendering diff --git a/products/render/schemas/runtime.schema.json b/products/render/schemas/runtime.schema.json index 36e0185a32..7649ec23c8 100644 --- a/products/render/schemas/runtime.schema.json +++ b/products/render/schemas/runtime.schema.json @@ -139,7 +139,10 @@ "properties": { "apiKeyRef": { "$ref": "#/$defs/SecretReference", - "description": "Secret reference to the shared API key, under a declared provider: one\nstatic bearer credential that every request presents. It is supported for a\nsingle trusted caller where no OIDC issuer is available. It never seals.\nEvery request carries the same key, so the audit records one fingerprint\nfor all calls and cannot tell callers apart. Omit when OIDC authentication\nis configured." + "description": "Secret reference to the shared API key, under a declared provider.\nRequires explicit development posture and a loopback API listener.\nEvery call shares one bearer credential and one audit fingerprint.\nOmit when using OIDC, which is required for production and sealing.", + "x-registry-development-only": [ + "render.posture.shared-api-key" + ] }, "oidc": { "$ref": "#/$defs/OidcRuntime" diff --git a/products/scheduling/CHANGELOG.md b/products/scheduling/CHANGELOG.md index be51e575fc..6ca8cc304a 100644 --- a/products/scheduling/CHANGELOG.md +++ b/products/scheduling/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- BREAKING: Runtime and migration PostgreSQL URLs with `sslmode=require` or + `sslmode=verify-full` are refused under a plaintext transport. Set + `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from + the URL to keep the configured plaintext transport. + - BREAKING: Generated Scheduling clients use `holdId` and `appointmentId` in `path` arguments. Replace `hold_id` and `appointment_id` when calling the generated methods. Operation names and concrete HTTP URLs stay the same. diff --git a/products/scheduling/scripts/run_managed_task_authority_journey.py b/products/scheduling/scripts/run_managed_task_authority_journey.py new file mode 100755 index 0000000000..06c44f093d --- /dev/null +++ b/products/scheduling/scripts/run_managed_task_authority_journey.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Run the managed Scheduling task-authority journey and refuse a vacuous pass. + +The ThunderID own-provider journey, with a managed Scheduling runtime, binds one +task agent to one Casework assertion issuer through `rstack dev`. Its hook step +checks four outcomes in order and stops the run with a harness failure if any +differs: + +- an exchanged bearer whose issuer binding is absent or wrong: 401 at + `token-assertion-issuer`; +- an ordinary hold without a task grant: 403 at `task-grant-missing`; +- a hold and confirm under the exact grant: 201 and 201, with the signed + confirmed appointment received by the run's hook sink; +- a write after the task authority stops: 503 `service.unavailable`. + +A zero exit alone does not prove those checks ran. This script also requires +the strict ThunderID run record, a `pass` row for every journey step of the +Scheduling cell (so the hook step is neither skipped nor unexercised), the files +only the managed controls write, a clean cleanup, and no container left under +the run's prefix. + +Usage: + run_managed_task_authority_journey.py --bin-dir DIR --out DIR +""" + +from __future__ import annotations + +import argparse +import csv +import json +import subprocess +import sys +from collections.abc import Callable +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[3] +JOURNEYS = ROOT / "products/platform/journeys" +TABLE = JOURNEYS / "expected-failures-thunderid.yaml" +JOURNEY = "own-provider-thunderid" +PRODUCT = "scheduling" + +# Written only by the managed branch of the composed Scheduling check: the +# unbound and wrong-authority controls, the bound run, and its projected live +# Casework status binding. +MANAGED_EVIDENCE = ( + "unbound-scheduling.json", + "wrong-authority-scheduling.json", + "managed-scheduling.json", + "managed-status-binding.json", +) + + +def journey_steps() -> list[str]: + table = yaml.safe_load(TABLE.read_text(encoding="utf-8")) + return list(table["journeys"][JOURNEY]["steps"]) + + +def journey_command(bin_dir: Path, out: Path) -> list[str]: + return [ + str(JOURNEYS / "own-provider.sh"), + "--issuer", "thunderid", + "--product", PRODUCT, + "--scheduling-runtime", "managed", + "--bin-dir", str(bin_dir), + "--expected", str(TABLE), + "--strict", + "--out", str(out), + ] + + +def docker_containers(names: list[str]) -> list[str]: + """Return those of NAMES that still exist as containers.""" + remaining = [] + for name in names: + listed = subprocess.run( + ["docker", "ps", "--all", "--filter", f"name=^{name}$", "--format", "{{.Names}}"], + check=True, capture_output=True, text=True, + ) + remaining.extend(line for line in listed.stdout.splitlines() if line) + return remaining + + +def verify(out: Path, containers: Callable[[list[str]], list[str]] = docker_containers) -> list[str]: + """Return every reason the run in OUT does not prove the four outcomes.""" + problems: list[str] = [] + try: + record = json.loads((out / "run.json").read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + return [f"no readable run record: {error}"] + + expected = { + "journey": JOURNEY, + "strict": True, + "products": [PRODUCT], + "exitStatus": 0, + "harnessFailure": None, + } + for key, value in expected.items(): + if record.get(key) != value: + problems.append(f"run record {key} is {record.get(key)!r}, not {value!r}") + if record.get("cleanup", {}).get("failures") != []: + problems.append(f"cleanup reported failures: {record.get('cleanup')!r}") + if record.get("leftovers") != []: + problems.append(f"cleanup left resources: {record.get('leftovers')!r}") + + try: + with (out / "cells.tsv").open(encoding="utf-8", newline="") as handle: + rows = [row for row in csv.DictReader(handle, delimiter="\t") if row["product"] == PRODUCT] + except (OSError, KeyError) as error: + rows = [] + problems.append(f"no readable cell rows: {error}") + for step in journey_steps(): + outcomes = [row["outcome"] for row in rows if row["step"] == step] + if outcomes != ["pass"]: + problems.append(f"step {step} recorded {outcomes or 'nothing'}, not one pass") + + composed = out / "work" / PRODUCT / "composed" + for name in MANAGED_EVIDENCE: + path = composed / name + if not path.is_file() or path.stat().st_size == 0: + problems.append(f"managed control evidence {name} is missing") + + # The containers this run started. The name prefix is shared by every + # journey run on a host, so only the recorded names are checked. + try: + started = [ + name for name in (out / "containers.txt").read_text(encoding="utf-8").splitlines() if name + ] + except OSError as error: + started = [] + problems.append(f"no readable container list: {error}") + if not started and not problems: + problems.append("the run recorded no container, so it did not start its PostgreSQL") + remaining = containers(started) if started else [] + if remaining: + problems.append(f"containers remain after the run: {', '.join(remaining)}") + return problems + + +def main( + argv: list[str] | None = None, + run: Callable[..., subprocess.CompletedProcess] = subprocess.run, + containers: Callable[[list[str]], list[str]] = docker_containers, +) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--bin-dir", type=Path, required=True, help="directory of the built binaries") + parser.add_argument("--out", type=Path, required=True, help="new run directory") + arguments = parser.parse_args(argv) + + status = run(journey_command(arguments.bin_dir, arguments.out), check=False).returncode + problems = verify(arguments.out, containers=containers) + if status != 0: + problems.insert(0, f"the journey exited with status {status}") + for problem in problems: + print(f"managed Scheduling task-authority journey: {problem}", file=sys.stderr) + if problems: + return 1 + print("managed Scheduling task-authority journey: all four outcomes verified") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/products/scheduling/scripts/test_run_managed_task_authority_journey.py b/products/scheduling/scripts/test_run_managed_task_authority_journey.py new file mode 100644 index 0000000000..c8e1d27068 --- /dev/null +++ b/products/scheduling/scripts/test_run_managed_task_authority_journey.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +import importlib.util +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).with_name("run_managed_task_authority_journey.py") +SPEC = importlib.util.spec_from_file_location("scheduling_managed_journey", SCRIPT) +assert SPEC and SPEC.loader +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + +STEPS = MODULE.journey_steps() + + +def write_run(out: Path, **changes) -> None: + """Write the record a passing managed run leaves, with CHANGES applied.""" + record = { + "schema": "registry.journey-run/v1", + "journey": "own-provider-thunderid", + "strict": True, + "products": ["scheduling"], + "containerPrefix": "journey-test-prefix", + "exitStatus": 0, + "harnessFailure": None, + "cleanup": {"failures": []}, + "leftovers": [], + } + record.update(changes) + (out / "run.json").write_text(json.dumps(record), encoding="utf-8") + + +def write_cells(out: Path, outcomes: dict[str, str] | None = None, product: str = "scheduling") -> None: + rows = ["product\tstep\toutcome\tcode\tseconds"] + for step in STEPS: + outcome = (outcomes or {}).get(step, "pass") + if outcome is not None: + rows.append(f"{product}\t{step}\t{outcome}\t-\t1.000") + (out / "cells.tsv").write_text("\n".join(rows) + "\n", encoding="utf-8") + + +def write_evidence(out: Path, skip: str | None = None) -> None: + composed = out / "work/scheduling/composed" + composed.mkdir(parents=True) + for name in MODULE.MANAGED_EVIDENCE: + if name != skip: + (composed / name).write_text("{}", encoding="utf-8") + + +def passing_run(out: Path) -> None: + write_run(out) + write_cells(out) + write_evidence(out) + (out / "containers.txt").write_text("rsj-own-provider-thunderid-run-pg\n", encoding="utf-8") + + +class VerifyTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory() + self.out = Path(self.temporary.name) + + def tearDown(self) -> None: + self.temporary.cleanup() + + def test_steps_come_from_the_thunderid_table_and_include_the_hook(self) -> None: + self.assertIn("hook", STEPS) + self.assertEqual("prepare", STEPS[0]) + + def test_a_complete_managed_run_passes(self) -> None: + passing_run(self.out) + self.assertEqual([], MODULE.verify(self.out, containers=lambda names: [])) + + def test_a_missing_run_record_fails(self) -> None: + self.assertNotEqual([], MODULE.verify(self.out, containers=lambda names: [])) + + def test_the_run_record_must_be_a_clean_strict_managed_scheduling_run(self) -> None: + cases = { + "keycloak journey": {"journey": "own-provider"}, + "ratchet without strict": {"strict": False}, + "another product": {"products": ["scheduling", "breg"]}, + "failed exit": {"exitStatus": 3}, + "unfinished exit": {"exitStatus": None}, + "harness failure": {"harnessFailure": "managed Scheduling did not refuse at token-assertion-issuer"}, + "cleanup failure": {"cleanup": {"failures": ["managed Scheduling recovery state retained"]}}, + "leftover container": {"leftovers": ["journey-test-prefix-postgres"]}, + } + for name, change in cases.items(): + with self.subTest(name), tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) + passing_run(out) + write_run(out, **change) + self.assertNotEqual([], MODULE.verify(out, containers=lambda names: [])) + + def test_every_step_must_pass_including_the_hook(self) -> None: + for step in STEPS: + for outcome in ("fail", "unexercised", "unreached", "assisted", None): + with self.subTest(step=step, outcome=outcome), tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) + passing_run(out) + write_cells(out, {step: outcome}) + problems = MODULE.verify(out, containers=lambda names: []) + self.assertTrue(any(step in problem for problem in problems), problems) + + def test_rows_for_another_product_do_not_count(self) -> None: + passing_run(self.out) + write_cells(self.out, product="breg") + self.assertNotEqual([], MODULE.verify(self.out, containers=lambda names: [])) + + def test_each_managed_control_must_leave_its_evidence(self) -> None: + # A standalone run passes the same steps but starts no managed runtime. + for name in MODULE.MANAGED_EVIDENCE: + with self.subTest(name), tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) + write_run(out) + write_cells(out) + write_evidence(out, skip=name) + problems = MODULE.verify(out, containers=lambda names: []) + self.assertTrue(any(name in problem for problem in problems), problems) + + def test_a_recorded_container_that_remains_fails_even_when_the_record_lists_none(self) -> None: + passing_run(self.out) + seen = [] + + def containers(names: list[str]) -> list[str]: + seen.append(names) + return names + + problems = MODULE.verify(self.out, containers=containers) + # Only this run's recorded containers are checked: the name prefix is + # shared by every journey run on the host. + self.assertEqual([["rsj-own-provider-thunderid-run-pg"]], seen) + self.assertTrue(any("rsj-own-provider-thunderid-run-pg" in problem for problem in problems)) + + def test_a_run_that_recorded_no_containers_fails(self) -> None: + passing_run(self.out) + (self.out / "containers.txt").unlink() + self.assertNotEqual([], MODULE.verify(self.out, containers=lambda names: [])) + + +class MainTest(unittest.TestCase): + def test_the_journey_runs_strict_and_managed_against_the_thunderid_table(self) -> None: + command = MODULE.journey_command(Path("/bins"), Path("/out")) + self.assertEqual(str(MODULE.JOURNEYS / "own-provider.sh"), command[0]) + joined = " ".join(command) + for fragment in ( + "--issuer thunderid", + "--product scheduling", + "--scheduling-runtime managed", + f"--expected {MODULE.TABLE}", + "--strict", + "--bin-dir /bins", + "--out /out", + ): + self.assertIn(fragment, joined) + self.assertNotIn("--keep", command) + + def test_a_zero_journey_exit_without_the_evidence_fails(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) / "run" + + def run(command, check): + out.mkdir() + write_run(out) + write_cells(out, {"hook": "unexercised"}) + return subprocess.CompletedProcess(command, 0) + + status = MODULE.main(["--bin-dir", "/bins", "--out", str(out)], run=run, containers=lambda names: []) + self.assertEqual(1, status) + + def test_a_failing_journey_fails_even_with_complete_evidence(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) / "run" + + def run(command, check): + out.mkdir() + passing_run(out) + return subprocess.CompletedProcess(command, 1) + + status = MODULE.main(["--bin-dir", "/bins", "--out", str(out)], run=run, containers=lambda names: []) + self.assertEqual(1, status) + + def test_a_complete_run_succeeds(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) / "run" + + def run(command, check): + out.mkdir() + passing_run(out) + return subprocess.CompletedProcess(command, 0) + + status = MODULE.main(["--bin-dir", "/bins", "--out", str(out)], run=run, containers=lambda names: []) + self.assertEqual(0, status) + + +if __name__ == "__main__": + unittest.main() diff --git a/release/NIGHTLY.md b/release/NIGHTLY.md index 4bb4a8550d..8014808767 100644 --- a/release/NIGHTLY.md +++ b/release/NIGHTLY.md @@ -40,7 +40,8 @@ inventory. `registry-stack.nightly-roster.v2.0` is the roster before Registry Coordinator joined. `registry-stack.nightly-roster.v2.1` adds the `coordinator` image and the Linux amd64 `coordinator` and `coordinatorctl` binaries, and nightlies use it from the base version that -`COORDINATOR_FIRST_RELEASE` in `release/scripts/release_roster.py` names. The +`COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE` in `release/scripts/release_roster.py` +names, never ahead of `COORDINATOR_FIRST_RELEASE`. The reader accepts both, so a v2.0 nightly built from the same base version before Coordinator joined stays readable. `registry-stack.nightly-roster.v2.2` adds the v0.44.0 binary roster for all supported platforms and additional installers @@ -57,12 +58,15 @@ add the standalone `registry-language-server` for Linux amd64 and macOS arm64 to v2.4 and v2.5 respectively, from the base version that `LANGUAGE_SERVER_FIRST_RELEASE` names. Its `--version` reports the Cargo package 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`. 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 +nightly source. The numbered v0.52.0 release adds the +Coordinator image, but nightlies keep it out while +`COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE` is `None`, until the Coordinator +release advisory baseline is reviewed. Until then, nightlies from base version +v0.52.0 use v2.6, which carries the Coordinator binaries without the image. +No profile carries the Registry Document Store, which stays held out while +`DOCUMENTS_FIRST_RELEASE` is `None`. No profile carries the Session binary or +image. Numbered releases add the binary in v0.51.0 and the image in v0.52.0. +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 without rewriting published bytes. diff --git a/release/OPERATIONS.md b/release/OPERATIONS.md index e84f46a6dc..55ac944ceb 100644 --- a/release/OPERATIONS.md +++ b/release/OPERATIONS.md @@ -150,9 +150,9 @@ Complete new-image onboarding outside the release clock, in this order: token on the command line: ```sh -package="${PACKAGE:?set PACKAGE to evidence, discovery, breg, breg-mcp, breg-review, casework, scheduling, messaging, registry-render, evidence-oid4vci, or coordinator}" +package="${PACKAGE:?set PACKAGE to evidence, discovery, breg, breg-mcp, breg-review, casework, scheduling, messaging, registry-render, evidence-oid4vci, coordinator, or registry-session}" case "${package}" in - evidence|discovery|breg|breg-mcp|breg-review|casework|scheduling|messaging|registry-render|evidence-oid4vci|coordinator) ;; + evidence|discovery|breg|breg-mcp|breg-review|casework|scheduling|messaging|registry-render|evidence-oid4vci|coordinator|registry-session) ;; *) echo "unsupported release image package: ${package}" >&2; exit 1 ;; esac @@ -218,8 +218,9 @@ exclude its image, binaries, installers, and client namespace. is held out of every release while `DOCUMENTS_FIRST_RELEASE` is `None`. `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. +`session` release unit, not an `rstack` component, and has no installer. +The Registry Session and Registry Coordinator images join the numbered roster +from `v0.52.0`. 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 @@ -351,39 +352,33 @@ version stays in the package and every applied run reports it again. GitHub documents one route for this limit, a GitHub Support request, so removing the version is a decision to file one, not a tooling change. -### Coordinator onboarding - -Coordinator's unified client roster is independent of its runtime image hold. -`COORDINATOR_CLIENT_FIRST_RELEASE` selects client packaging; it does not prove -that the binary pair or image has been published. Keep the runtime image hold -until its own onboarding and advisory checks pass, and use the release manifest -to identify assets actually shipped. - -For a first Coordinator image, complete steps 3 and 4 above for `coordinator` -and `coordinator-candidate`. The final package must be public, its candidate -package private, and repository Actions must have the required package access. -Only after the private identity exists may `coordinator-candidate` join -`CANDIDATE_PACKAGES` and its test. Keep `coordinator` in `PUBLIC_PACKAGES`. -A missing-baseline rehearsal does not relax these ownership prerequisites. - -Then use one clean, committed baseline-bootstrap branch with the intended -Coordinator runtime image roster and the existing `release-rehearsal.yml` -workflow. Supply `unit=stack`, the intended `version`, an explicit -`coordinator-baseline-bootstrap-...` request ID, and `advisory_evidence=true`; -omit `release_id`. This dispatch has no publication permission. The canonical -Linux evidence job and evidence-only workflow must succeed. The ordinary strict -rehearsal remains unavailable while -`release/security/coordinator-advisory-baseline.json` is missing. Do not -substitute a macOS binary, another service's fingerprint, or an unreviewed -placeholder baseline. - -Review that job's exact source, OCI config and digest, native Syft and Grype -reports, exported rootfs, and exposure reports for both -`/usr/local/bin/coordinator` and `/usr/local/bin/coordinatorctl`. Author the -first baseline and update its existing live-pin tests through the reviewed -procedure below. Keep advisory acceptance and package visibility decisions -with the release owner. Once the baseline is reviewed, rerun strict onboarding -and the read-only rehearsal on that prepared branch before removing the image hold. +### Session and Coordinator image onboarding + +The image roster starts with v0.52.0. Use the release manifest to find the +images and exact digests published for a release. + +1. Complete the package bootstrap above for `registry-session` and + `coordinator`. Make the final packages public, keep the candidate packages + private, and grant this repository Actions access to both pairs. +2. After bootstrap, add the two private identities to `CANDIDATE_PACKAGES`, + its tests, and the matching pin in `check-gates-inventory.py`. Both final + names are in `PUBLIC_PACKAGES`. Missing-baseline rehearsal still checks these + identities. +3. Dispatch the hosted evidence-only rehearsal from a clean, committed branch + with the intended v0.52.0 roster. Use `unit=stack`, `version=0.52.0`, a + unique `host-images-baseline-bootstrap-...` request ID, and + `advisory_evidence=true`. Omit `release_id`. This run has no publication + permission. Do not substitute a macOS binary, another service's + fingerprint, or an unreviewed placeholder baseline. +4. Review the exact source, OCI config and digest, Syft and Grype reports, + exported rootfs and exposure evidence for both images. Review the + `registry-session`, `coordinator` and `coordinatorctl` executables. Author + the two v4 baselines from that evidence and review any exception separately. + Keep advisory acceptance and package visibility decisions with the release + owner. +5. Run strict onboarding and the read-only rehearsal. The normal candidate + builds each image once and binds its digest and security evidence. Promote + those exact digests and run `verify-public`. ### Mirror the pinned BuildKit image @@ -451,7 +446,7 @@ browser and edge package is `@registrystack/client`. Their product namespaces ca version-selected APIs: `discovery`, `evidence`, and `breg` from v0.26.1, `casework` from v0.30.0, `messaging` from v0.38.0, and `scheduling` from v0.40.0. The client roster selects `coordinator` from v0.44.0; this is -independent of the Coordinator runtime image hold and is not proof of +independent of the Coordinator runtime image and is not proof of publication. Check that version's actual release manifest and package assets. Releases through v0.38.0 also carry a `relay` namespace; v0.39.0 removes it. The product-specific native bindings are build inputs, not additional public @@ -1197,6 +1192,56 @@ workflow then: - Runs the release payload checks. - Seals a candidate manifest and bundle that remain promotable for seven days. - Attests the manifest and bundle after re-verifying their bytes. +- For Stack candidates that ship the Session image, runs the + business-registration Compose host in separate BReg and Casework jobs with + read-only permissions. Both use the same candidate attempt's attested BReg + and Session image digests, and the Casework profile also uses its Casework + image digest. The candidate Session CLI generates and checks the gateway. + The browser build uses the sealed web client tarball and BReg serves the + package sealed from a separate production-posture schema test. The Casework + browser checks that the same reviewer reads both products with one Session + sign-in, verifies the two role refusals, and checks for browser Authorization + headers. Each job retains its checked receipt for two days. Promotion + requires a successful candidate workflow run. + +### Replay the candidate reference host locally + +Use a clean checkout at the protected candidate source, the compact artifact +from the exact successful run attempt, and an authenticated GitHub CLI with +read access to its attestations. On a disposable Linux amd64 Docker host with +Node.js 24 and noninteractive sudo, choose a new absolute staging directory. +The host needs the Compose v2 plugin, Chromium's system libraries and unused +loopback ports 8443 and 9443. Set `PROFILE` to `breg` or `casework`. To replay +both, run one profile at a time with a fresh stage and receipt path for each. + +```sh +python3 release/scripts/candidate_host_inputs.py verify \ + --profile "$PROFILE" \ + --source-sha "$CANDIDATE_SOURCE" --version "$CANDIDATE_VERSION" \ + --release-id "$CANDIDATE_RELEASE_ID" --run-id "$CANDIDATE_RUN_ID" \ + --run-attempt "$CANDIDATE_RUN_ATTEMPT" \ + --manifest "$ARTIFACT/release-candidate-manifest.json" \ + --bundle "$ARTIFACT/registry-stack-v${CANDIDATE_VERSION}-candidate.tar.gz" \ + --output "$STAGE" +``` + +With read access to the private candidate packages, pull the exact +references from `jq -er '.images[]' "$STAGE/inputs.json"` for +`linux/amd64`. Then run the staged driver with no GitHub credentials in its +environment. + +```sh +bash "$STAGE/source/release/scripts/candidate-host-smoke.sh" \ + "$STAGE" "$RECEIPT" +``` + +Use a new absolute receipt path. The driver checks the local image digests and +OCI source labels, runs the production-posture reference host with synthetic +users and verifies the browser result. It writes the receipt only after +teardown succeeds. The receipt binds the candidate, preview bundle, checked +BReg package and gateway configuration to the selected profile's browser +result. The Casework receipt also binds the Casework image and both Casework +executables to the same manifest and candidate attempt. ### Renew an image advisory fingerprint diff --git a/release/VERIFY.md b/release/VERIFY.md index 1be92c8099..0ef170900a 100644 --- a/release/VERIFY.md +++ b/release/VERIFY.md @@ -223,7 +223,9 @@ jq -e --arg tag "${tag}" ' elif $version.minor >= 21 then ["evidence", "mint", "relay"] else ["relay"] end) as $roster | ([.distribution_components[]?.images[].name]) as $carried | - ($roster - $carried) as $image_names | + (if ($version.major > 0 or $version.minor >= 52) + then ["coordinator", "registry-session"] else [] end) as $host_images | + (($roster + $host_images - $carried) | sort) as $image_names | ((.schema_version == "registry-stack.release-candidate.v2" and (has("distribution_components") | not)) or (.schema_version == "registry-stack.release-candidate.v3" and @@ -277,17 +279,19 @@ Registry Relay's final numbered release is `v0.38.0`; releases from `v0.39.0` omit it from the image and payload rosters. Registry Coordinator binaries join in `v0.44.0`, as set by `COORDINATOR_BINARY_FIRST_RELEASE`. Its unified Node.js and Python client namespace also joins in `v0.44.0`, under -`COORDINATOR_CLIENT_FIRST_RELEASE`. Its image remains held while -`COORDINATOR_FIRST_RELEASE` is unset. +`COORDINATOR_CLIENT_FIRST_RELEASE`. Its image, `ghcr.io/registrystack/coordinator`, joins the numbered roster in +`v0.52.0` under `COORDINATOR_FIRST_RELEASE`. Registry Adapter binaries join in `v0.46.0`, as set by `ADAPTER_FIRST_RELEASE`. Its image is authored and remains held while `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. `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. +Linux amd64, Linux arm64 and macOS arm64 payloads from `v0.51.0`. It is a +standalone asset outside the `rstack` component inventory. The Session image, +`ghcr.io/registrystack/registry-session`, packages that same Linux amd64 +executable from `v0.52.0` under `SESSION_IMAGE_FIRST_RELEASE`. 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` @@ -302,7 +306,7 @@ as their candidate bindings: ```sh while IFS=$'\t' read -r name digest final_ref; do case "${name}" in - breg|breg-mcp|breg-review|casework|coordinator|discovery|evidence|evidence-oid4vci|messaging|mint|registry-render|relay|scheduling) ;; + breg|breg-mcp|breg-review|casework|coordinator|discovery|evidence|evidence-oid4vci|messaging|mint|registry-render|registry-session|relay|scheduling) ;; *) echo "unexpected release image: ${name}" >&2; exit 1 ;; esac resolved_digest="$(crane digest "${final_ref}")" @@ -384,7 +388,8 @@ published platform inventory forward through the distribution lock and does not rebuild or relabel Discovery assets for other platforms. The Coordinator runtime `coordinator` and operator tool `coordinatorctl` join that verified binary payload under -`COORDINATOR_BINARY_FIRST_RELEASE`; its separately governed image remains held. +`COORDINATOR_BINARY_FIRST_RELEASE`. Its separately governed image joins from +`v0.52.0` under `COORDINATOR_FIRST_RELEASE`. From `v0.44.0`, the unified Node.js and Python client packages carry the `coordinator` namespace under `COORDINATOR_CLIENT_FIRST_RELEASE`. From `v0.46.0`, the Adapter runtime `adapter` and author tool `adapterctl` diff --git a/release/docker/Dockerfile.registry-session b/release/docker/Dockerfile.registry-session new file mode 100644 index 0000000000..ca0aab3469 --- /dev/null +++ b/release/docker/Dockerfile.registry-session @@ -0,0 +1,47 @@ +# syntax=docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e + +ARG SOURCE_DATE_EPOCH=0 + +FROM docker.io/library/debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 AS runtime-root +ARG SOURCE_DATE_EPOCH + +ADD --checksum=sha256:b59b0625cd1a791375d40dab23a4d5d3d0641e3d0a773501becdc3725b7f99cf https://snapshot.debian.org/archive/debian/20261114T144101Z/pool/main/g/glibc/libc6_2.41-12+deb13u5_amd64.deb /workspace/runtime-packages/libc6_2.41-12+deb13u5_amd64.deb +ADD --checksum=sha256:0966fc3da1a26cc57647c68b5736f791b6e7eb498173a7993f63b6c89b4ed4f5 https://snapshot.debian.org/archive/debian/20261114T144101Z/pool/main/g/glibc/libc6_2.41-12+deb13u5_arm64.deb /workspace/runtime-packages/libc6_2.41-12+deb13u5_arm64.deb +ADD --checksum=sha256:ff16bc048bcd7d1b256094450b79c77947d8e76fe2a24bd99b91021d591fa074 https://snapshot.debian.org/archive/debian-security/20260930T060347Z/pool/updates/main/o/openssl/libssl3t64_3.5.7-1~deb13u3_amd64.deb /workspace/runtime-packages/libssl3t64_3.5.7-1~deb13u3_amd64.deb +ADD --checksum=sha256:d0681293a160392186c6ef85a165e40603d1628a099936137d24d391bd591f97 https://snapshot.debian.org/archive/debian-security/20260930T060347Z/pool/updates/main/o/openssl/libssl3t64_3.5.7-1~deb13u3_arm64.deb /workspace/runtime-packages/libssl3t64_3.5.7-1~deb13u3_arm64.deb +ADD --checksum=sha256:8c27c342230503b73dfde629642c3b352e87b554e06d60cf58772f236a305ceb https://snapshot.debian.org/archive/debian-security/20261107T075304Z/pool/updates/main/z/zlib/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_amd64.deb /workspace/runtime-packages/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_amd64.deb +ADD --checksum=sha256:0e41b3d7ad8ad7fcd36dd4d61ca91a70018478fc4af652e044f4be770784ddff https://snapshot.debian.org/archive/debian-security/20261107T075304Z/pool/updates/main/z/zlib/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_arm64.deb /workspace/runtime-packages/zlib1g_1.3.dfsg+really1.3.1-1+deb13u1_arm64.deb +ADD --checksum=sha256:23a6f8a774d5dceda5f759b4ecdcdd652dfbefbf8271912e6a7ab0ee3250dc75 https://snapshot.debian.org/archive/debian-security/20261124T215723Z/pool/updates/main/libz/libzstd/libzstd1_1.5.7+dfsg-1+deb13u1_amd64.deb /workspace/runtime-packages/libzstd1_1.5.7+dfsg-1+deb13u1_amd64.deb +ADD --checksum=sha256:ab5ad90f986b315bfa12be50f438aa3453e32da3b29540844d2d847800d2ce08 https://snapshot.debian.org/archive/debian-security/20261124T215723Z/pool/updates/main/libz/libzstd/libzstd1_1.5.7+dfsg-1+deb13u1_arm64.deb /workspace/runtime-packages/libzstd1_1.5.7+dfsg-1+deb13u1_arm64.deb + +# Runtime configuration, issuer credentials and audit key are supplied by the +# deployment. Sessions live in memory. Mount the audit directory for persistence. +RUN --mount=type=bind,source=dist/image-bin,target=/workspace/image-bin \ + --mount=type=bind,source=LICENSE,target=/workspace/LICENSE \ + --mount=type=bind,source=THIRD_PARTY_NOTICES,target=/workspace/THIRD_PARTY_NOTICES,readonly \ + --mount=type=bind,source=release/scripts/install-runtime-packages.sh,target=/workspace/install-runtime-packages.sh,readonly \ + /workspace/install-runtime-packages.sh /workspace/runtime-root /workspace/runtime-packages \ + && mkdir -p \ + /workspace/runtime-root/etc/registry-session \ + /workspace/runtime-root/licenses/registry-session \ + /workspace/runtime-root/usr/local/bin \ + /workspace/runtime-root/var/lib/registry-session \ + && install -m 0755 /workspace/image-bin/registry-session /workspace/runtime-root/usr/local/bin/registry-session \ + && install -m 0644 /workspace/LICENSE /workspace/runtime-root/licenses/registry-session/LICENSE \ + && install -m 0644 /workspace/THIRD_PARTY_NOTICES /workspace/runtime-root/licenses/registry-session/THIRD_PARTY_NOTICES \ + && chown -R 65532:65532 /workspace/runtime-root/var/lib/registry-session \ + && chmod 0700 /workspace/runtime-root/var/lib/registry-session \ + && find /workspace/runtime-root -exec touch -h --date="@${SOURCE_DATE_EPOCH}" {} + + +FROM gcr.io/distroless/cc-debian13:nonroot@sha256:cb87acc574abe719b6e5c547384defa2f7b1f24af9605d3f618cf852495d8be2 AS runtime + +LABEL org.registrystack.runtime.uid="65532" \ + org.registrystack.runtime.gid="65532" + +COPY --from=runtime-root /workspace/runtime-root/ / + +WORKDIR /var/lib/registry-session + +# Keep the check listener private to the gateway. The deployment owns probes. +ENTRYPOINT ["/usr/local/bin/registry-session"] +CMD ["--runtime-config", "/etc/registry-session/runtime.yaml"] diff --git a/release/scripts/build-release-binaries.sh b/release/scripts/build-release-binaries.sh index 430cda0290..1c6289104b 100755 --- a/release/scripts/build-release-binaries.sh +++ b/release/scripts/build-release-binaries.sh @@ -164,8 +164,12 @@ if [[ "${coordinator_in_release}" == true ]]; then include_coordinator=1 fi include_coordinator_image=0 +coordinator_image_predicate=coordinator-in-release +if [[ -n "${nightly_tag}" ]]; then + coordinator_image_predicate=coordinator-nightly-image-in-release +fi coordinator_image_in_release="$(python3 "${script_dir}/release_roster.py" \ - coordinator-in-release "${version}")" + "${coordinator_image_predicate}" "${version}")" if [[ "${coordinator_image_in_release}" == true ]]; then include_coordinator_image=1 fi @@ -175,6 +179,13 @@ session_in_release="$(python3 "${script_dir}/release_roster.py" \ if [[ -z "${nightly_tag}" && "${session_in_release}" == true ]]; then include_session=1 fi +# The Session image packages the same canonical Linux amd64 executable. +include_session_image=0 +session_image_in_release="$(python3 "${script_dir}/release_roster.py" \ + session-image-in-release "${version}")" +if [[ "${include_session}" -eq 1 && "${session_image_in_release}" == true ]]; then + include_session_image=1 +fi # Adapter binaries have an independent boundary from image publication. include_adapter=0 adapter_in_release="$(python3 "${script_dir}/release_roster.py" \ @@ -375,6 +386,9 @@ build_payload() { 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}" + if [[ "${include_session_image}" -eq 1 ]]; then + cp target/release/registry-session dist/image-bin/registry-session + fi fi # One invocation per binary keeps each product's feature boundary. @@ -750,6 +764,9 @@ if [[ "${group}" == all || "${group}" == core ]]; then fi if [[ "${include_session}" -eq 1 ]]; then bin_assets+=("registry-session-${tag}-linux-amd64") + if [[ "${include_session_image}" -eq 1 ]]; then + image_bin_binaries+=(registry-session) + fi fi if [[ "${include_adapter}" -eq 1 ]]; then bin_assets+=( diff --git a/release/scripts/build-release-image.sh b/release/scripts/build-release-image.sh index b984a4915b..808923c31c 100755 --- a/release/scripts/build-release-image.sh +++ b/release/scripts/build-release-image.sh @@ -24,7 +24,7 @@ release_image_context="${RELEASE_IMAGE_CONTEXT:-${repo_root}}" created_builder=false case "${name}" in - discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator|adapter) + discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator|adapter|registry-session) dockerfile="${repo_root}/release/docker/Dockerfile.${name}" ;; *) diff --git a/release/scripts/candidate-host-casework.compose.yaml b/release/scripts/candidate-host-casework.compose.yaml new file mode 100644 index 0000000000..5e9fadd119 --- /dev/null +++ b/release/scripts/candidate-host-casework.compose.yaml @@ -0,0 +1,15 @@ +# Apply after the reference host's Casework overlay in candidate mode. +services: + casework: + image: ${CANDIDATE_CASEWORK_IMAGE:?Set the verified Casework candidate image reference} + entrypoint: [/usr/local/bin/casework] + volumes: !override + - ${REFERENCE_CONFIG}/casework/runtime:/run/casework:ro + - ${REFERENCE_CONFIG}/casework/audit:/var/lib/casework + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + casework-admin: + image: ${CANDIDATE_CASEWORK_IMAGE:?Set the verified Casework candidate image reference} + entrypoint: [/usr/local/bin/caseworkctl] + volumes: !override + - ${REFERENCE_CONFIG}/casework/admin:/run/casework:ro + - ${REFERENCE_CONFIG}/casework/audit:/var/lib/casework diff --git a/release/scripts/candidate-host-smoke.sh b/release/scripts/candidate-host-smoke.sh new file mode 100644 index 0000000000..e4111e0e64 --- /dev/null +++ b/release/scripts/candidate-host-smoke.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail + +stage=${1:?Pass the absolute directory produced by candidate_host_inputs.py verify} +[[ "$stage" == /* ]] || { + printf 'Pass an absolute candidate stage path. +' >&2 + exit 2 +} +exec bash "$stage/source/deploy/examples/business-registration/tests/run-reference.sh" --candidate "$@" diff --git a/release/scripts/candidate-host.compose.yaml b/release/scripts/candidate-host.compose.yaml new file mode 100644 index 0000000000..d9448ab7e6 --- /dev/null +++ b/release/scripts/candidate-host.compose.yaml @@ -0,0 +1,24 @@ +# Used with deploy/examples/business-registration/compose.yaml. +services: + session: + image: ${CANDIDATE_SESSION_IMAGE:?Set the verified Session candidate image reference} + breg: + image: ${CANDIDATE_BREG_IMAGE:?Set the verified BReg candidate image reference} + entrypoint: [/usr/local/bin/breg] + volumes: !override + - ${REFERENCE_CONFIG}/breg/runtime:/run/breg:ro + - ${REFERENCE_CONFIG}/breg/audit:/var/lib/breg + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + breg-admin: + image: ${CANDIDATE_BREG_IMAGE:?Set the verified BReg candidate image reference} + entrypoint: [/usr/local/bin/bregctl] + volumes: !override + - ${CANDIDATE_BREG_ADMIN_DIR:?Set the BReg admin input directory}:/run/breg:ro + - ${REFERENCE_CONFIG}/breg/audit:/var/lib/breg + - ${REFERENCE_CONFIG}/trust:/run/trust:ro + application: + build: !reset null + image: node:24.22.3@sha256:dc26ae92c9fb15cf6b1d63e20f0944b2efe0f115b20e00be48fb23fceb061c54 + entrypoint: [node, /app/host.mjs] + volumes: + - ${REFERENCE_HOST:?Set the staged reference host directory}:/app:ro diff --git a/release/scripts/candidate_host_inputs.py b/release/scripts/candidate_host_inputs.py new file mode 100644 index 0000000000..f12f5179c8 --- /dev/null +++ b/release/scripts/candidate_host_inputs.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Authenticate and stage the exact inputs for the candidate reference host.""" + +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +from release_candidate import ( + CandidateError, + REPOSITORY, + WORKFLOW_PATH, + WORKFLOW_REF, + extract_candidate_bundle, + read_json, + require_digest, + require_sha, + require_sha256, + sha256_file, + validate_candidate_manifest, + workflow_run_from_json, +) +from client_registry import web_npm_tarball + + +ROOT = Path(__file__).resolve().parents[2] +RECIPE = "deploy/examples/business-registration" +PREVIEW = "products/platform/examples/service-previews/business-registration" +LOCK_HELPER = "products/platform/scripts/prepare-service-preview-locks.mjs" +PROFILES = ("breg", "casework") +SOURCE_PATHS = ( + RECIPE, + PREVIEW, + LOCK_HELPER, + "products/casework/examples/standalone-decision/casework.yaml", + "clients/typescript/package.json", + "clients/typescript/package-lock.json", + "release/scripts/candidate-host.compose.yaml", + "release/scripts/candidate-host-casework.compose.yaml", + "release/scripts/candidate-host-smoke.sh", +) + + +def host_inputs(manifest, profile): + if profile not in PROFILES: + raise CandidateError(f"unsupported candidate host profile: {profile}") + version = manifest["release"]["version"] + web_client = web_npm_tarball(version) + if web_client is None: + raise CandidateError("candidate host requires the packaged web client") + binaries = ("rstack", "breg", "bregctl", "registry-session") + image_names = ("breg", "registry-session") + if profile == "casework": + binaries += ("casework", "caseworkctl") + image_names += ("casework",) + paths = {binary: f"{binary}-v{version}-linux-amd64" for binary in binaries} + paths["client.tgz"] = web_client + images = {image["name"]: image for image in manifest["images"]} + refs = {} + for name in image_names: + if name not in images: + raise CandidateError(f"candidate host requires the {name} candidate image") + image = images[name] + digest = require_digest(image["digest"], f"{name} candidate digest") + ref = f"ghcr.io/registrystack/{name}-candidate@{digest}" + if digest == "sha256:" + "0" * 64 or image["candidate_ref"] != ref: + raise CandidateError(f"candidate host requires a real private digest for {name}") + refs[name] = ref + return paths, refs + + +def require_digest_match(path, expected): + require_sha256(expected, "staged asset SHA-256") + if sha256_file(path) != expected: + raise CandidateError(f"candidate host input sha256 mismatch: {path.name}") + + +def verify_and_stage(args): + source = require_sha(args.source_sha, "candidate source SHA") + git = ["git", "-C", str(ROOT)] + head = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip() + if head != source: + raise CandidateError("candidate host checkout is not the exact candidate source") + subprocess.run([*git, "diff", "--quiet", "HEAD", "--"], check=True) + in_progress = args.current_run + if in_progress and ( + os.environ.get("GITHUB_ACTIONS") != "true" + or os.environ.get("GITHUB_REPOSITORY") != REPOSITORY + or os.environ.get("GITHUB_REF") != WORKFLOW_REF + or os.environ.get("GITHUB_SHA") != source + or os.environ.get("GITHUB_WORKFLOW_REF") != f"{REPOSITORY}/{WORKFLOW_PATH}@{WORKFLOW_REF}" + or os.environ.get("GITHUB_RUN_ID") != str(args.run_id) + or os.environ.get("GITHUB_RUN_ATTEMPT") != str(args.run_attempt) + ): + raise CandidateError("in-progress proof requires the same protected candidate workflow run") + run_json = subprocess.check_output([ + "gh", "api", f"repos/{REPOSITORY}/actions/runs/{args.run_id}/attempts/{args.run_attempt}" + ], text=True) + expected = dict( + expected_source_sha=source, + expected_workflow_revision=source, + expected_version=args.version, + expected_release_id=args.release_id, + expected_unit="stack", + expected_run_id=args.run_id, + expected_run_attempt=args.run_attempt, + workflow_run_metadata=workflow_run_from_json(json.loads(run_json)), + allow_current_run_in_progress=in_progress, + ) + manifest_sha256 = sha256_file(args.manifest) + bundle_sha256 = sha256_file(args.bundle) + for subject in (args.manifest, args.bundle): + subprocess.run([ + "gh", "attestation", "verify", str(subject), "--repo", REPOSITORY, + "--signer-workflow", f"{REPOSITORY}/{WORKFLOW_PATH}", + "--signer-digest", source, "--source-ref", WORKFLOW_REF, + "--source-digest", source, "--deny-self-hosted-runners", + ], check=True) + require_digest_match(args.manifest, manifest_sha256) + require_digest_match(args.bundle, bundle_sha256) + document = read_json(args.manifest) + manifest = validate_candidate_manifest(document, **expected) + bundle_record = manifest["bundle"] + if ( + args.bundle.name != bundle_record["name"] + or bundle_sha256 != bundle_record["sha256"] + or args.bundle.stat().st_size != bundle_record["size"] + ): + raise CandidateError("candidate bundle differs from its sealed name, digest, or size") + paths, images = host_inputs(manifest, args.profile) + args.output.mkdir(mode=0o700) + with tempfile.TemporaryDirectory(dir=args.output) as work: + root = extract_candidate_bundle(args.bundle, Path(work) / "bundle") + require_digest_match(args.bundle, bundle_sha256) + validate_candidate_manifest(document, bundle_root=root, **expected) + records = {record["name"]: record for record in manifest["payloads"]} + staged = {} + for name, asset in paths.items(): + expected_kind = "client-package" if name == "client.tgz" else "binary" + record = records.get(asset) + if record is None or record["kind"] != expected_kind: + raise CandidateError(f"candidate host requires sealed asset {asset}") + destination = args.output / name + shutil.copyfile(root / asset, destination) + require_digest_match(destination, record["sha256"]) + destination.chmod(0o400 if name == "client.tgz" else 0o500) + staged[name] = {"asset": asset, "sha256": record["sha256"]} + tree = args.output / "source" + tree.mkdir() + archive = Path(work) / "source.tar" + subprocess.run([*git, "archive", "--format=tar", f"--output={archive}", + source, *SOURCE_PATHS], check=True) + subprocess.run(["tar", "-xf", str(archive), "-C", str(tree)], check=True) + binding = { + "profile": args.profile, + "release": manifest["release"], + "workflow": manifest["workflow"], + "manifest_sha256": manifest_sha256, + "bundle_sha256": bundle_sha256, + "assets": staged, + "images": images, + } + (args.output / "inputs.json").write_text(json.dumps(binding, indent=2) + "\n") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + verify = commands.add_parser("verify") + for option in ("manifest", "bundle", "output"): + verify.add_argument(f"--{option}", type=Path, required=True) + for option in ("source-sha", "version", "release-id"): + verify.add_argument(f"--{option}", required=True) + for option in ("run-id", "run-attempt"): + verify.add_argument(f"--{option}", type=int, required=True) + verify.add_argument("--profile", choices=PROFILES, required=True) + verify.add_argument("--current-run", action="store_true") + args = parser.parse_args() + try: + verify_and_stage(args) + except (CandidateError, OSError, subprocess.CalledProcessError, json.JSONDecodeError) as exc: + print(f"Candidate host verification failed: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/release/scripts/check-debian13-images.py b/release/scripts/check-debian13-images.py index 5fbe938119..1fa0f64359 100755 --- a/release/scripts/check-debian13-images.py +++ b/release/scripts/check-debian13-images.py @@ -142,6 +142,7 @@ def archive_version(version: str) -> str: Path("release/docker/Dockerfile.scheduling"), Path("release/docker/Dockerfile.messaging"), Path("release/docker/Dockerfile.coordinator"), + Path("release/docker/Dockerfile.registry-session"), Path("release/docker/Dockerfile.adapter"), ) @@ -237,6 +238,11 @@ def archive_version(version: str) -> str: "entrypoint": 'ENTRYPOINT ["/usr/local/bin/coordinator"]', "command": 'CMD ["--runtime-config", "/etc/registry-coordinator/runtime.yaml"]', }, + Path("release/docker/Dockerfile.registry-session"): { + "binary": "registry-session", + "entrypoint": 'ENTRYPOINT ["/usr/local/bin/registry-session"]', + "command": 'CMD ["--runtime-config", "/etc/registry-session/runtime.yaml"]', + }, Path("release/docker/Dockerfile.adapter"): { "binary": "adapter", "tool": "adapterctl", diff --git a/release/scripts/check-gates-inventory.py b/release/scripts/check-gates-inventory.py index 98506e34a5..c8af265eeb 100644 --- a/release/scripts/check-gates-inventory.py +++ b/release/scripts/check-gates-inventory.py @@ -117,6 +117,14 @@ ), ("MCP dependency boundary", "python3 products/platform/scripts/check-mcp-dependencies.py"), ("MCP configuration schema drift", "run: cargo test --locked -p registry-mcp --features schema --lib schema::tests"), + ( + "Session dependency boundary", + "run: python3 products/platform/scripts/check-session-dependencies.py", + ), + ( + "Session dependency boundary tests", + "run: python3 -m unittest products/platform/scripts/test_check_session_dependencies.py", + ), ("Cargo deny", "run: cargo deny check"), ( "Standalone Cargo lockfiles", diff --git a/release/scripts/cleanup-release-candidates.py b/release/scripts/cleanup-release-candidates.py index 1d9f1b088e..282853cf38 100755 --- a/release/scripts/cleanup-release-candidates.py +++ b/release/scripts/cleanup-release-candidates.py @@ -44,6 +44,7 @@ "evidence", "evidence-oid4vci", "registry-render", + "registry-session", "mint", "breg", "breg-mcp", diff --git a/release/scripts/collect-rehearsal-advisory-evidence.py b/release/scripts/collect-rehearsal-advisory-evidence.py index 3e9180d80c..e8e7b80696 100755 --- a/release/scripts/collect-rehearsal-advisory-evidence.py +++ b/release/scripts/collect-rehearsal-advisory-evidence.py @@ -38,6 +38,7 @@ "evidence-oid4vci", "messaging", "registry-render", + "registry-session", "scheduling", } ) diff --git a/release/scripts/merge-release-binary-shards.py b/release/scripts/merge-release-binary-shards.py index 5607bf7686..63b87486ab 100755 --- a/release/scripts/merge-release-binary-shards.py +++ b/release/scripts/merge-release-binary-shards.py @@ -142,7 +142,10 @@ def rosters( ] ) if nightly_tag is None and release_roster.session_in_release(parsed): - common.append(f"registry-session-{tag}-linux-amd64") + session = f"registry-session-{tag}-linux-amd64" + common.append(session) + if release_roster.session_image_in_release(parsed): + image_bins.append(("registry-session", session)) if release_roster.adapter_in_release(parsed): common.extend( [ @@ -165,7 +168,12 @@ def rosters( image_bins.append( ("registry-render", f"registry-render-{tag}-linux-amd64") ) - if release_roster.coordinator_in_release(parsed): + coordinator_image = ( + release_roster.coordinator_in_release(parsed) + if nightly_tag is None + else release_roster.coordinator_nightly_image_in_release(parsed) + ) + if coordinator_image: for binary in ("coordinator", "coordinatorctl"): image_bins.append((binary, f"{binary}-{tag}-linux-amd64")) if release_roster.adapter_image_in_release(parsed): diff --git a/release/scripts/nightly_release.py b/release/scripts/nightly_release.py index 88f826b819..1e69718391 100644 --- a/release/scripts/nightly_release.py +++ b/release/scripts/nightly_release.py @@ -336,8 +336,15 @@ def read_manifest(path: Path) -> dict: def image_names(version: str) -> list[str]: - # The release roster remains the owner of image membership. - return sorted(release_candidate._candidate_image_names(version)) + # Session is a numbered release image. Nightlies keep their frozen roster. + names = ( + release_candidate._candidate_image_names(version) + - release_candidate.SESSION_RUNTIME_IMAGE_NAMES + ) + parsed = tuple(int(part) for part in version.split(".")) + if not release_roster.coordinator_nightly_image_in_release(parsed): + names -= release_candidate.COORDINATOR_RUNTIME_IMAGE_NAMES + return sorted(names) def historical_image_names(version: str) -> list[str]: @@ -366,7 +373,7 @@ def current_roster(version: str, tag: str) -> dict: raise NightlyError("nightly roster version does not match its tag") parsed = tuple(int(part) for part in version.split(".")) if parsed >= release_roster.ALL_PLATFORMS_FIRST_RELEASE: - coordinator_image = release_roster.coordinator_in_release(parsed) + coordinator_image = release_roster.coordinator_nightly_image_in_release(parsed) if release_roster.language_server_in_release(parsed): return frozen_roster( V2_7_ROSTER_PROFILE if coordinator_image else V2_6_ROSTER_PROFILE, @@ -377,7 +384,7 @@ def current_roster(version: str, tag: str) -> dict: else: profile = V2_3_ROSTER_PROFILE if coordinator_image else V2_2_ROSTER_PROFILE return frozen_roster(profile, tag) - if release_roster.coordinator_in_release(parsed): + if release_roster.coordinator_nightly_image_in_release(parsed): return frozen_roster(V2_1_ROSTER_PROFILE, tag) return frozen_roster(V2_ROSTER_PROFILE, tag) diff --git a/release/scripts/release_candidate.py b/release/scripts/release_candidate.py index 47af0ecffc..c2771cda89 100644 --- a/release/scripts/release_candidate.py +++ b/release/scripts/release_candidate.py @@ -97,6 +97,7 @@ # Registry Coordinator joins the release set from the release that # release_roster.COORDINATOR_FIRST_RELEASE names. COORDINATOR_RUNTIME_IMAGE_NAMES = {"coordinator"} +SESSION_RUNTIME_IMAGE_NAMES = {"registry-session"} # The Registry Adapter facade image joins the release set from the release that # release_roster.ADAPTER_IMAGE_FIRST_RELEASE names. ADAPTER_RUNTIME_IMAGE_NAMES = {"adapter"} @@ -147,6 +148,7 @@ | RENDER_RUNTIME_IMAGE_NAMES | EVIDENCE_OID4VCI_RUNTIME_IMAGE_NAMES | COORDINATOR_RUNTIME_IMAGE_NAMES + | SESSION_RUNTIME_IMAGE_NAMES | ADAPTER_RUNTIME_IMAGE_NAMES ) for directory, suffix in ( @@ -191,6 +193,8 @@ def _candidate_image_names(version: str) -> set[str]: image_names = image_names | EVIDENCE_OID4VCI_RUNTIME_IMAGE_NAMES if release_roster.coordinator_in_release(parsed): image_names = image_names | COORDINATOR_RUNTIME_IMAGE_NAMES + if release_roster.session_image_in_release(parsed): + image_names = image_names | SESSION_RUNTIME_IMAGE_NAMES if release_roster.adapter_image_in_release(parsed): image_names = image_names | ADAPTER_RUNTIME_IMAGE_NAMES if not release_roster.relay_in_release(parsed): diff --git a/release/scripts/release_roster.py b/release/scripts/release_roster.py index 12dcd8c463..d3fa0923ca 100644 --- a/release/scripts/release_roster.py +++ b/release/scripts/release_roster.py @@ -49,6 +49,9 @@ its image-specific security evidence join. They remain held until that evidence is ready. ``COORDINATOR_BINARY_FIRST_RELEASE`` independently adds the runtime, operator CLI, and installer in v0.44.0. Client facades are governed independently. +``COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE`` holds the Coordinator image out of +nightlies until its release advisory baseline is reviewed. A nightly never +carries the image ahead of the numbered release. ``ADAPTER_FIRST_RELEASE`` decides when the Registry Adapter binaries join the Stack train: the ``adapter`` facade, the ``adapterctl`` author tool and their @@ -70,8 +73,10 @@ ``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. +a standalone release asset that ``rstack`` does not install. +``SESSION_IMAGE_FIRST_RELEASE`` adds the Session image, built from that +canonical Linux amd64 executable, from v0.52.0. The image and the frozen +nightly inventories are independent of the binary 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 @@ -110,11 +115,14 @@ # Held until native facade and packaging checks pass; no image or binary inference. RENDER_CLIENT_FIRST_RELEASE: tuple[int, int, int] | None = None -COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = None +COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = (0, 52, 0) +# Held until the Coordinator release advisory baseline is reviewed. +COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE: tuple[int, int, int] | None = None DOCUMENTS_FIRST_RELEASE: tuple[int, int, int] | None = None SESSION_FIRST_RELEASE: tuple[int, int, int] | None = (0, 51, 0) +SESSION_IMAGE_FIRST_RELEASE: tuple[int, int, int] = (0, 52, 0) COORDINATOR_BINARY_FIRST_RELEASE: tuple[int, int, int] = (0, 44, 0) @@ -281,6 +289,19 @@ def coordinator_in_release(version: tuple[int, int, int]) -> bool: return first_release is not None and tuple(version) >= first_release +def coordinator_nightly_image_in_release(version: tuple[int, int, int]) -> bool: + """Return whether a nightly at base ``version`` carries the Coordinator image. + + The constants are read at call time so tests can patch them. + """ + first_release = COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE + return ( + coordinator_in_release(version) + and first_release is not None + and tuple(version) >= first_release + ) + + def documents_in_release(version: tuple[int, int, int]) -> bool: """Return whether the release at ``version`` ships Registry Document Store. @@ -299,6 +320,11 @@ def session_in_release(version: tuple[int, int, int]) -> bool: return first_release is not None and tuple(version) >= first_release +def session_image_in_release(version: tuple[int, int, int]) -> bool: + """Return whether the release ships the Session image and its evidence.""" + return tuple(version) >= SESSION_IMAGE_FIRST_RELEASE + + def coordinator_binaries_in_release(version: tuple[int, int, int]) -> bool: """Binary distribution does not waive the independent image evidence gate.""" return tuple(version) >= COORDINATOR_BINARY_FIRST_RELEASE or coordinator_in_release(version) @@ -457,12 +483,21 @@ def main(argv: list[str] | None = None) -> int: ) coordinator.add_argument("version", type=version_argument, help="release version as X.Y.Z") coordinator.set_defaults(in_release=coordinator_in_release) + coordinator_nightly_image = commands.add_parser( + "coordinator-nightly-image-in-release", + help="print true when a nightly at the base version carries the Coordinator image, else false", + ) + coordinator_nightly_image.add_argument("version", type=version_argument, help="release version as X.Y.Z") + coordinator_nightly_image.set_defaults(in_release=coordinator_nightly_image_in_release) documents = commands.add_parser( "documents-in-release", help="print true when the release version ships Registry Document Store, else false", ) documents.add_argument("version", type=version_argument, help="release version as X.Y.Z") documents.set_defaults(in_release=documents_in_release) + session_image = commands.add_parser("session-image-in-release") + session_image.add_argument("version", type=version_argument) + session_image.set_defaults(in_release=session_image_in_release) render = commands.add_parser( "render-in-release", help="print true when the release version ships Registry Render, else false", diff --git a/release/scripts/smoke-release-image-oci-labels.sh b/release/scripts/smoke-release-image-oci-labels.sh index 238cafaca4..04e10ce18d 100755 --- a/release/scripts/smoke-release-image-oci-labels.sh +++ b/release/scripts/smoke-release-image-oci-labels.sh @@ -6,7 +6,7 @@ repo_root="$(cd -- "${script_dir}/../.." && pwd)" checker="${script_dir}/check-release-image-oci-labels.py" image_builder="${script_dir}/build-release-image.sh" layout_comparator="${script_dir}/compare-release-image-layouts.py" -images=(evidence evidence-oid4vci discovery registry-render breg breg-mcp breg-review casework scheduling messaging coordinator adapter) +images=(evidence evidence-oid4vci discovery registry-render breg breg-mcp breg-review casework scheduling messaging coordinator adapter registry-session) # The stateful product images carry their operator tool beside the runtime. operator_tools=(bregctl caseworkctl schedulingctl messagingctl coordinatorctl adapterctl) sample_dockerfile="${repo_root}/release/docker/Dockerfile.evidence" diff --git a/release/scripts/test_candidate_host_smoke.py b/release/scripts/test_candidate_host_smoke.py new file mode 100644 index 0000000000..e42b787611 --- /dev/null +++ b/release/scripts/test_candidate_host_smoke.py @@ -0,0 +1,308 @@ +"""Contract checks for the release-profile Compose proof.""" + +from argparse import Namespace +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from unittest import TestCase, mock, skipUnless + +import yaml + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "release/scripts")) + +import candidate_host_inputs as inputs +WORKFLOW = ROOT / ".github/workflows/release-candidate.yml" +RECIPE = ROOT / "deploy/examples/business-registration" +OVERLAY = ROOT / "release/scripts/candidate-host.compose.yaml" +DRIVER = ROOT / "release/scripts/candidate-host-smoke.sh" +RUNNER = RECIPE / "tests/run-reference.sh" +CASEWORK_OVERLAY = ROOT / "release/scripts/candidate-host-casework.compose.yaml" +DIGEST = "sha256:" + "1" * 64 + + +def candidate_ref(image): + return f"ghcr.io/registrystack/{image}-candidate@{DIGEST}" + + +class CandidateHostSmokeTest(TestCase): + def test_exact_host_candidates_and_asset_names(self): + manifest = { + "release": {"version": "0.52.0"}, + "images": [ + {"name": name, "digest": DIGEST, "candidate_ref": candidate_ref(name)} + for name in ("breg", "registry-session", "casework", "coordinator") + ], + } + paths, refs = inputs.host_inputs(manifest, "breg") + self.assertEqual(set(refs), {"breg", "registry-session"}) + self.assertEqual(refs["registry-session"], candidate_ref("registry-session")) + self.assertEqual( + paths, + { + "rstack": "rstack-v0.52.0-linux-amd64", + "breg": "breg-v0.52.0-linux-amd64", + "bregctl": "bregctl-v0.52.0-linux-amd64", + "registry-session": "registry-session-v0.52.0-linux-amd64", + "client.tgz": "registrystack-client-0.52.0.tgz", + }, + ) + casework_paths, casework_refs = inputs.host_inputs(manifest, "casework") + self.assertEqual(casework_refs, {**refs, "casework": candidate_ref("casework")}) + self.assertEqual(casework_paths, { + **paths, + "casework": "casework-v0.52.0-linux-amd64", + "caseworkctl": "caseworkctl-v0.52.0-linux-amd64", + }) + self.assertIn("products/casework/examples/standalone-decision/casework.yaml", + inputs.SOURCE_PATHS) + for profile, missing in (("breg", "registry-session"), ("casework", "casework")): + with self.subTest(profile=profile), self.assertRaisesRegex(inputs.CandidateError, missing): + inputs.host_inputs({**manifest, "images": [ + image for image in manifest["images"] if image["name"] != missing + ]}, profile) + with self.assertRaisesRegex(inputs.CandidateError, "profile"): + inputs.host_inputs(manifest, "coordinator") + + def test_image_selection_refuses_mutable_public_or_placeholder_refs(self): + for name in ("breg", "registry-session", "casework"): + for digest, ref in ( + (DIGEST, f"ghcr.io/registrystack/{name}-candidate:v0.52.0"), + (DIGEST, f"ghcr.io/registrystack/{name}@{DIGEST}"), + ("sha256:" + "0" * 64, f"ghcr.io/registrystack/{name}-candidate@sha256:" + "0" * 64), + ): + with self.subTest(image=name, reference=ref): + manifest = { + "release": {"version": "0.52.0"}, + "images": [ + {"name": image, "digest": DIGEST, "candidate_ref": candidate_ref(image)} + if image != name else {"name": name, "digest": digest, "candidate_ref": ref} + for image in ("breg", "registry-session", "casework") + ], + } + with self.assertRaisesRegex(inputs.CandidateError, "real private digest"): + inputs.host_inputs(manifest, "casework") + + def test_current_run_verification_rejects_external_context_before_gh(self): + source = "2" * 40 + args = Namespace(source_sha=source, run_id=1, run_attempt=1, current_run=True) + with mock.patch.dict(os.environ, {}, clear=True), \ + mock.patch.object(inputs.subprocess, "check_output", return_value=source) as output, \ + mock.patch.object(inputs.subprocess, "run"): + with self.assertRaisesRegex(inputs.CandidateError, "same protected"): + inputs.verify_and_stage(args) + output.assert_called_once() + + def test_bundle_digest_is_verified_before_extraction(self): + source = "2" * 40 + with tempfile.TemporaryDirectory() as work: + scratch = Path(work) + args = Namespace( + source_sha=source, run_id=1, run_attempt=1, current_run=False, + manifest=scratch / "manifest.json", bundle=scratch / "bundle.tar.gz", + output=scratch / "output", version="0.52.0", release_id="beta", profile="casework", + ) + args.manifest.write_text("{}") + args.bundle.write_bytes(b"other bytes") + sealed = {"bundle": {"name": args.bundle.name, "sha256": "1" * 64, "size": 12}} + with ( + mock.patch.object(inputs.subprocess, "check_output", side_effect=[source, "{}"]), + mock.patch.object(inputs.subprocess, "run") as run, + mock.patch.object(inputs, "workflow_run_from_json"), + mock.patch.object(inputs, "validate_candidate_manifest", return_value=sealed), + mock.patch.object(inputs, "extract_candidate_bundle") as extract, + ): + with self.assertRaisesRegex(inputs.CandidateError, "sealed name, digest, or size"): + inputs.verify_and_stage(args) + extract.assert_not_called() + self.assertFalse(args.output.exists()) + for call in run.call_args_list[1:]: + self.assertIn("--deny-self-hosted-runners", call.args[0]) + self.assertIn("--signer-digest", call.args[0]) + self.assertIn("--source-digest", call.args[0]) + self.assertEqual(len(run.call_args_list), 3) + + def test_staged_bytes_reject_substitution(self): + with tempfile.TemporaryDirectory() as work: + scratch = Path(work) + asset = scratch / "file" + asset.write_bytes(b"candidate") + expected = inputs.sha256_file(asset) + inputs.require_digest_match(asset, expected) + asset.write_bytes(b"other") + with self.assertRaisesRegex(inputs.CandidateError, "sha256 mismatch"): + inputs.require_digest_match(asset, expected) + + @skipUnless(shutil.which("docker"), "Compose v2 is required") + def test_merged_recipe_has_only_digest_images_and_one_read_only_admin_mount(self): + with tempfile.TemporaryDirectory() as work: + for profile in ("breg", "casework"): + for area in ("admin", "rehearsal"): + with self.subTest(profile=profile, area=area): + admin_dir = str(Path(work) / "breg" / area) + files = [RECIPE / "compose.yaml"] + if profile == "casework": + files.append(RECIPE / "casework/compose.yaml") + files.append(OVERLAY) + if profile == "casework": + files.append(CASEWORK_OVERLAY) + result = subprocess.run( + ["docker", "compose", "--env-file", "/dev/null", "--profile", "setup", + *[item for path in files for item in ("--file", str(path))], + "config", "--format", "json"], + check=True, + capture_output=True, + text=True, + env={ + **os.environ, + "REFERENCE_CONFIG": work, + "REFERENCE_ARTIFACTS": work, + "REFERENCE_SESSION_DIGEST": DIGEST, + "REFERENCE_HOST": work, + "REFERENCE_HOST_CLIENT": work, + "BUSINESS_BUNDLE": work, + "BUSINESS_BUNDLE_SHA256": "1" * 64, + "CANDIDATE_BREG_IMAGE": candidate_ref("breg"), + "CANDIDATE_SESSION_IMAGE": candidate_ref("registry-session"), + "CANDIDATE_CASEWORK_IMAGE": candidate_ref("casework"), + "CANDIDATE_BREG_ADMIN_DIR": admin_dir, + }, + ) + services = json.loads(result.stdout)["services"] + for name, service in services.items(): + self.assertRegex(service["image"], r"@sha256:[0-9a-f]{64}$", name) + self.assertNotIn("build", service, name) + self.assertEqual(services["session"]["image"], candidate_ref("registry-session")) + self.assertEqual(services["breg"]["image"], candidate_ref("breg")) + self.assertEqual(services["breg-admin"]["image"], candidate_ref("breg")) + host = [v for v in services["application"]["volumes"] if v["target"] == "/app"] + self.assertEqual([(v["source"], v["read_only"]) for v in host], [(work, True)]) + for name in ("session", "breg", "breg-admin"): + self.assertTrue(all("/opt/native" not in v["target"] + for v in services[name]["volumes"]), name) + self.assertIn("/opt/native/registry-session", + [v["target"] for v in services["gateway-check"]["volumes"]]) + for name, source in ( + ("breg-admin", admin_dir), + ("breg", str(Path(work) / "breg" / "runtime")), + ): + mounts = [v for v in services[name]["volumes"] if v["target"] == "/run/breg"] + self.assertEqual(len(mounts), 1) + self.assertEqual(mounts[0]["source"], source) + self.assertIs(mounts[0]["read_only"], True) + + self.assertEqual("casework" in services, profile == "casework") + if profile == "casework": + for name, tool, mount_area in ( + ("casework", "casework", "runtime"), + ("casework-admin", "caseworkctl", "admin"), + ): + service = services[name] + self.assertEqual(service["image"], candidate_ref("casework")) + self.assertEqual(service["entrypoint"], [f"/usr/local/bin/{tool}"]) + self.assertTrue(all("/opt/native" not in v["target"] + for v in service["volumes"]), name) + mounts = [v for v in service["volumes"] if v["target"] == "/run/casework"] + self.assertEqual([(v["source"], v["read_only"]) for v in mounts], + [(f"{work}/casework/{mount_area}", True)]) + self.assertEqual([name for name, service in services.items() + if service.get("ports")], ["edge"]) + for name in ("session", "gateway-check"): + mounts = [v for v in services[name]["volumes"] + if v["target"] == "/run/reference/session.yaml"] + self.assertEqual([(v["source"], v["read_only"]) for v in mounts], + [(f"{work}/session.yaml", True)]) + self.assertEqual(services["casework-seed"]["profiles"], ["setup"]) + + def test_driver_selects_rehearsal_mount_without_cli_override(self): + driver = RUNNER.read_text() + self.assertIn('export CANDIDATE_BREG_ADMIN_DIR="$REFERENCE_CONFIG/breg/admin"', driver) + self.assertIn('CANDIDATE_BREG_ADMIN_DIR="$REFERENCE_CONFIG/breg/rehearsal"', driver) + self.assertIn('rehearse_command=("${run[@]}")', driver) + + def test_driver_gates_first_smoke_on_bounded_serving_probes(self): + driver = RUNNER.read_text() + wait = driver.index("wait_for_serving || refuse") + self.assertLess(driver.index('cmp "$REFERENCE_CONFIG/gateway/envoy.json"'), wait) + self.assertLess(wait, driver.index('bash "$recipe/tests/smoke.sh"')) + self.assertIn("SECONDS + 45", driver) + self.assertIn("SECONDS < deadline", driver) + self.assertIn("--max-time 2", driver) + self.assertIn("timeout --kill-after=1s 4s", driver) + for endpoint in ("/session/me", "/apply/", "8100/ready", "8200/", "8300/functions/register-business", "8500/ready"): + self.assertIn(endpoint, driver) + + def test_driver_uses_locked_playwright_and_explicit_dependency_opt_in(self): + driver = RUNNER.read_text() + self.assertIn('[[ $# == 4 && $4 == --with-deps ]]', driver) + self.assertIn("chromium_options+=(--with-deps)", driver) + install = driver.index('npm --prefix "$dependencies" ci --ignore-scripts') + chromium = driver.index('playwright-core/cli.js" install "${chromium_options[@]}" chromium') + self.assertLess(install, chromium) + + def test_workflow_is_same_run_and_read_only(self): + jobs = yaml.safe_load(WORKFLOW.read_text())["jobs"] + job = jobs["reference-host"] + self.assertEqual(set(job["needs"]), {"validate", "attest"}) + self.assertEqual(job["permissions"], { + "actions": "read", "attestations": "read", + "contents": "read", "packages": "read", + }) + self.assertEqual(job["strategy"], { + "fail-fast": False, "matrix": {"profile": ["breg", "casework"]}, + }) + self.assertNotIn("environment", job) + self.assertIn("outputs.unit == 'stack'", job["if"]) + self.assertIn("' registry-session '", job["if"]) + steps = job["steps"] + self.assertEqual(steps[0]["with"]["persist-credentials"], False) + self.assertEqual(steps[1]["with"]["name"], + "registry-stack-release-candidate-${{ github.run_id }}-${{ github.run_attempt }}") + verify = next(i for i, step in enumerate(steps) if "candidate_host_inputs.py verify" in step.get("run", "")) + pull = next(i for i, step in enumerate(steps) if "docker login" in step.get("run", "")) + run = next(i for i, step in enumerate(steps) if "candidate-host-smoke.sh" in step.get("run", "")) + self.assertLess(verify, pull) + self.assertLess(pull, run) + self.assertNotIn("env", steps[run]) + self.assertIn('"${RUNNER_TEMP}/candidate-host-receipt.json" --with-deps', + steps[run]["run"]) + self.assertEqual(steps[verify]["env"]["REFERENCE_PROFILE"], "${{ matrix.profile }}") + self.assertIn('--profile "${REFERENCE_PROFILE}"', steps[verify]["run"]) + self.assertIn('--run-id "${GITHUB_RUN_ID}" --run-attempt "${GITHUB_RUN_ATTEMPT}"', + steps[verify]["run"]) + self.assertIn("docker logout", steps[pull]["run"]) + self.assertIn("docker pull --platform linux/amd64", steps[pull]["run"]) + self.assertEqual(steps[-1]["with"]["path"], "${{ runner.temp }}/candidate-host-receipt.json") + + self.assertEqual(steps[-1]["with"]["name"], + "candidate-host-receipt-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.profile }}") + + def test_candidate_uses_the_shared_runner_and_receipt_validator(self): + self.assertIn('tests/run-reference.sh" --candidate "$@"', DRIVER.read_text()) + driver = RUNNER.read_text() + self.assertIn('compose_files+=("$recipe/compose.local.yaml")', driver) + self.assertIn('archive="$REFERENCE_ARTIFACTS/client.tgz"', driver) + self.assertIn("stagePreviewClient", driver) + self.assertIn('fixture="$recipe/tests/prepare-inputs.mjs"', driver) + self.assertIn('bash "$recipe/tests/cleanup-preview.sh"', driver) + self.assertIn('node "$recipe/tests/receipt.mjs" "$profile"', driver) + self.assertIn('run+=(--pull never)', driver) + browser = (RECIPE / "tests/browser.mjs").read_text() + self.assertIn("'--no-deps', '--pull', 'never', 'casework-seed'", browser) + + def test_candidate_uses_the_export_and_generated_holder_client(self): + driver = RUNNER.read_text() + self.assertIn('export REFERENCE_HOST="$REFERENCE_HOST_CLIENT"', driver) + self.assertNotIn('"$rstack" dev start', driver) + install = driver.index('npm ci --prefix "$preview"') + export = driver.index('"$rstack" dev export-preview') + digest = driver.index('.bundleDigest', export) + generate = driver.index('build-host-client.mjs" "$preview" "$REFERENCE_HOST_CLIENT"') + check = driver.index('build-host-client.mjs" --check "$preview" "$REFERENCE_HOST_CLIENT"') + serve = driver.index('"${up[@]}"', check) + self.assertEqual([install, export, digest, generate, check, serve], + sorted((install, export, digest, generate, check, serve))) diff --git a/release/scripts/test_check_debian13_images.py b/release/scripts/test_check_debian13_images.py index 4ed53591c8..7927fa9041 100644 --- a/release/scripts/test_check_debian13_images.py +++ b/release/scripts/test_check_debian13_images.py @@ -40,6 +40,7 @@ def test_official_runtime_images_are_required_maintained_surfaces(self) -> None: Path("release/docker/Dockerfile.scheduling"), Path("release/docker/Dockerfile.messaging"), Path("release/docker/Dockerfile.coordinator"), + Path("release/docker/Dockerfile.registry-session"), Path("release/docker/Dockerfile.adapter"), }, set(POLICY.DOCKERFILES), @@ -57,11 +58,22 @@ def test_official_runtime_images_are_required_maintained_surfaces(self) -> None: Path("release/docker/Dockerfile.scheduling"), Path("release/docker/Dockerfile.messaging"), Path("release/docker/Dockerfile.coordinator"), + Path("release/docker/Dockerfile.registry-session"), Path("release/docker/Dockerfile.adapter"), }, set(POLICY.HTTP_PROBE_DOCKERFILES), ) + def test_session_image_runs_only_its_runtime_under_the_shared_contract(self) -> None: + self.assertEqual( + { + "binary": "registry-session", + "entrypoint": 'ENTRYPOINT ["/usr/local/bin/registry-session"]', + "command": 'CMD ["--runtime-config", "/etc/registry-session/runtime.yaml"]', + }, + POLICY.HTTP_PROBE_DOCKERFILES[Path("release/docker/Dockerfile.registry-session")], + ) + def test_unrostered_release_dockerfile_is_rejected(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) diff --git a/release/scripts/test_check_gates_inventory.py b/release/scripts/test_check_gates_inventory.py index 9fa748ea33..f533f5c3a9 100644 --- a/release/scripts/test_check_gates_inventory.py +++ b/release/scripts/test_check_gates_inventory.py @@ -1021,6 +1021,21 @@ def test_mcp_guards_cannot_be_removed_from_ci(self) -> None: with self.subTest(gate=label): self.assertIn(label, self.module.missing_gates(self.workflow.replace(snippet, "true # disabled"))) + def test_session_dependency_guards_cannot_be_removed_from_ci(self) -> None: + for label, snippet in ( + ( + "Session dependency boundary", + "run: python3 products/platform/scripts/check-session-dependencies.py", + ), + ( + "Session dependency boundary tests", + "run: python3 -m unittest products/platform/scripts/test_check_session_dependencies.py", + ), + ): + with self.subTest(gate=label): + self.assertIn(snippet, self.workflow) + self.assertIn(label, self.module.missing_gates(self.workflow.replace(snippet, "run: true # disabled"))) + def test_missing_casework_schema_runner_step_is_reported(self) -> None: runner = self.casework_schema_runner.replace( "python3 products/casework/scripts/generate_openapi.py --check", diff --git a/release/scripts/test_check_release_image_oci_labels.py b/release/scripts/test_check_release_image_oci_labels.py index ba12d1ab38..e338a9a333 100644 --- a/release/scripts/test_check_release_image_oci_labels.py +++ b/release/scripts/test_check_release_image_oci_labels.py @@ -649,7 +649,7 @@ def read_calls(path: Path) -> list[list[str]]: build_calls = [ call for call in read_calls(docker_log) if call[:2] == ["buildx", "build"] ] - self.assertEqual(26, len(build_calls)) + self.assertEqual(28, len(build_calls)) dockerfiles = [] for call in build_calls: self.assertEqual(["buildx", "build"], call[:2]) @@ -686,6 +686,7 @@ def read_calls(path: Path) -> list[list[str]]: str(ROOT / "release/docker/Dockerfile.messaging"), str(ROOT / "release/docker/Dockerfile.coordinator"), str(ROOT / "release/docker/Dockerfile.adapter"), + str(ROOT / "release/docker/Dockerfile.registry-session"), }, set(dockerfiles), ) @@ -707,6 +708,7 @@ def read_calls(path: Path) -> list[list[str]]: "messaging", "coordinator", "adapter", + "registry-session", ): self.assertEqual( 2, @@ -744,6 +746,7 @@ def read_calls(path: Path) -> list[list[str]]: "coordinatorctl", "adapter", "adapterctl", + "registry-session", ) ) ) @@ -772,6 +775,7 @@ def read_calls(path: Path) -> list[list[str]]: "correct-messaging-first", "correct-coordinator-first", "correct-adapter-first", + "correct-registry-session-first", }, { Path(layout.removeprefix("oci-layout://")).name @@ -794,7 +798,7 @@ def read_calls(path: Path) -> list[list[str]]: for call in python_calls if call and call[0].endswith("compare-release-image-layouts.py") ] - self.assertEqual(13, len(comparisons)) + self.assertEqual(14, len(comparisons)) self.assertEqual(1, sum("--rootfs-only" in call for call in comparisons)) diff --git a/release/scripts/test_cleanup_release_candidates.py b/release/scripts/test_cleanup_release_candidates.py index e2a2c85320..1cc8e970bf 100644 --- a/release/scripts/test_cleanup_release_candidates.py +++ b/release/scripts/test_cleanup_release_candidates.py @@ -345,14 +345,16 @@ def test_v0_38_candidates_are_allowlisted_after_package_bootstrap(self) -> None: self.assertIn(f"{name}-candidate", self.module.CANDIDATE_PACKAGES) self.module.assert_candidate_package(f"{name}-candidate") - def test_coordinator_remains_denylisted_until_package_bootstrap(self) -> None: - self.assertIn("coordinator", self.module.PUBLIC_PACKAGES) - self.assertNotIn("coordinator-candidate", self.module.CANDIDATE_PACKAGES) - with self.assertRaisesRegex( - self.module.CleanupError, - "package is not in the exact candidate allowlist", - ): - self.module.assert_candidate_package("coordinator-candidate") + def test_host_images_remain_denylisted_until_package_bootstrap(self) -> None: + for name in ("coordinator", "registry-session"): + with self.subTest(name=name): + self.assertIn(name, self.module.PUBLIC_PACKAGES) + self.assertNotIn(f"{name}-candidate", self.module.CANDIDATE_PACKAGES) + with self.assertRaisesRegex( + self.module.CleanupError, + "package is not in the exact candidate allowlist", + ): + self.module.assert_candidate_package(f"{name}-candidate") def test_malformed_or_future_timestamp_fails_without_deleting(self) -> None: for timestamp in ("not-a-date", "2026-07-25T12:00:01Z"): diff --git a/release/scripts/test_merge_release_binary_shards.py b/release/scripts/test_merge_release_binary_shards.py index 010b140f90..d78512183c 100644 --- a/release/scripts/test_merge_release_binary_shards.py +++ b/release/scripts/test_merge_release_binary_shards.py @@ -487,6 +487,33 @@ def test_coordinator_joins_the_core_shard_only_from_v0_42(self) -> None: ) self.assertNotIn("coordinator", dict(images_held)) + def test_session_and_coordinator_image_inputs_join_numbered_v0_52(self) -> None: + host_binaries = {"registry-session", "coordinator", "coordinatorctl"} + prior_shards, prior_bins = MODULE.rosters("0.51.0") + self.assertTrue(host_binaries.isdisjoint(dict(prior_bins))) + self.assertIn("registry-session-v0.51.0-linux-amd64", prior_shards["core"]) + shards, image_bins = MODULE.rosters("0.52.0") + for binary in host_binaries: + asset = f"{binary}-v0.52.0-linux-amd64" + self.assertEqual(1, shards["core"].count(asset)) + self.assertEqual(asset, dict(image_bins)[binary]) + nightly = f"v0.52.0-nightly.20261202.{'a' * 40}" + nightly_shards, nightly_bins = MODULE.rosters("0.52.0", nightly) + self.assertNotIn("registry-session", dict(nightly_bins)) + self.assertNotIn(f"registry-session-{nightly}-linux-amd64", nightly_shards["core"]) + # The Coordinator binaries stay in the nightly, but its image inputs wait + # for the reviewed advisory baseline. + self.assertIn(f"coordinator-{nightly}-linux-amd64", nightly_shards["core"]) + self.assertNotIn("coordinator", dict(nightly_bins)) + self.assertNotIn("coordinatorctl", dict(nightly_bins)) + with mock.patch.object( + MODULE.release_roster, "COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE", (0, 52, 0) + ): + _, reviewed_bins = MODULE.rosters("0.52.0", nightly) + self.assertEqual( + f"coordinator-{nightly}-linux-amd64", dict(reviewed_bins)["coordinator"] + ) + def test_adapter_joins_the_core_shard_from_v0_46_0_without_an_image(self) -> None: rosters_045, _ = MODULE.rosters("0.45.0") self.assertFalse( diff --git a/release/scripts/test_nightly_release.py b/release/scripts/test_nightly_release.py index 3f8d1e4d6f..70f0ec1229 100644 --- a/release/scripts/test_nightly_release.py +++ b/release/scripts/test_nightly_release.py @@ -464,6 +464,7 @@ def test_v2_roster_refuses_retired_or_extra_valid_looking_assets(self): nightly.read_manifest(path) @roster_patch("release_roster.COORDINATOR_FIRST_RELEASE", (0, 42, 0)) + @roster_patch("release_roster.COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE", (0, 42, 0)) def test_coordinator_joins_the_nightly_roster_under_profile_v2_1(self): tag_40 = f"v0.40.0-nightly.20261012.{SHA}" tag_41 = f"v0.42.0-nightly.20261012.{SHA}" @@ -484,6 +485,23 @@ def test_coordinator_joins_the_nightly_roster_under_profile_v2_1(self): ) self.assertEqual(after, nightly.validate_v2_roster(after, tag_41)) + def test_coordinator_image_waits_for_its_nightly_first_release(self): + base = "0.52.0" + tag = f"v{base}-nightly.20261202.{SHA}" + held = nightly.current_roster(base, tag) + self.assertEqual("registry-stack.nightly-roster.v2.6", held["profile"]) + self.assertNotIn("coordinator", held["images"]) + self.assertNotIn("coordinator", nightly.image_names(base)) + self.assertIn(f"coordinator-{tag}-linux-amd64", held["payloads"]) + with roster_patch.object( + nightly.release_roster, "COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE", (0, 52, 0) + ): + reviewed = nightly.current_roster(base, tag) + reviewed_images = nightly.image_names(base) + self.assertEqual("registry-stack.nightly-roster.v2.7", reviewed["profile"]) + self.assertIn("coordinator", reviewed["images"]) + self.assertIn("coordinator", reviewed_images) + def test_no_nightly_roster_carries_the_document_store_while_it_is_held_out(self): # The Document Store is held out by DOCUMENTS_FIRST_RELEASE and has no # release packaging yet, so no nightly roster profile may name it. @@ -499,6 +517,7 @@ def test_no_nightly_roster_carries_the_document_store_while_it_is_held_out(self) ) @roster_patch("release_roster.COORDINATOR_FIRST_RELEASE", (0, 42, 0)) + @roster_patch("release_roster.COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE", (0, 42, 0)) def test_published_roster_profiles_keep_their_meaning(self): path = self.root / "nightly.json" tag_41 = f"v0.42.0-nightly.20261012.{SHA}" @@ -534,6 +553,7 @@ def test_published_roster_profiles_keep_their_meaning(self): nightly.read_manifest(path) @roster_patch("release_roster.COORDINATOR_FIRST_RELEASE", (0, 42, 0)) + @roster_patch("release_roster.COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE", (0, 42, 0)) def test_v0_42_nightly_publishes_coordinator(self): base = "0.42.0" tag = f"v{base}-nightly.20261012.{SHA}" diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 57e0b3cbff..618f0b891c 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -3416,6 +3416,7 @@ def test_release_packaging_uses_retained_artifact_identities(self) -> None: "scheduling", "messaging", "coordinator", + "registry-session", ) } @@ -3441,6 +3442,7 @@ def test_release_packaging_uses_retained_artifact_identities(self) -> None: "scheduling", "messaging", "coordinator", + "registry-session", ): self.assertIn( f"cp target/release/{name} dist/image-bin/{name}", @@ -3479,6 +3481,7 @@ def test_release_packaging_uses_retained_artifact_identities(self) -> None: "scheduling", "messaging", "coordinator", + "registry-session", ): self.assertIn( "--mount=type=bind,source=THIRD_PARTY_NOTICES," @@ -3492,7 +3495,7 @@ def test_release_packaging_uses_retained_artifact_identities(self) -> None: ) self.assertNotIn("THIRD_PARTY_NOTICES", release_dockerfiles["discovery"]) self.assertIn( - "discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator|adapter)", + "discovery|evidence|evidence-oid4vci|registry-render|breg|breg-mcp|breg-review|casework|scheduling|messaging|coordinator|adapter|registry-session)", image_recipe, ) self.assertNotIn("registry-relay)", image_recipe) diff --git a/release/scripts/test_release_candidate.py b/release/scripts/test_release_candidate.py index d0f20c4b4a..13dd8b1fab 100644 --- a/release/scripts/test_release_candidate.py +++ b/release/scripts/test_release_candidate.py @@ -584,6 +584,36 @@ def make_v2_candidate(self) -> tuple[dict, Path, Path, dict]: } return candidate, bundle_path, bundle_root, run + def test_public_verification_requires_both_host_images_and_preserves_digests(self): + import verify_public_release + + document, _, _, _ = self.make_v2_candidate() + checksums = {row["name"]: row["sha256"] for row in document["payloads"]} + checksums["registry-stack-v1.2.3-release-manifest.json"] = "0" * 64 + assets = {row["name"]: {"size": row["size"]} for row in document["payloads"]} + arguments = { + "repository": "registrystack/registry-stack", + "source_sha": SOURCE_SHA, + "tag": "v1.2.3", + "checksums": checksums, + "assets": assets, + } + refs = { + image["final_ref"]: image["digest"] + for image in verify_public_release.validate_release_manifest(document, **arguments) + } + for name in ("registry-session", "coordinator"): + with self.subTest(name=name): + self.assertEqual(IMAGE_DIGEST, refs[f"ghcr.io/registrystack/{name}:v1.2.3"]) + missing = { + **document, + "images": [image for image in document["images"] if image["name"] != name], + } + with self.assertRaisesRegex( + verify_public_release.PublicReleaseError, "image inventory must be exactly" + ): + verify_public_release.validate_release_manifest(missing, **arguments) + def test_v2_candidate_requires_source_to_equal_workflow_revision(self) -> None: candidate, bundle_path, bundle_root, run = self.make_v2_candidate() validated = self.module.validate_candidate_manifest( @@ -1242,6 +1272,8 @@ def test_no_version_ships_messaging_until_the_roster_names_a_first_release( expected_images |= ( self.module.COORDINATOR_RUNTIME_IMAGE_NAMES ) + if self.module.release_roster.session_image_in_release(parsed): + expected_images |= {"registry-session"} self.assertEqual( expected_images, self.module._candidate_image_names(version), @@ -1374,8 +1406,9 @@ def test_adapter_image_is_absent_from_every_roster_while_held(self) -> None: ): for version in ("0.48.0", "1.0.0"): with self.subTest(version=version): + expected_images = held_images | ({"registry-session"} if version == "1.0.0" else set()) self.assertEqual( - held_images, self.module._candidate_image_names(version) + expected_images, self.module._candidate_image_names(version) ) self.assertEqual( held_tools, self.module.image_operator_tools(version) @@ -1386,7 +1419,7 @@ def test_adapter_image_is_absent_from_every_roster_while_held(self) -> None: ["image-names", "--version", version, "--unit", "stack"] ) self.assertEqual(0, result) - self.assertEqual(held_images, set(stdout.getvalue().split())) + self.assertEqual(expected_images, set(stdout.getvalue().split())) required = self.module._security_evidence_required_files( self.module._candidate_image_names(version) ) @@ -1607,6 +1640,8 @@ def test_no_version_ships_the_breg_services_until_the_roster_names_one( expected_images |= ( self.module.COORDINATOR_RUNTIME_IMAGE_NAMES ) + if self.module.release_roster.session_image_in_release(parsed): + expected_images |= {"registry-session"} self.assertEqual( expected_images, self.module._candidate_image_names(version), diff --git a/release/scripts/test_release_repeatability_workflow.py b/release/scripts/test_release_repeatability_workflow.py index 0e187e8b45..f5cf9a15c3 100644 --- a/release/scripts/test_release_repeatability_workflow.py +++ b/release/scripts/test_release_repeatability_workflow.py @@ -69,6 +69,11 @@ def test_clean_proof_compares_binaries_and_images(self) -> None: self.assertIn('"messagingctl": "messagingctl"', self.workflow) self.assertIn('"coordinator": "coordinator"', self.workflow) self.assertIn('"coordinatorctl": "coordinatorctl"', self.workflow) + self.assertIn( + 'if release_roster.session_image_in_release(parsed_version):\n' + ' binary_names["registry-session"] = "registry-session"', + self.workflow, + ) self.assertIn('"relay": "relay"', self.workflow) self.assertIn('"relayctl": "relayctl"', self.workflow) self.assertIn( diff --git a/release/scripts/test_release_roster.py b/release/scripts/test_release_roster.py index bdc630107c..d615b2a46b 100644 --- a/release/scripts/test_release_roster.py +++ b/release/scripts/test_release_roster.py @@ -100,13 +100,30 @@ def test_unified_clients_include_coordinator_from_its_first_client_release(self) self.assertFalse(release_roster.coordinator_client_in_release((0, 41, 99))) self.assertTrue(release_roster.coordinator_client_in_release((0, 42, 0))) - def test_coordinator_runtime_is_held_until_release_prerequisites_are_ready(self) -> None: - self.assertIsNone(release_roster.COORDINATOR_FIRST_RELEASE) - for version in ((0, 41, 0), (0, 42, 0), (1, 0, 0)): + def test_host_images_join_the_numbered_roster_from_v0_52(self) -> None: + for version in ((0, 50, 0), (0, 51, 0), (0, 51, 99)): self.assertFalse(release_roster.coordinator_in_release(version)) - with mock.patch.object(release_roster, "COORDINATOR_FIRST_RELEASE", (0, 42, 0)): - self.assertFalse(release_roster.coordinator_in_release((0, 41, 99))) - self.assertTrue(release_roster.coordinator_in_release((0, 42, 0))) + self.assertFalse(release_roster.session_image_in_release(version)) + for version in ((0, 52, 0), (0, 52, 1), (1, 0, 0)): + self.assertTrue(release_roster.coordinator_in_release(version)) + self.assertTrue(release_roster.session_image_in_release(version)) + + def test_coordinator_image_is_held_out_of_nightlies_until_its_baseline_is_reviewed( + self, + ) -> None: + self.assertIsNone(release_roster.COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE) + for version in ((0, 51, 0), (0, 52, 0), (1, 0, 0)): + self.assertFalse(release_roster.coordinator_nightly_image_in_release(version)) + with mock.patch.object( + release_roster, "COORDINATOR_NIGHTLY_IMAGE_FIRST_RELEASE", (0, 52, 1) + ): + self.assertFalse(release_roster.coordinator_nightly_image_in_release((0, 52, 0))) + self.assertTrue(release_roster.coordinator_nightly_image_in_release((0, 52, 1))) + # A nightly never carries the image ahead of the numbered release. + with mock.patch.object(release_roster, "COORDINATOR_FIRST_RELEASE", None): + self.assertFalse( + release_roster.coordinator_nightly_image_in_release((0, 52, 1)) + ) def test_document_store_is_held_out_of_every_release(self) -> None: self.assertIsNone(release_roster.DOCUMENTS_FIRST_RELEASE) diff --git a/release/scripts/test_release_supporting_images.py b/release/scripts/test_release_supporting_images.py index 9d1659b013..e985f44bfa 100644 --- a/release/scripts/test_release_supporting_images.py +++ b/release/scripts/test_release_supporting_images.py @@ -9,6 +9,10 @@ ROOT = Path(__file__).resolve().parents[2] SUPPORTING_IMAGES = { + "registry-session": { + "workdir": "/var/lib/registry-session", + "command": 'CMD ["--runtime-config", "/etc/registry-session/runtime.yaml"]', + }, "breg-mcp": { "workdir": "/var/lib/breg-mcp", "command": 'CMD ["--runtime-config", "/etc/breg-mcp/runtime.yaml", "serve"]', @@ -149,7 +153,8 @@ def test_shared_publication_surfaces_admit_every_supporting_image(self) -> None: self.assertIn(f'"{name}"', collector) self.assertIn(name, smoke.split("images=(", 1)[1].split(")", 1)[0]) self.assertIn(f'"{name}",', cleanup) - self.assertIn(f'"{name}-candidate",', cleanup) + if name != "registry-session": + self.assertIn(f'"{name}-candidate",', cleanup) if __name__ == "__main__": diff --git a/release/scripts/test_release_workflow_structure.py b/release/scripts/test_release_workflow_structure.py index 90b3e5efa6..645a647c58 100644 --- a/release/scripts/test_release_workflow_structure.py +++ b/release/scripts/test_release_workflow_structure.py @@ -457,7 +457,7 @@ def test_current_release_pipeline_has_no_pre_v0_19_surface(self) -> None: self.assertEqual( (module._candidate_image_names("0.37.0") - ({"relay"} if version == "1.0.0" else set())) | {"registry-render", "evidence-oid4vci", "breg-mcp", "breg-review", "messaging"} - | ({"coordinator"} if version == "1.0.0" else set()), + | ({"coordinator", "registry-session"} if version == "1.0.0" else set()), module._candidate_image_names(version), ) # Coordinator joins a release only from the one release_roster names. @@ -541,6 +541,7 @@ def test_keeps_one_candidate_pipeline_with_narrow_permissions(self) -> None: "clients", "assemble", "attest", + "reference-host", ], ) for job in ( @@ -551,6 +552,7 @@ def test_keeps_one_candidate_pipeline_with_narrow_permissions(self) -> None: "build-platforms", "build-macos-platforms", "clients", + "reference-host", ): permissions = document["jobs"][job]["permissions"] self.assertNotEqual(permissions.get("packages"), "write") @@ -3085,7 +3087,9 @@ def test_public_verification_selects_the_versioned_image_roster(self) -> None: cases["v0.40.0"] = list(cases["v0.39.0"]) cases["v0.42.0"] = list(cases["v0.39.0"]) cases["v0.44.0"] = list(cases["v0.39.0"]) - cases["v1.0.0"] = list(cases["v0.42.0"]) + cases["v0.51.0"] = list(cases["v0.39.0"]) + cases["v0.52.0"] = sorted([*cases["v0.51.0"], "coordinator", "registry-session"]) + cases["v1.0.0"] = list(cases["v0.52.0"]) manifests = {} for tag, image_names in cases.items(): with self.subTest(tag=tag): @@ -3188,7 +3192,7 @@ def test_public_verification_selects_the_versioned_image_roster(self) -> None: ), }, ] - for tag in ("v0.40.0", "v0.42.0", "v0.44.0", "v1.0.0"): + for tag in ("v0.40.0", "v0.42.0", "v0.44.0", "v0.51.0", "v1.0.0"): with self.subTest(tag=tag, changed="coordinator"): changed = dict(manifests[tag]) changed["images"] = [ @@ -3233,7 +3237,7 @@ def test_public_verification_selects_the_versioned_image_roster(self) -> None: self.assertNotEqual(0, rejected.returncode) self.assertIn( - "breg|breg-mcp|breg-review|casework|coordinator|discovery|evidence|evidence-oid4vci|messaging|mint|registry-render|relay|scheduling)", + "breg|breg-mcp|breg-review|casework|coordinator|discovery|evidence|evidence-oid4vci|messaging|mint|registry-render|registry-session|relay|scheduling)", verify, ) self.assertIn("Registry Coordinator binaries join", verify) diff --git a/release/scripts/test_verify_public_release.py b/release/scripts/test_verify_public_release.py index 4ea5103fec..10633f988a 100644 --- a/release/scripts/test_verify_public_release.py +++ b/release/scripts/test_verify_public_release.py @@ -445,6 +445,15 @@ def test_discovery_assets_use_unit_names_and_require_provenance(self) -> None: ): self.module.verify_downloaded_assets(root, assets, tag=tag) + def test_host_image_roster_is_version_selected_in_public_candidate_validation(self) -> None: + candidate = self.module.release_candidate + host_images = {"registry-session", "coordinator"} + self.assertTrue(host_images.isdisjoint(candidate._candidate_image_names("0.51.0"))) + expected = candidate._candidate_image_names("0.52.0") + self.assertLessEqual(host_images, expected) + for name in host_images: + self.assertIn(f"grype/{name}.grype.json", candidate._security_evidence_required_files(expected)) + def test_manifest_binds_tag_source_workflow_and_final_images(self) -> None: source = "a" * 40 payload_sha256 = "d" * 64 diff --git a/release/scripts/test_zig_glibc_compiler.py b/release/scripts/test_zig_glibc_compiler.py index 7fc3f017ec..5518ca8fac 100644 --- a/release/scripts/test_zig_glibc_compiler.py +++ b/release/scripts/test_zig_glibc_compiler.py @@ -300,9 +300,9 @@ def setUp(self) -> None: "'casework', 'caseworkctl', 'scheduling', 'schedulingctl', 'messaging', " "'messagingctl', 'registry-render', 'coordinator', 'coordinatorctl', " "'adapter', 'adapterctl', " - "'registry-language-server'):\n" + "'registry-language-server', 'registry-session'):\n" " path = target / binary\n" - " if binary in ('registry-manifest', 'rstack', 'registry-language-server'):\n" + " if binary in ('registry-manifest', 'rstack', 'registry-language-server', 'registry-session'):\n" " version = (os.environ.get('FAKE_MANIFEST_VERSION') if binary == 'registry-manifest' else None) or os.environ.get('REGISTRY_NIGHTLY_TAG') or os.environ['REGISTRY_RELEASE_TAG']\n" " if binary == 'registry-language-server':\n" " version = version.removeprefix('v').split('-nightly.', 1)[0]\n" @@ -393,6 +393,17 @@ def setUp(self) -> None: for relative in ("dist/bin", "dist/image-bin"): (self.root / relative).mkdir(parents=True) + def move_copied_coordinator_first_release(self, version: tuple[int, int, int]) -> None: + # Change only the copied test recipe's roster, including its child processes. + roster = self.scripts / "release_roster.py" + source = roster.read_text() + current = "COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = (0, 52, 0)" + self.assertIn(current, source, "the copied roster no longer has the patched literal") + roster.write_text(source.replace( + current, + f"COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = {version!r}", + )) + def run_payload( self, *, @@ -623,13 +634,33 @@ def test_nightly_core_stages_language_server_with_its_cargo_version(self) -> Non ).is_file() ) + def test_numbered_session_image_reuses_the_standalone_binary(self) -> None: + for version in ("0.51.0", "0.52.0"): + with self.subTest(version=version): + result, calls = self.run_payload(version=version, group="core") + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual( + 1, sum("registry-session" in call["args"] for call in calls) + ) + asset = self.root / f"dist/bin/registry-session-v{version}-linux-amd64" + image = self.root / "dist/image-bin/registry-session" + self.assertTrue(asset.is_file()) + if version == "0.52.0": + self.assertEqual(asset.read_bytes(), image.read_bytes()) + else: + self.assertFalse(image.exists()) + + def test_nightly_core_holds_the_coordinator_image_inputs(self) -> None: + nightly_tag = f"v0.52.0-nightly.20261202.{'1' * 40}" + result, _ = self.run_payload(version="0.52.0", group="core", nightly_tag=nightly_tag) + self.assertEqual(0, result.returncode, result.stderr) + binaries, images = self.staged() + self.assertIn(f"coordinator-{nightly_tag}-linux-amd64", binaries) + self.assertNotIn("coordinator", images) + self.assertNotIn("coordinatorctl", images) + def test_core_stages_coordinator_only_from_its_first_release(self) -> None: - # Enable only the copied test recipe's roster, including its child processes. - roster = self.scripts / "release_roster.py" - roster.write_text(roster.read_text().replace( - "COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = None", - "COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = (0, 42, 0)", - )) + self.move_copied_coordinator_first_release((0, 42, 0)) result, historical_calls = self.run_payload(version="0.40.0", group="core") self.assertEqual(result.returncode, 0, result.stderr) self.assertFalse( @@ -1026,12 +1057,7 @@ def test_v0_44_coordinator_binaries_do_not_stage_held_image_inputs(self) -> None self.assertFalse((merged / "image-bin" / binary).exists()) def test_v0_42_merged_groups_stage_coordinator_in_the_core_shard(self) -> None: - # Enable only the copied test recipe's roster, including its child processes. - roster = self.scripts / "release_roster.py" - roster.write_text(roster.read_text().replace( - "COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = None", - "COORDINATOR_FIRST_RELEASE: tuple[int, int, int] | None = (0, 42, 0)", - )) + self.move_copied_coordinator_first_release((0, 42, 0)) self.assert_merged_groups_equivalent_to_all( "0.42.0", ("core", "breg", "casework", "scheduling", "messaging") )