From b7a170240ffee5c6b664882aaded2e4a8bde6fe1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 06:11:09 +0000 Subject: [PATCH 01/33] fix: replay review initiator and Record hook authority hardening Preserve the resolved Review wire contract, opt-in PublicSchema reporting, retained-work safeguards, and ordinary CI manifest comparison on the current protected source. Retain the protected source recovery and authorization checks, and allocate a distinct invariant identifier for proposing hooks. Signed-off-by: Jeremi Joslin --- .github/workflows/ci.yml | 20 +- clients/typescript/generated/casework.ts | 10 +- crates/registry-breg/src/api/context.rs | 1 + .../src/api/tests/immediate_action_tests.rs | 96 ++++++++ crates/registry-breg/src/auth.rs | 35 +++ crates/registry-breg/src/compiler.rs | 63 ++++- crates/registry-breg/src/migration.rs | 20 ++ .../registry-breg/src/migration_reconcile.rs | 1 + crates/registry-breg/src/model.rs | 79 ++++++ crates/registry-breg/src/mutation.rs | 1 + crates/registry-breg/src/mutation/action.rs | 6 + crates/registry-breg/src/review_store.rs | 78 +++++- crates/registry-breg/src/runtime_config.rs | 30 ++- crates/registry-breg/src/startup.rs | 6 + .../registry-breg/tests/compiler_webhook.rs | 130 ++++++++++ crates/registry-breg/tests/http_auth.rs | 175 +++++++++++++ .../tests/package_change_plan.rs | 71 +++++- .../tests/postgres_hook_changes.rs | 83 ++++++- .../tests/postgres_native_retention.rs | 67 +++++ .../tests/postgres_package/pre_1_0_schema.rs | 46 +++- .../tests/postgres_webhook_outbox.rs | 11 + crates/registry-breg/tests/startup_http.rs | 6 +- .../registry-bregctl/src/apply_lifecycle.rs | 6 + crates/registry-bregctl/src/doctor.rs | 5 + crates/registry-bregctl/src/identity_facts.rs | 13 + .../src/init_from_model/render.rs | 190 ++++++++------ .../src/init_from_model/resolve.rs | 194 ++++++++++++++- .../src/init_from_model/selection.rs | 50 ++++ .../src/init_from_model/wizard.rs | 100 +++++++- crates/registry-bregctl/src/lib.rs | 8 + crates/registry-bregctl/tests/cli.rs | 127 ++++++++++ .../registry-bregctl/tests/identity_facts.rs | 116 +++++++++ .../tests/publicschema_inline_value_lists.rs | 35 ++- crates/registry-bregctl/tests/tool_schema.rs | 33 +++ .../__test__/facade.test-d.ts | 8 +- .../registry-casework-client-node/client.d.ts | 2 +- .../registry_casework_client/__init__.pyi | 1 + .../tests/python/test_typing_contract.py | 6 + crates/registry-casework-core/src/config.rs | 64 ++++- .../tests/format_alignment.rs | 2 +- .../tests/policy_compiler.rs | 2 +- .../tests/principal_claims.rs | 41 +++- .../examples/problem-catalog.rs | 2 +- crates/registry-casework/src/pinned_work.rs | 74 +++++- crates/registry-casework/src/review.rs | 15 +- crates/registry-casework/src/store.rs | 12 + .../src/task_grants/http_tests.rs | 2 +- .../src/task_grants/native_exchange_tests.rs | 2 +- .../tests/access_profile_selection.rs | 1 + .../tests/breg_review_journey.rs | 26 +- .../tests/review_acceptance_postgres.rs | 3 +- crates/registry-casework/tests/review_http.rs | 7 +- .../tests/review_payment_fixture_postgres.rs | 1 + .../tests/review_postgres.rs | 232 ++++++++++++++++++ crates/registry-caseworkctl/src/identity.rs | 2 +- .../registry-caseworkctl/src/provider_add.rs | 183 +++++++++++++- crates/registry-caseworkctl/src/templates.rs | 1 + .../identity/facts-canonical-review.yaml | 7 + .../identity/facts-task-authority.yaml | 7 + .../tests/identity_facts.rs | 9 +- .../tests/provider_add.rs | 19 ++ crates/registry-coordinator/src/operations.rs | 11 +- .../registry-coordinator/tests/authoring.rs | 23 ++ crates/registry-linkml/README.md | 10 +- crates/registry-linkml/publicschema/PIN.yaml | 4 +- .../schema/agriculture_holdings.yaml | 10 +- .../publicschema/schema/common.yaml | 19 +- .../publicschema/schema/consent.yaml | 21 +- .../publicschema/schema/core.yaml | 34 +-- .../publicschema/schema/document.yaml | 6 +- .../publicschema/schema/identity.yaml | 142 ++++++++--- .../publicschema/schema/misc.yaml | 19 +- .../publicschema/schema/program.yaml | 6 +- .../publicschema/schema/public_services.yaml | 8 + .../publicschema/starters/household.yaml | 2 +- crates/registry-linkml/src/model.rs | 2 + crates/registry-linkml/src/publicschema.rs | 42 +++- crates/registry-linkml/src/reader.rs | 117 +++++++-- crates/registry-linkml/tests/snapshot.rs | 21 +- .../src/identity_facts.rs | 10 +- crates/registry-review-client/README.md | 3 + crates/registry-review-protocol/README.md | 4 + crates/registry-review-protocol/src/lib.rs | 42 +++- crates/registry-rstack-dev/src/products.rs | 1 + .../casework/client.d.ts | 2 +- .../src/content/docs/configure/casework.mdx | 10 +- .../operate/advanced/upgrade-and-retire.mdx | 24 ++ .../content/docs/operate/breg-webhooks.mdx | 34 +++ .../reference/bregctl-publicschema-wizard.mdx | 65 ++++- .../docs/reference/casework-configuration.mdx | 5 + docs/site/src/content/docs/security/breg.mdx | 25 +- .../src/content/docs/security/casework.mdx | 5 +- .../derive-a-registry-from-publicschema.mdx | 83 +++---- .../review-breg-changes-in-casework.mdx | 5 + external/README.md | 6 +- products/breg/CHANGELOG.md | 23 ++ .../casework/casework.yaml | 9 +- .../contracts/security-invariant-matrix.yaml | 4 + .../contracts/security-test-traceability.yaml | 1 + .../breg/evidence/organization-selection.yaml | 2 +- .../model-selection.v1alpha1.schema.json | 51 ++++ .../breg/scripts/test_validate_product.py | 2 +- products/breg/scripts/validate_product.py | 2 +- products/casework/CHANGELOG.md | 12 + products/casework/README.md | 5 +- .../casework/contracts/cli/report.schema.json | 7 + .../contracts/security-invariant-matrix.yaml | 2 +- .../contracts/security-test-traceability.yaml | 2 +- .../examples/canonical-review/casework.yaml | 7 +- .../generated/project/project.schema.json | 4 + .../generated/registry-casework.openapi.json | 11 + products/coordinator/CHANGELOG.md | 7 + .../generated/operations/README.md | 4 +- ...submit-review-request.v1.input.schema.json | 4 + .../generated/operations/catalog.json | 6 +- .../identifiers/generated/catalog.v1.json | 6 +- .../examples/licensing/casework/casework.yaml | 7 +- .../examples/licensing/dev-journeys.yaml | 2 +- release/scripts/check-gates-inventory.py | 2 +- release/scripts/registry-release | 153 ++++++++++-- release/scripts/test_check_gates_inventory.py | 2 +- release/scripts/test_registry_release.py | 155 +++++++++++- .../test_release_workflow_structure.py | 20 ++ 123 files changed, 3592 insertions(+), 384 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e7905196d..b27e59caa8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2914,7 +2914,25 @@ jobs: run: uv run --no-project --with PyYAML==6.0.2 python3 -m unittest release/scripts/test_check_gates_inventory.py - name: Validate release manifest - run: uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-current + env: + RELEASE_MANIFEST_BASE_REF: ${{ needs.changes.outputs.archive_base_ref }} + RELEASE_MANIFEST_COMPARISON_REQUIRED: ${{ needs.changes.outputs.archive_comparison_required }} + shell: bash + run: | + set -euo pipefail + validate=(uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-current-ci) + if [[ "${RELEASE_MANIFEST_COMPARISON_REQUIRED}" == "true" ]]; then + if [[ -z "${RELEASE_MANIFEST_BASE_REF}" ]]; then + echo "Cannot validate the inherited release manifest: the event baseline is unavailable." >&2 + exit 1 + fi + "${validate[@]}" --base-ref "${RELEASE_MANIFEST_BASE_REF}" + elif [[ "${RELEASE_MANIFEST_COMPARISON_REQUIRED}" == "false" ]]; then + "${validate[@]}" + else + echo "The release manifest comparison policy is unavailable." >&2 + exit 1 + fi - name: Validate release docsets run: uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-docsets diff --git a/clients/typescript/generated/casework.ts b/clients/typescript/generated/casework.ts index 89d00fe88b..8e196ba5a6 100644 --- a/clients/typescript/generated/casework.ts +++ b/clients/typescript/generated/casework.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 195bfdca62f16e84447145617876a65a104e70f4d96b3b3aa1c6a682be591041 +// Source SHA-256 52dca49e0603c08eacea7a1324f26ac5b876c3aea2d1fb8ed3c673d7d166d109 // Unconstrained JSON /components/schemas/ReviewHistoryEntry/properties/detail // Unconstrained JSON /components/schemas/ReviewPolicy/properties/displaySchema // Unconstrained JSON /components/schemas/ReviewPolicy/properties/resultSchema @@ -53,7 +53,7 @@ export type Schema_InputDecisionKind = (({ "outcome": (string); "publicReason"?: export type Schema_InputDirectoryMember = ({ "displayName"?: (string | null); "issuer": (string); "subject": (string) }) export type Schema_InputDirectoryTargetPurpose = ("assignment" | "absence-person" | "absence-cover") & (string) export type Schema_InputHolidaySetDocument = ({ "dates": (Array<(string)>); "holidaySet": (string); "revision": (number) }) -export type Schema_InputHumanIdentity = ({ "issuer": (string); "subject": (string) }) +export type Schema_InputHumanIdentity = ({ "issuer": (string); "principalClaim": (string); "subject": (string) }) export type Schema_InputIssuerPrincipal = ({ "issuer": (string); "subject": (string) }) export type Schema_InputPolicySelection = ({ "digest"?: Schema_InputContentDigest; "id": (string); "version"?: (string) }) export type Schema_InputReviewAskWant = (({ "kind": "answer" & (string) }) | ({ "kind": "document" & (string) }) | ({ "form": (string); "kind": "form" & (string) })) @@ -174,7 +174,7 @@ export type Schema_ReviewPolicyClosure = ({ "clocks"?: (Array<(string)>); "conte export type Schema_ReviewPolicyClosureList = (Array) export type Schema_ReviewPolicyDependencies = ({ "accessProfiles": (Array); "calendars": (Array); "clocks": (Array); "contextProvider": (Schema_ReviewContextProviderPolicy | (null)); "inbox": Schema_InboxPolicy; "queues": (Array); "taskTemplates": (Array); "teams": (Array); "trustedProducers": (Array) }) export type Schema_ReviewPolicyIdentity = ({ "digest": Schema_Digest; "id": Schema_LocalId; "version": (string) }) -export type Schema_ReviewProducerPolicy = ({ "completion"?: (Schema_ReviewCompletionDestinationPolicy | (null)); "id": Schema_LocalId; "initiatorProfile"?: (string | null); "issuer": Schema_Url; "profile": (string); "readsAsks"?: (boolean); "retention": Schema_ProducerRetention; "reviewPolicies": (Array<(string)>); "sourceNamespaces": (Array<(string)>); "subject": (string); "trustedInitiatorIssuer"?: Schema_Url }) +export type Schema_ReviewProducerPolicy = ({ "completion"?: (Schema_ReviewCompletionDestinationPolicy | (null)); "id": Schema_LocalId; "initiatorProfile"?: (string | null); "issuer": Schema_Url; "profile": (string); "readsAsks"?: (boolean); "retention": Schema_ProducerRetention; "reviewPolicies": (Array<(string)>); "sourceNamespaces": (Array<(string)>); "subject": (string); "trustedInitiatorIssuer"?: Schema_Url; "trustedInitiatorPrincipalClaim"?: (string | null) }) export type Schema_ReviewProgressCode = (string) export type Schema_ReviewPublicReasonRule = ("required" | "optional" | "none") & (string) export type Schema_ReviewPurpose = ("approval" | "answer") & (string) @@ -342,7 +342,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/InputDirectoryMember", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"displayName\":{\"type\":[\"string\",\"null\"]},\"issuer\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"}},\"required\":[\"issuer\",\"subject\"],\"type\":\"object\"}")], ["/components/schemas/InputDirectoryTargetPurpose", JSON.parse("{\"enum\":[\"assignment\",\"absence-person\",\"absence-cover\"],\"type\":\"string\"}")], ["/components/schemas/InputHolidaySetDocument", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"dates\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"holidaySet\":{\"type\":\"string\"},\"revision\":{\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"holidaySet\",\"revision\",\"dates\"],\"type\":\"object\"}")], - ["/components/schemas/InputHumanIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"issuer\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"}},\"required\":[\"issuer\",\"subject\"],\"type\":\"object\"}")], + ["/components/schemas/InputHumanIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"issuer\":{\"type\":\"string\"},\"principalClaim\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"}},\"required\":[\"issuer\",\"principalClaim\",\"subject\"],\"type\":\"object\"}")], ["/components/schemas/InputIssuerPrincipal", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"issuer\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"}},\"required\":[\"issuer\",\"subject\"],\"type\":\"object\"}")], ["/components/schemas/InputPolicySelection", JSON.parse("{\"additionalProperties\":false,\"dependentRequired\":{\"digest\":[\"version\"],\"version\":[\"digest\"]},\"properties\":{\"digest\":{\"$ref\":\"/components/schemas/InputContentDigest\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}")], ["/components/schemas/InputReviewAskWant", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"answer\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"document\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"form\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"kind\":{\"const\":\"form\",\"type\":\"string\"}},\"required\":[\"kind\",\"form\"],\"type\":\"object\"}]}")], @@ -459,7 +459,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/ReviewPolicyClosureList", JSON.parse("{\"items\":{\"$ref\":\"/components/schemas/ReviewPolicyClosure\"},\"type\":\"array\"}")], ["/components/schemas/ReviewPolicyDependencies", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"accessProfiles\":{\"items\":{\"$ref\":\"/components/schemas/AccessProfile\"},\"type\":\"array\"},\"calendars\":{\"items\":{\"$ref\":\"/components/schemas/CalendarPolicy\"},\"type\":\"array\"},\"clocks\":{\"items\":{\"$ref\":\"/components/schemas/ClockPolicy\"},\"type\":\"array\"},\"contextProvider\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewContextProviderPolicy\"},{\"type\":\"null\"}]},\"inbox\":{\"$ref\":\"/components/schemas/InboxPolicy\"},\"queues\":{\"items\":{\"$ref\":\"/components/schemas/QueuePolicy\"},\"type\":\"array\"},\"taskTemplates\":{\"items\":{\"$ref\":\"/components/schemas/TaskTemplate\"},\"type\":\"array\"},\"teams\":{\"items\":{\"$ref\":\"/components/schemas/TeamPolicy\"},\"type\":\"array\"},\"trustedProducers\":{\"items\":{\"$ref\":\"/components/schemas/ReviewProducerPolicy\"},\"type\":\"array\"}},\"required\":[\"accessProfiles\",\"queues\",\"teams\",\"clocks\",\"calendars\",\"contextProvider\",\"taskTemplates\",\"trustedProducers\",\"inbox\"],\"type\":\"object\"}")], ["/components/schemas/ReviewPolicyIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"digest\":{\"$ref\":\"/components/schemas/Digest\"},\"id\":{\"$ref\":\"/components/schemas/LocalId\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"}")], - ["/components/schemas/ReviewProducerPolicy", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"completion\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewCompletionDestinationPolicy\"},{\"type\":\"null\"}]},\"id\":{\"$ref\":\"/components/schemas/LocalId\"},\"initiatorProfile\":{\"type\":[\"string\",\"null\"]},\"issuer\":{\"$ref\":\"/components/schemas/Url\"},\"profile\":{\"type\":\"string\"},\"readsAsks\":{\"type\":\"boolean\"},\"retention\":{\"$ref\":\"/components/schemas/ProducerRetention\"},\"reviewPolicies\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"sourceNamespaces\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"subject\":{\"type\":\"string\"},\"trustedInitiatorIssuer\":{\"$ref\":\"/components/schemas/Url\"}},\"required\":[\"id\",\"profile\",\"issuer\",\"subject\",\"sourceNamespaces\",\"reviewPolicies\",\"retention\"],\"type\":\"object\"}")], + ["/components/schemas/ReviewProducerPolicy", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"completion\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewCompletionDestinationPolicy\"},{\"type\":\"null\"}]},\"id\":{\"$ref\":\"/components/schemas/LocalId\"},\"initiatorProfile\":{\"type\":[\"string\",\"null\"]},\"issuer\":{\"$ref\":\"/components/schemas/Url\"},\"profile\":{\"type\":\"string\"},\"readsAsks\":{\"type\":\"boolean\"},\"retention\":{\"$ref\":\"/components/schemas/ProducerRetention\"},\"reviewPolicies\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"sourceNamespaces\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"subject\":{\"type\":\"string\"},\"trustedInitiatorIssuer\":{\"$ref\":\"/components/schemas/Url\"},\"trustedInitiatorPrincipalClaim\":{\"type\":[\"string\",\"null\"]}},\"required\":[\"id\",\"profile\",\"issuer\",\"subject\",\"sourceNamespaces\",\"reviewPolicies\",\"retention\"],\"type\":\"object\"}")], ["/components/schemas/ReviewProgressCode", JSON.parse("{\"maxLength\":64,\"minLength\":1,\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"}")], ["/components/schemas/ReviewPublicReasonRule", JSON.parse("{\"enum\":[\"required\",\"optional\",\"none\"],\"type\":\"string\"}")], ["/components/schemas/ReviewPurpose", JSON.parse("{\"enum\":[\"approval\",\"answer\"],\"type\":\"string\"}")], diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index 50c664a1bd..d50345bd58 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -871,6 +871,7 @@ mod tests { fn authenticated_context_preserves_identity_values_larger_than_review_protocol_bounds() { let identity = registry_review_client::HumanIdentity { issuer: format!("https://identity.example/{}", "i".repeat(300)), + principal_claim: "sub".to_owned(), subject: "s".repeat(300), }; let claims = VerifiedRequestClaims::authenticated( diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index e48a5d814a..caa1ca1dc6 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -14,6 +14,7 @@ use registry_platform_httputil::FetchUrlPolicy; use registry_platform_oidc::{ClaimNames, JwksFetcher, JwksFetcherConfig}; use registry_platform_testing::{oidc_verifier_config, MockIdp}; use std::time::{Duration, Instant}; +use tower::ServiceExt; use zeroize::Zeroizing; const PROJECT: &str = r#" @@ -99,6 +100,101 @@ fn compiled() -> Arc { ) } +#[tokio::test] +async fn internal_hook_profile_is_excluded_from_action_invoke_http_authority() { + let mut project = parse_project_yaml(PROJECT.as_bytes()).expect("action fixture parses"); + project.entities[0].hooks.push( + serde_json::from_value(json!({ + "id": "case-created", + "phase": "after", + "trigger": "created", + "principal": "hook-worker", + "projection": ["label"], + "handler": {"type": "url", "destinationId": "case-events"} + })) + .expect("hook declaration parses"), + ); + project.access_profiles.push( + serde_json::from_value(json!({ + "id": "hook-worker", + "principalClaim": "registry_principal", + "requiredScopes": "unrestricted", + "permissions": {"actions": [{ + "action": "rename-case", + "operations": ["invoke"], + "targets": [{"recordType": "case", "rowBoundaries": "unrestricted"}], + "results": ["renamed"] + }]} + })) + .expect("hook profile parses"), + ); + let registry = Arc::new( + compile_project(&project, &[], CompileProfile::Authoring).expect("hook project compiles"), + ); + let service = Arc::new(service_for(Arc::clone(®istry), true)); + let route = registry + .actions() + .routes + .iter() + .find(|route| route.kind == ActionRouteKind::Invoke) + .expect("Invoke route compiles"); + let idp = MockIdp::start().await; + let audience = "urn:example:breg"; + let mut verifier = oidc_verifier_config(idp.issuer(), vec![audience.to_owned()]); + verifier.allowed_clients = vec!["agent-client".to_owned()]; + let authenticator = Arc::new( + RegistryAuthenticator::new( + ®istry, + verifier, + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )), + AuthorityClaimConfig::new("registry_principal", Some("registry_purpose".to_owned())), + ) + .expect("omitted issuer profile list is valid"), + ); + let app = crate::api::authenticated_router(service, authenticator); + let send = |token: String, profile: &str| { + let request = axum::http::Request::builder() + .method("POST") + .uri(format!("{}?accessProfile={profile}", route.path)) + .header(axum::http::header::AUTHORIZATION, format!("Bearer {token}")) + .body(Body::empty()) + .expect("Action request builds"); + app.clone().oneshot(request) + }; + + let ordinary = idp.mint_token(json!({ + "aud": audience, + "sub": "ordinary-registrar", + "azp": "agent-client", + "registry_principal": "ordinary-registrar", + "registry_purpose": "case-management", + "regions": ["north"], + "scope": "case.rename" + })); + // An admitted caller reaches input validation before any mutation. + let admitted = send(ordinary, "registrar").await.expect("router responds"); + assert_eq!(admitted.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); + + let hook = idp.mint_token(json!({ + "aud": audience, + "sub": "hook-caller", + "azp": "agent-client", + "registry_principal": "hook-caller", + "scope": "hook.invoke" + })); + let denied = send(hook, "hook-worker").await.expect("router responds"); + assert_eq!(denied.status(), StatusCode::FORBIDDEN); + let body = to_bytes(denied.into_body(), 4096) + .await + .expect("read refusal"); + let problem: Value = serde_json::from_slice(&body).expect("problem response"); + assert_eq!(problem["code"], "profile.not-authorized"); +} + fn task_action_registry() -> Arc { let mut project = parse_project_yaml(PROJECT.as_bytes()).unwrap(); project.access_profiles.push(serde_json::from_value(json!({ diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index ec3827682a..1dd3cd7486 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -151,6 +151,10 @@ pub enum AuthenticationConfigError { ConflictingClaimExpectation, #[error("an issuer entry names an access profile that the compiled registry does not declare")] UnknownAccessProfile, + #[error( + "an issuer entry explicitly reaches a proposing Record hook's internal access profile" + )] + HookProfileHttpReachable, #[error("an access profile that reads the principal or names requester clients is reachable from more than one issuer entry")] PrincipalAcrossIssuers, } @@ -414,6 +418,18 @@ pub(crate) fn compiled_profile_facts( facts } +/// Access profiles selected by governed Record hooks that may return Action +/// proposals. They are internal worker authority and are never HTTP caller +/// profiles, even when an issuer entry omits its `accessProfiles` list. +pub fn proposing_hook_profiles(registry: &CompiledRegistry) -> BTreeSet { + registry + .event_deliveries() + .deliveries + .iter() + .filter_map(|delivery| delivery.principal.clone()) + .collect() +} + /// Production OIDC verifiers plus the only claim mapping allowed to construct /// [`VerifiedRequestClaims`]. pub struct RegistryAuthenticator { @@ -473,15 +489,22 @@ impl RegistryAuthenticator { .collect::>(); let direct_claims = validate_claim_mapping(registry, &profiles, &claims)?; let profile_facts = compiled_profile_facts(registry); + let hook_profiles = proposing_hook_profiles(registry); for issuer in &issuers { if let Some(listed) = &issuer.access_profiles { if listed.is_empty() || listed.iter().any(|id| !profile_facts.contains_key(id)) { return Err(AuthenticationConfigError::UnknownAccessProfile); } + if listed.iter().any(|id| hook_profiles.contains(id)) { + return Err(AuthenticationConfigError::HookProfileHttpReachable); + } } } if issuers.len() > 1 { for (profile_id, facts) in &profile_facts { + if hook_profiles.contains(profile_id) { + continue; + } if !facts.reads_principal && !facts.has_requester_clients { continue; } @@ -512,6 +535,17 @@ impl RegistryAuthenticator { declared, access_profiles, } = issuer; + let access_profiles = if hook_profiles.is_empty() || access_profiles.is_some() { + access_profiles + } else { + Some( + profile_facts + .keys() + .filter(|profile_id| !hook_profiles.contains(*profile_id)) + .cloned() + .collect(), + ) + }; let namespace = several.then(|| verifier.issuer.clone()); let repeated = rules .insert( @@ -738,6 +772,7 @@ impl RegistryAuthenticator { let human_identity = if actor_kind == Some(registry_platform_oidc::ActorKind::Human) { Some(registry_review_client::HumanIdentity { issuer: rules.issuer.clone(), + principal_claim: self.principal_claim.clone(), subject: principal.clone(), }) } else { diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 6d5fff3f58..69ed40dff8 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -358,6 +358,12 @@ fn compile_with_source_rules( &mut diagnostics, ); validate_project_entity_access_profiles(project, &mut diagnostics); + validate_hook_proposal_authorities( + &sources, + &project.access_profiles, + &origins.hook_paths, + &mut diagnostics, + ); validate_module_access_profile_task_grants(&sources, &mut diagnostics); disclosure::validate_module_access_reason_operations(&sources, &mut diagnostics); let module_profiles = crate::access::module_profile_keys(&sources); @@ -4061,6 +4067,54 @@ fn validate_project_entity_access_profiles( } } +/// A Record hook is not an HTTP caller. Its authored `principal` is an +/// explicit binding to one project access profile, but the worker has no +/// verified token scopes, purpose, actor, OAuth client, or task grant to +/// satisfy caller-dependent conditions on that profile. Refuse such a +/// binding during authoring instead of manufacturing claims at delivery. +fn validate_hook_proposal_authorities( + entities: &BTreeMap, + profiles: &[ProjectAccessProfileSource], + hook_paths: &HookPathMap, + errors: &mut Vec, +) { + let profiles = profiles + .iter() + .map(|profile| (profile.id.as_str(), profile)) + .collect::>(); + for entity in entities.values() { + for hook in &entity.hooks { + let Some(principal) = hook.principal.as_deref() else { + continue; + }; + let hook_path = hook_paths + .get(&(entity.id.clone(), hook.id.clone())) + .cloned() + .unwrap_or_else(|| format!("recordTypes[id={}].hooks[id={}]", entity.id, hook.id)); + let Some(profile) = profiles.get(principal) else { + errors.push(Diagnostic::error( + "breg.event.hook-authority-unknown", + format!("{hook_path}.principal"), + "a proposing hook must bind an existing project access profile", + )); + continue; + }; + if !profile.required_scopes.is_empty() + || !profile.required_purposes.is_empty() + || profile.actor_kind.is_some() + || !profile.requester_clients.is_empty() + || profile.task_grant.is_some() + { + errors.push(Diagnostic::error( + "breg.event.hook-authority-unsupported", + format!("{hook_path}.principal"), + "a proposing hook must bind a profile with unrestricted scopes and no purpose, actor, requester-client, or task-grant requirement", + )); + } + } + } +} + /// A task grant is authored only in project `accessProfiles`, where /// `expand_project_access` checks its ceiling and compiles its collection /// bounds. Before that expansion, every entity profile was contributed by a @@ -7132,11 +7186,16 @@ fn validate_hooks( None } None => { - if profile == CompileProfile::Production { + if hook.principal.is_some() || profile == CompileProfile::Production { + let message = if hook.principal.is_some() { + "a proposing event requires a supported delivery" + } else { + "a production event requires a supported delivery" + }; errors.push(Diagnostic::error( "breg.event.delivery-required", format!("{hook_path}.handler"), - "a production event requires a supported delivery", + message, )); } continue; diff --git a/crates/registry-breg/src/migration.rs b/crates/registry-breg/src/migration.rs index cfbdce0234..87730c8e37 100644 --- a/crates/registry-breg/src/migration.rs +++ b/crates/registry-breg/src/migration.rs @@ -109,6 +109,9 @@ pub enum MigrationError { /// package. The bounded inventory contains compiled identifiers only. #[error("retained local hook deliveries prevent activation")] RetainedLocalHooks(crate::postgres::RetainedLocalHookDeliveries), + /// Retained Review requests must settle on the release that created them. + #[error("{}", crate::review_store::REVIEW_INITIATOR_UPGRADE_ADVICE)] + ReviewInitiatorUpgrade, /// Refused before maintenance: legacy data contains more than one run /// which still occupies an import authority. Each creator can recover it /// through the authenticated run routes of the still-serving runtime. @@ -1375,6 +1378,23 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> return Err(refusal_before_maintenance(error)); } } + // Hold the registry lock before checking any retained work, even + // when plan would otherwise return an unchanged activation. + match crate::review_store::review_initiator_upgrade_required( + connection.client_for_proposal_retention_guard(), + ) + .await + { + Ok(false) => {} + Ok(true) => { + let _ = connection.release().await; + return Err(MigrationError::ReviewInitiatorUpgrade); + } + Err(_) => { + let _ = connection.release().await; + return Err(MigrationError::DatabaseUnavailable); + } + } } Ok(crate::postgres::RegistryStateShape::Absent) => {} Err(error) => { diff --git a/crates/registry-breg/src/migration_reconcile.rs b/crates/registry-breg/src/migration_reconcile.rs index 2c70f282c4..06f9996f18 100644 --- a/crates/registry-breg/src/migration_reconcile.rs +++ b/crates/registry-breg/src/migration_reconcile.rs @@ -288,6 +288,7 @@ impl From for ReconcileError { | MigrationError::DatabaseMismatch | MigrationError::HistoryCoverage | MigrationError::RetainedLocalHooks(_) + | MigrationError::ReviewInitiatorUpgrade | MigrationError::ConflictingImportRuns | MigrationError::DatabaseUnavailable | MigrationError::FieldPatternSyntax { .. } diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index 4d165337c3..263d386090 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -948,6 +948,21 @@ pub struct CompiledActionTargetPermission { } impl CompiledActionPermission { + /// Whether a Record hook can use this grant without inventing caller + /// context. The principal claim remains mandatory profile metadata, while + /// the hook's authored principal binding selects the profile directly. + #[cfg(feature = "runtime")] + pub(crate) fn is_caller_independent_hook_authority(&self) -> bool { + self.principal_claim + .as_ref() + .is_some_and(|claim| !claim.is_empty()) + && self.actor_kind.is_none() + && self.task_grant.is_none() + && self.requester_clients.is_empty() + && self.required_scopes.is_empty() + && self.required_purposes.is_empty() + } + /// Returns each entity-level authority lock once. Permission targets are /// discriminated by action use for authoring and explanation, but runtime /// row authority remains one lock per entity. @@ -966,6 +981,51 @@ impl CompiledActionPermission { } } +#[cfg(all(test, feature = "runtime"))] +mod hook_authority_tests { + use super::*; + + fn caller_independent_grant() -> CompiledActionPermission { + CompiledActionPermission { + profile_id: "hook-worker".to_owned(), + default: false, + actor_kind: None, + task_grant: None, + requester_clients: BTreeSet::new(), + principal_claim: Some("registry_principal".to_owned()), + required_scopes: BTreeSet::new(), + required_purposes: BTreeSet::new(), + operations: BTreeSet::from([Operation::Invoke]), + targets: Vec::new(), + results: BTreeSet::from(["followup".to_owned()]), + } + } + + #[test] + fn hook_apply_predicate_refuses_actor_purpose_and_requester_context() { + let grant = caller_independent_grant(); + assert!(grant.is_caller_independent_hook_authority()); + + let mut actor = grant.clone(); + actor.actor_kind = Some(crate::contract::ActorKindSource::Service); + let mut purpose = grant.clone(); + purpose.required_purposes.insert("hook-response".to_owned()); + let mut requester = grant; + requester.requester_clients.insert("hook-client".to_owned()); + + for (case, grant) in [ + ("actor kind", actor), + ("purpose", purpose), + ("requester client", requester), + ] { + assert!( + !grant.is_caller_independent_hook_authority(), + "{case} requires caller context" + ); + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct CompiledActionTargetUse { @@ -2140,6 +2200,25 @@ pub struct CompiledRegistry { } impl CompiledRegistry { + /// Access a compiled Action grant in a disposable PostgreSQL test fixture. + #[cfg(feature = "postgres-test")] + pub fn action_grant_mut_for_test( + &mut self, + action_id: &str, + profile_id: &str, + ) -> Option<&mut CompiledActionPermission> { + self.action_inventory + .actions + .iter_mut() + .find(|action| action.id == action_id) + .and_then(|action| { + action + .permissions + .iter_mut() + .find(|grant| grant.profile_id == profile_id) + }) + } + #[allow(clippy::too_many_arguments)] pub(crate) fn new( registry_id: String, diff --git a/crates/registry-breg/src/mutation.rs b/crates/registry-breg/src/mutation.rs index 53b1820a1c..8b86890db7 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -613,6 +613,7 @@ pub(crate) fn exact_entity_event_deliveries( record_type: entity.id.clone(), trigger: event.trigger, }) + || delivery.principal != event.principal || delivery.destination_id.as_deref() != expected_destination_id || delivery.handler_kind() != expected_handler_kind || delivery.projection_fields != expected_projection diff --git a/crates/registry-breg/src/mutation/action.rs b/crates/registry-breg/src/mutation/action.rs index d3e2c19331..8285f40bf7 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -1255,6 +1255,12 @@ impl MutationTransaction { "The declared principal may not invoke the proposed action.", ); } + if !grant.is_caller_independent_hook_authority() { + return refused_proposal( + "hook.proposal.unauthorized", + "The declared principal's grant requires caller context a hook does not carry.", + ); + } if grant.results.is_empty() { return refused_proposal( "hook.proposal.no-visible-results", diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index fa0fe1d7be..8212c1cf5b 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -85,6 +85,45 @@ pub(crate) const REVIEW_SUBMISSION_CLAIMABLE: &str = "next_attempt_at <= transac AND (state<>'cancelling' OR lease_until IS NULL OR lease_until < transaction_timestamp())"; +const RETAINED_REVIEW_SUBMISSION: &str = + "s.state IN ('pending','submitting','uncertain','cancelling') + OR (s.state='accepted' AND EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_state w + WHERE (w.action_id,w.proposal_id,w.submission_version)= + (s.action_id,s.proposal_id,s.submission_version) + AND w.state='submitted'))"; + +pub(crate) const REVIEW_INITIATOR_UPGRADE_ADVICE: &str = "retained Review requests use the previous release's initiator format. Use the previous matching Registry Stack release to finish or cancel the affected work before retrying"; + +/// Inspect resumable Review work without claiming a job or rewriting a request. +pub(crate) async fn review_initiator_upgrade_required( + client: &impl GenericClient, +) -> Result { + let has_review_store: bool = client + .query_one( + "SELECT to_regclass('registry_internal.registry_proposal_review_submissions') IS NOT NULL", + &[], + ) + .await? + .get(0); + if !has_review_store { + return Ok(false); + } + let row = client + .query_one( + &format!( + "SELECT EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_review_submissions s + WHERE ({RETAINED_REVIEW_SUBMISSION}) + AND jsonb_typeof(s.create_request->'initiator') = 'object' + AND NULLIF(s.create_request#>>'{{initiator,principalClaim}}','') IS NULL)" + ), + &[], + ) + .await?; + Ok(row.get(0)) +} + fn outbound_lease_seconds(request_timeout: Duration) -> i64 { // The claim lease must outlive the outbound call it guards: an expiry // inside the request timeout lets another instance treat the job as @@ -123,6 +162,7 @@ pub enum RetainedReviewBindingError { authority: String, retained_submissions: u64, }, + ReviewInitiatorUpgrade, Refused, Unavailable, } @@ -137,6 +177,7 @@ impl std::fmt::Display for RetainedReviewBindingError { formatter, "review authority {authority} is required by {retained_submissions} retained submissions" ), + Self::ReviewInitiatorUpgrade => formatter.write_str(REVIEW_INITIATOR_UPGRADE_ADVICE), Self::Refused => formatter.write_str("retained review bindings were refused"), Self::Unavailable => { formatter.write_str("retained review bindings could not be inspected") @@ -147,6 +188,24 @@ impl std::fmt::Display for RetainedReviewBindingError { impl std::error::Error for RetainedReviewBindingError {} +/// Refuse an upgrade before activation contacts a Review authority. +pub async fn check_review_initiator_upgrade( + pool: &crate::postgres::RuntimePool, +) -> Result<(), crate::migration::MigrationError> { + use crate::migration::MigrationError; + let client = pool + .get() + .await + .map_err(|_| MigrationError::DatabaseUnavailable)?; + if review_initiator_upgrade_required(&**client) + .await + .map_err(|_| MigrationError::ApplyFailed)? + { + return Err(MigrationError::ReviewInitiatorUpgrade); + } + Ok(()) +} + /// Configured bindings must retain the producer identity of accepted work. /// Missing bindings leave that immutable work pending and inspectable until /// the dependency is restored, while unrelated registry operations stay usable. @@ -159,20 +218,23 @@ pub async fn verify_retained_bindings( .get() .await .map_err(|_| RetainedReviewBindingError::Unavailable)?; + if review_initiator_upgrade_required(&**client) + .await + .map_err(|_| RetainedReviewBindingError::Unavailable)? + { + return Err(RetainedReviewBindingError::ReviewInitiatorUpgrade); + } let authority_rows = client .query( - "SELECT authority, + &format!( + "SELECT authority, array_agg(DISTINCT producer_id ORDER BY producer_id), count(*)::bigint FROM registry_internal.registry_proposal_review_submissions s - WHERE state IN ('pending','submitting','uncertain','cancelling') - OR (s.state='accepted' AND EXISTS ( - SELECT 1 FROM registry_internal.registry_proposal_state w - WHERE (w.action_id,w.proposal_id,w.submission_version)= - (s.action_id,s.proposal_id,s.submission_version) - AND w.state='submitted')) + WHERE {RETAINED_REVIEW_SUBMISSION} GROUP BY authority - ORDER BY authority", + ORDER BY authority" + ), &[], ) .await diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index ae26b695ac..8a83ee1fc7 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -2826,8 +2826,9 @@ impl AuthenticationConfig { } /// Check `accessProfiles` on every issuer entry against the compiled - /// registry: unknown profile references and principal-reading or - /// client-restricted profiles reachable from two or more issuer entries. + /// registry: unknown references, internal hook profiles exposed to HTTP, + /// and principal-reading or client-restricted profiles reachable from two + /// or more issuer entries. fn access_profile_diagnostics( &self, registry: &CompiledRegistry, @@ -2835,6 +2836,7 @@ impl AuthenticationConfig { check: Option<®istry_platform_config::RuntimeFileCheck>, ) -> Vec { let profile_facts = crate::auth::compiled_profile_facts(registry); + let hook_profiles = crate::auth::proposing_hook_profiles(registry); let mut diagnostics = Vec::new(); for entry in self.oidc.issuers() { if let Some(listed) = entry.access_profiles() { @@ -2856,6 +2858,23 @@ impl AuthenticationConfig { diag }; diagnostics.push(diag); + } else if hook_profiles.contains(profile_id) { + let pointer = format!("{}/accessProfiles/{index}", entry.pointer()); + let code = "breg.runtime.hook-profile-http-reachable"; + let message = "This issuer entry explicitly reaches an internal access profile selected by a proposing Record hook."; + let action = "Remove this profile from the issuer entry. Omit accessProfiles to let BReg exclude proposing-hook profiles from HTTP automatically."; + let diag = if let Some(check) = check { + check.error_at(RUNTIME_CONFIG_KIND, code, &pointer, message, action) + } else { + let mut diag = Diagnostic::error(code, &pointer, message, action); + diag.source = runtime_path.map(|path| Source { + file: path.display().to_string(), + line: None, + column: None, + }); + diag + }; + diagnostics.push(diag); } } } @@ -2863,6 +2882,9 @@ impl AuthenticationConfig { if self.oidc.issuers().count() > 1 { let mut reported_pairs = BTreeSet::<(String, String)>::new(); for (profile_id, facts) in &profile_facts { + if hook_profiles.contains(profile_id) { + continue; + } if !facts.reads_principal && !facts.has_requester_clients { continue; } @@ -2928,8 +2950,12 @@ impl AuthenticationConfig { registry: &CompiledRegistry, ) -> Vec { let profile_facts = crate::auth::compiled_profile_facts(registry); + let hook_profiles = crate::auth::proposing_hook_profiles(registry); let mut settings = Vec::new(); for (profile_id, facts) in &profile_facts { + if hook_profiles.contains(profile_id) { + continue; + } if facts.has_subject_row_rule { continue; } diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index b1dcc77000..cc59054dee 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -195,6 +195,8 @@ pub enum StartupError { }, #[error("the Registry retained review bindings were refused")] ReviewBindings, + #[error("{}", crate::review_store::REVIEW_INITIATOR_UPGRADE_ADVICE)] + ReviewInitiatorUpgrade, #[error( "review authority {authority} is required by {retained_submissions} retained submissions" )] @@ -931,6 +933,7 @@ impl StartupError { Self::ReviewBindings | Self::ReviewAuthorityMissing { .. } => { "the Registry retained review bindings were refused" } + Self::ReviewInitiatorUpgrade => crate::review_store::REVIEW_INITIATOR_UPGRADE_ADVICE, Self::Listener => "the Registry listener could not be started", Self::Shutdown => "the Registry shutdown signal failed", Self::BackgroundTaskStopped => { @@ -2487,6 +2490,9 @@ fn review_binding_startup_error( authority, retained_submissions, }, + crate::review_store::RetainedReviewBindingError::ReviewInitiatorUpgrade => { + StartupError::ReviewInitiatorUpgrade + } crate::review_store::RetainedReviewBindingError::Refused | crate::review_store::RetainedReviewBindingError::Unavailable => { StartupError::ReviewBindings diff --git a/crates/registry-breg/tests/compiler_webhook.rs b/crates/registry-breg/tests/compiler_webhook.rs index e238007e82..94a110f3c4 100644 --- a/crates/registry-breg/tests/compiler_webhook.rs +++ b/crates/registry-breg/tests/compiler_webhook.rs @@ -78,6 +78,136 @@ fn webhook_mut(value: &mut Value) -> &mut serde_json::Map { .expect("hook object") } +fn proposal_hook_project_value() -> Value { + let mut source = project_value(); + source["recordTypes"]["case"]["hooks"][0]["principal"] = json!("case-hook"); + source["recordTypes"]["followup"] = json!({ + "primaryDataset": "test-dataset", + "route": "followups", + "mutationMode": "create-only", + "classification": "internal", + "fields": [{ + "id": "label", + "type": "string", + "maximumLength": 64, + "classification": "internal" + }] + }); + source["actions"] = json!({ + "open-followup": { + "execution": {"mode": "immediate"}, + "inputs": [{ + "id": "label", + "type": "string", + "maximumLength": 64, + "classification": "internal" + }], + "plan": { + "type": "fixed", + "effects": [{ + "id": "followup", + "target": {"recordType": "followup"}, + "operation": "create", + "set": {"label": {"fromInput": "label"}} + }] + } + } + }); + source["accessProfiles"] = json!({ + "case-hook": { + "principalClaim": "registry_principal", + "requiredScopes": "unrestricted", + "permissions": { + "actions": [{ + "action": "open-followup", + "operations": ["invoke"], + "targets": [{ + "recordType": "followup", + "rowBoundaries": "unrestricted" + }], + "results": ["followup"] + }] + } + } + }); + source +} + +#[test] +fn proposal_hook_authority_requires_a_caller_independent_profile() { + for (member, value) in [ + ("requiredScopes", json!(["registry.write"])), + ("requiredPurposes", json!(["case-management"])), + ("actorKind", json!("human")), + ("requesterClients", json!(["case-worker"])), + ] { + let mut source = proposal_hook_project_value(); + source["accessProfiles"]["case-hook"][member] = value; + assert_compile_code(&source, "breg.event.hook-authority-unsupported"); + } +} + +#[test] +fn proposal_hook_authority_refuses_task_grant_approval() { + let mut source = proposal_hook_project_value(); + source["accessProfiles"]["case-hook"]["taskGrant"] = + json!({"sourceIssuer": "https://task-authority.example.test"}); + assert_compile_code(&source, "breg.event.hook-authority-unsupported"); +} + +#[test] +fn proposal_hook_authority_requires_a_handler_in_authoring() { + let mut source = proposal_hook_project_value(); + source["recordTypes"]["case"]["hooks"][0] + .as_object_mut() + .expect("hook object") + .remove("handler"); + assert_compile_code(&source, "breg.event.delivery-required"); +} + +#[test] +fn proposal_hook_authority_must_bind_an_existing_profile() { + let mut source = proposal_hook_project_value(); + source["recordTypes"]["case"]["hooks"][0]["principal"] = json!("missing-profile"); + assert_compile_code(&source, "breg.event.hook-authority-unknown"); +} + +#[test] +fn proposal_hook_accepts_a_bounded_profile_and_keeps_its_authored_binding() { + let compiled = compile(&proposal_hook_project_value()) + .expect("a caller-independent hook action grant compiles"); + let delivery = &compiled.event_deliveries().deliveries[0]; + assert_eq!(delivery.principal.as_deref(), Some("case-hook")); + let action = compiled + .actions() + .actions + .iter() + .find(|action| action.id == "open-followup") + .expect("the granted action compiles"); + let grant = action + .permissions + .iter() + .find(|grant| grant.profile_id == "case-hook") + .expect("the hook profile grant compiles"); + assert_eq!(grant.principal_claim.as_deref(), Some("registry_principal")); + assert!(grant.required_scopes.is_empty()); + assert!(grant.required_purposes.is_empty()); + assert!(grant.actor_kind.is_none()); + assert!(grant.requester_clients.is_empty()); + assert!(grant.task_grant.is_none()); +} + +#[test] +fn notification_only_hook_does_not_constrain_unrelated_caller_profiles() { + let mut source = proposal_hook_project_value(); + source["recordTypes"]["case"]["hooks"][0] + .as_object_mut() + .expect("hook object") + .remove("principal"); + source["accessProfiles"]["case-hook"]["requiredScopes"] = json!(["registry.write"]); + compile(&source).expect("a hook without proposal authority remains notification-only"); +} + #[test] fn governed_webhook_compiles_to_deterministic_destination_neutral_inventory() { let source = project_value(); diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index 76f5cbe083..aaf54426e7 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -181,6 +181,77 @@ accessProfiles: - {field: tenant, claim: tenant, operator: equals} "#; +const PROPOSING_HOOK_PROFILE_PROJECT: &str = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: proposing-hook-profile + version: 0.1.0 + defaultLanguage: en + canonicalBaseIri: https://authoring.example.test +datasets: + cases: {} +recordTypes: + case: + primaryDataset: cases + route: cases + mutationMode: mutable + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + hooks: + - id: case-created + phase: after + trigger: created + principal: hook-worker + projection: [label] + handler: {type: url, destinationId: case-events} + followup: + primaryDataset: cases + route: followups + mutationMode: create-only + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} +actions: + open-followup: + execution: {mode: immediate} + inputs: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + plan: + type: fixed + effects: + - id: followup + target: {recordType: followup} + operation: create + set: {label: {fromInput: label}} +accessProfiles: + ordinary-reader: + default: true + principalClaim: registry_principal + requiredScopes: [registry.read] + requiredPurposes: [case-management-never-rendered] + permissions: + records: + - recordType: case + operations: [get] + readableFields: [label] + rowBoundaries: unrestricted + hook-worker: + principalClaim: registry_principal + requiredScopes: unrestricted + permissions: + records: + - recordType: case + operations: [get] + readableFields: [label] + rowBoundaries: unrestricted + actions: + - action: open-followup + operations: [invoke] + targets: + - {recordType: followup, rowBoundaries: unrestricted} + results: [followup] +"#; + const CANONICAL_ID_BOUNDARY_PROJECT: &str = r#" apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 kind: BRegProject @@ -4511,6 +4582,110 @@ fn an_unknown_access_profile_on_an_issuer_entry_is_refused() { ); } +#[test] +fn an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile() { + let project = + parse_project_yaml(PROPOSING_HOOK_PROFILE_PROJECT.as_bytes()).expect("hook project parses"); + let registry = + compile_project(&project, &[], CompileProfile::Authoring).expect("hook project compiles"); + let scratch = tempfile::tempdir().expect("tempdir"); + let path = scratch.path().join("runtime.yaml"); + std::fs::write( + &path, + two_issuer_runtime_yaml( + " accessProfiles: [hook-worker]", + " accessProfiles: [ordinary-reader]", + ), + ) + .expect("write runtime"); + + let check = registry_breg::runtime_config::check_runtime_config( + &path, + false, + Some(®istry), + registry_platform_config::DeclaredPosture { + posture: registry_platform_config::Posture::Production, + source: registry_platform_config::PostureSource::Default, + }, + ); + let diag = check + .diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "breg.runtime.hook-profile-http-reachable") + .unwrap_or_else(|| panic!("expected hook-profile refusal: {:?}", check.diagnostics)); + assert_eq!( + diag.path, + "/authentication/oidc/issuers/first/accessProfiles/0" + ); + assert!( + !diag.message.contains("hook-worker"), + "the diagnostic stays value-free: {}", + diag.message + ); +} + +#[tokio::test] +async fn authenticator_construction_refuses_an_explicit_proposing_hook_profile() { + let project = + parse_project_yaml(PROPOSING_HOOK_PROFILE_PROJECT.as_bytes()).expect("hook project parses"); + let registry = + compile_project(&project, &[], CompileProfile::Authoring).expect("hook project compiles"); + let idp = MockIdp::start().await; + + let Err(error) = RegistryAuthenticator::with_issuers( + ®istry, + vec![ + AuthenticatorIssuer::new("issuer", verifier_config(&idp), key_source(&idp)) + .with_access_profiles(["hook-worker".to_owned()]), + ], + authority_claims(), + ) else { + panic!("an HTTP issuer must not reach internal hook authority"); + }; + + assert_eq!(error, AuthenticationConfigError::HookProfileHttpReachable); +} + +#[tokio::test] +async fn an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes() { + let harness = Harness::with_source(PROPOSING_HOOK_PROFILE_PROJECT).await; + let ordinary = harness.valid_token(); + let response = harness + .send( + &format!("/v1/records/cases/{RECORD_ID}"), + &[bearer(&ordinary)], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(harness.records.calls.load(Ordering::SeqCst), 1); + + let hook_token = harness.signed_token( + json!({ + "aud": AUDIENCE, + "registry_actor_kind": "service", + "registry_principal": PRINCIPAL, + "scope": "hook.invoke", + "purpose": "hook-response" + }), + "JWT", + ); + let denied = harness + .send( + &format!("/v1/records/cases/{RECORD_ID}?accessProfile=hook-worker"), + &[bearer(&hook_token)], + None, + ) + .await; + assert_eq!(denied.status(), StatusCode::FORBIDDEN); + assert_eq!(body_json(denied).await["code"], "profile.not-authorized"); + assert_eq!( + harness.records.calls.load(Ordering::SeqCst), + 1, + "the hook profile is denied before the read service despite its Record grant" + ); +} + #[tokio::test] async fn an_issuer_reaches_only_the_profiles_it_names() { let source = PROJECT.replace(" default: true\n", ""); diff --git a/crates/registry-breg/tests/package_change_plan.rs b/crates/registry-breg/tests/package_change_plan.rs index 354faf057d..1bddae9447 100644 --- a/crates/registry-breg/tests/package_change_plan.rs +++ b/crates/registry-breg/tests/package_change_plan.rs @@ -114,7 +114,13 @@ fn stored_field_ceiling_widens_compiled_access_on_successor_field_changes() { "mutationMode":"mutable","classification":"internal", "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}] }}, - "accessProfiles":{"reader":{ + "accessProfiles":{"named":{ + "principalClaim":"sub","requiredScopes":["records:read"], + "permissions":{"records":[{ + "recordType":"record","operations":["get"],"rowBoundaries":"unrestricted", + "readableFields":["label"] + }]} + },"ceiling":{ "principalClaim":"sub","requiredScopes":["records:read"], "permissions":{"records":[{ "recordType":"record","operations":["get"],"rowBoundaries":"unrestricted", @@ -139,17 +145,64 @@ fn stored_field_ceiling_widens_compiled_access_on_successor_field_changes() { for predecessor in [source, restricted] { assert_eq!(predecessor["accessProfiles"], included["accessProfiles"]); let previous = compile(&predecessor); - assert!(!previous.entities()["record"].access_profiles["reader"] - .readable_fields - .contains("note")); - assert!(candidate.entities()["record"].access_profiles["reader"] - .readable_fields - .contains("note")); + let previous_profiles = &previous.entities()["record"].access_profiles; + let candidate_profiles = &candidate.entities()["record"].access_profiles; + assert_eq!( + previous_profiles["named"].readable_fields, candidate_profiles["named"].readable_fields, + "a named field grant does not acquire the new internal field" + ); + assert_eq!( + candidate_profiles["named"] + .readable_fields + .iter() + .map(String::as_str) + .collect::>(), + vec!["label"] + ); + assert_eq!( + previous_profiles["ceiling"] + .readable_fields + .iter() + .map(String::as_str) + .collect::>(), + vec!["label"] + ); + assert_eq!( + candidate_profiles["ceiling"] + .readable_fields + .iter() + .map(String::as_str) + .collect::>(), + vec!["label", "note"], + "the compiled ceiling grant expands to the new internal field" + ); + let change_set = compiled_registry_change_set(&previous, &candidate, PRIOR_REVISION); + assert!( + !change_set + .changes + .iter() + .any(|change| change.code == CompiledRegistryChangeCode::QueryInventoryChanged), + "GET-only field grants do not change the query inventory" + ); + assert!( + change_set_to_applicable_migration_plan(&change_set).is_ok(), + "GET-only field changes remain automatically plannable; List and read-path projections are covered by the review-required regression" + ); let diff = classify_registry_diff(&previous, &candidate, PRIOR_REVISION); + assert!( + !diff.changes.iter().any(|change| { + change.change.code == CompiledRegistryChangeCode::AccessProfileChanged + && change.change.target.member_id.as_deref() == Some("named") + }), + "the unchanged named field grant is not reported as an access change" + ); let change = diff .changes .iter() - .find(|change| change.change.code == CompiledRegistryChangeCode::AccessProfileChanged) + .find(|change| { + change.change.code == CompiledRegistryChangeCode::AccessProfileChanged + && change.change.target.member_id.as_deref() == Some("ceiling") + }) .expect("the unchanged authored ceiling widens the compiled grant"); assert_eq!( change.classification, @@ -159,7 +212,7 @@ fn stored_field_ceiling_widens_compiled_access_on_successor_field_changes() { change.change.target.record_type_id.as_deref(), Some("record") ); - assert_eq!(change.change.target.member_id.as_deref(), Some("reader")); + assert_eq!(change.change.target.member_id.as_deref(), Some("ceiling")); let detail = change .access_details .iter() diff --git a/crates/registry-breg/tests/postgres_hook_changes.rs b/crates/registry-breg/tests/postgres_hook_changes.rs index 6767e97bab..58a84bd0a4 100644 --- a/crates/registry-breg/tests/postgres_hook_changes.rs +++ b/crates/registry-breg/tests/postgres_hook_changes.rs @@ -35,7 +35,7 @@ use registry_breg::field_encryption::{FieldEncryptionProvider, FieldEncryptionSe use registry_breg::hooks::{ HookDeliveryError, HookDeliveryService, HookRetainedBindingError, HookWorkOutcome, }; -use registry_breg::model::CompiledRegistry; +use registry_breg::model::{CompiledActionPermission, CompiledRegistry}; use registry_breg::mutation::{MutationBody, MutationPlan, MutationRequest, MutationTransaction}; use registry_breg::postgres::{ initialize_compiled_registry_state_with_posture_for_test, install_compiled_schema, @@ -263,6 +263,21 @@ fn proposal_registry() -> CompiledRegistry { ) } +/// Models a loaded compiled package whose action grant no longer matches the +/// caller-independent hook authority the authoring compiler accepted. The +/// live apply path must independently refuse it before any Record mutation. +fn proposal_registry_with_substituted_grant( + constrain: fn(&mut CompiledActionPermission), +) -> CompiledRegistry { + let mut compiled = proposal_registry(); + constrain( + compiled + .action_grant_mut_for_test("open-followup", "case-hook") + .expect("the compiled hook grant exists"), + ); + compiled +} + /// The standard proposal registry with the action's `origin` target sealed /// at rest. The proposal still carries plaintext process-local input; only /// the committed field changes storage shape. @@ -2608,6 +2623,72 @@ async fn real_postgres_a_proposal_without_a_declared_principal_is_dead_lettered_ receiver.stop().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn real_postgres_a_loaded_hook_grant_requiring_caller_context_is_refused_without_mutation() { + type Constraint = fn(&mut CompiledActionPermission); + let constraints: [(&str, Constraint); 4] = [ + ("scope", |grant| { + assert!(grant.required_scopes.insert("registry.write".to_owned())); + }), + ("actor kind", |grant| { + assert!(grant.actor_kind.is_none()); + grant.actor_kind = Some(registry_breg::contract::ActorKindSource::Service); + }), + ("purpose", |grant| { + assert!(grant.required_purposes.insert("case-management".to_owned())); + }), + ("requester client", |grant| { + assert!(grant.requester_clients.insert("hook-client".to_owned())); + }), + ]; + for (case, constrain) in constraints { + let receiver = HttpsReceiver::start().await; + let setup = setup( + proposal_registry_with_substituted_grant(constrain), + &receiver, + false, + ) + .await; + let mut mutation_client = setup + .pool + .get_for_test() + .await + .expect("runtime mutation connection is available"); + let event = create_case(&setup, &mut mutation_client, case).await; + let delivery_id = single_delivery(&event).to_owned(); + drop(mutation_client); + + assert_eq!( + setup.service.deliver_once().await, + Ok(HookWorkOutcome::Delivered), + "{case}: the incompatible proposal settles as a refusal" + ); + let row = delivery_row(&setup, event.event_id, &delivery_id).await; + assert_eq!(row.state, "delivered", "{case}"); + assert_eq!(row.disposition.as_deref(), Some("refused"), "{case}"); + assert_eq!(row.resulting_revision, None, "{case}"); + assert_eq!( + row.code.as_deref(), + Some("hook.proposal.unauthorized"), + "{case}" + ); + assert_eq!( + row.summary.as_deref(), + Some("The declared principal's grant requires caller context a hook does not carry."), + "{case}: the live hook-authority guard produced the refusal" + ); + assert_eq!( + record_count(&setup, "followup").await, + 0, + "{case}: a caller-dependent hook grant applies no Record mutation" + ); + assert_eq!(record_count(&setup, "case").await, 1, "{case}"); + + setup.teardown().await; + receiver.stop().await; + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_a_proposal_failing_outcome_validation_is_refused_not_applied() { let receiver = HttpsReceiver::start().await; diff --git a/crates/registry-breg/tests/postgres_native_retention.rs b/crates/registry-breg/tests/postgres_native_retention.rs index ae1d7e05e0..777c78963c 100644 --- a/crates/registry-breg/tests/postgres_native_retention.rs +++ b/crates/registry-breg/tests/postgres_native_retention.rs @@ -506,6 +506,7 @@ async fn seed_retention_initiator( serde_json::from_value(value).unwrap(); request.initiator = Some(registry_review_client::HumanIdentity { issuer: "https://retention-issuer.example.test".into(), + principal_claim: "sub".into(), subject: "retention-initiator-canary".into(), }); request.check().unwrap(); @@ -515,6 +516,72 @@ async fn seed_retention_initiator( fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET create_request=$2,expected_submission_digest=$3 WHERE proposal_id=$1",&[&id,&json!(request),&digest.as_str()]).await.unwrap(); } +#[tokio::test] +async fn retained_review_preflight_requires_an_initiator_claim_binding() { + use registry_breg::review_store::verify_retained_bindings; + + let policy = + json!({"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}); + let authority = proposal_review_authority::LocalAuthority::start( + serde_json::from_value(policy.clone()).unwrap(), + ) + .await; + let mut source = registry_source(false); + source["reviewAuthorities"] = + json!({"local-review": {"protocol":"id.registrystack.org/protocols/review/v1"}}); + source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({ + "type":"required","authority":"local-review","source":"proposal-test","policy":policy + }); + let configured = authority.registry.clone(); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(source), + claims("clerk", "zone-a"), + move |mutations| { + mutations.with_proposal_review_substitute_for_test(configured.clone(), configured) + }, + ) + .await; + let client = &fixture.http.client; + let draft = start(&fixture, "upgrade-test", "upgrade-start").await; + let submit = client + .prepare_proposal(&draft, "submit", json!({}), &key("upgrade-submit")) + .unwrap(); + let submitted = client.execute_proposal(&submit).await.unwrap().value; + let id = uuid::Uuid::parse_str(submitted.id()).unwrap(); + verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) + .await + .expect("a request without a named initiator can be resumed"); + + seed_retention_initiator(&fixture, &submitted).await; + verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) + .await + .expect("the current claim binding can be resumed"); + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET create_request = create_request #- '{initiator,principalClaim}' + WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap(); + let error = + verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) + .await + .expect_err("the preflight refuses a retained request from the previous release"); + assert!(error.to_string().contains("previous release")); + let state = fixture.database.admin.query_one( + "SELECT state, attempt_count FROM registry_internal.registry_proposal_review_submissions + WHERE proposal_id=$1", + &[&id], + ).await.unwrap(); + assert_eq!(state.get::<_, String>(0), "pending"); + assert_eq!(state.get::<_, i32>(1), 0); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn native_erasure_reports_sensitive_copies_and_preserves_only_bounded_review_recovery() { use registry_breg::review_store::run_review_authority_once_for_test; diff --git a/crates/registry-breg/tests/postgres_package/pre_1_0_schema.rs b/crates/registry-breg/tests/postgres_package/pre_1_0_schema.rs index 610b7f98f7..8fae8b8102 100644 --- a/crates/registry-breg/tests/postgres_package/pre_1_0_schema.rs +++ b/crates/registry-breg/tests/postgres_package/pre_1_0_schema.rs @@ -59,7 +59,7 @@ async fn plan_and_apply_name_the_v0_43_0_attachment_verification_shape() { .await .expect("a fresh database plans the initial activation"); assert_eq!(fresh_plan.activation, PlannedActivation::Initial); - apply_package( + let active = apply_package( &database, &package, ApplyPrecondition::InitialActivation, @@ -69,6 +69,50 @@ async fn plan_and_apply_name_the_v0_43_0_attachment_verification_shape() { .await .expect("a fresh database applies the initial activation"); + let unchanged = || plan(ApplyPrecondition::RoleChange { current: &active }); + assert_eq!( + unchanged().await.unwrap().activation, + PlannedActivation::AlreadyActive, + ); + database.admin.batch_execute( + r#"WITH proposal AS ( + INSERT INTO registry_internal.registry_proposal_state + (action_id,proposal_id,owner_reference,state,submission_version,workflow_revision) + VALUES ('correction',gen_random_uuid(),'test-owner','submitted',1,1) + RETURNING action_id,proposal_id + ), submission AS ( + INSERT INTO registry_internal.registry_proposal_submissions + (action_id,proposal_id,submission_version,input_revision,contract_fingerprint,effect_digest,snapshot) + SELECT action_id,proposal_id,1,1,'sha256:' || repeat('1',64),'sha256:' || repeat('2',64),'{}' + FROM proposal RETURNING action_id,proposal_id,submission_version,effect_digest + ) + INSERT INTO registry_internal.registry_proposal_review_submissions + (action_id,proposal_id,submission_version,proposal_digest,job_id,authority,producer_id, + policy_id,expected_policy,idempotency_key,create_request,expected_submission_digest,on_approved_mode,state) + SELECT action_id,proposal_id,submission_version,effect_digest,gen_random_uuid(),'test-review', + 'test-producer','approval','{}','older-review','{"initiator":{"issuer":"https://example.test","subject":"person-1"}}', + 'sha256:' || repeat('3',64),'manual','pending' + FROM submission"#, + ).await.unwrap(); + assert_eq!( + unchanged().await.err(), + Some(MigrationError::ReviewInitiatorUpgrade), + "same-package plan names retained work that needs the previous release", + ); + database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions SET state='cancelled'", + &[], + ) + .await + .unwrap(); + assert_eq!( + unchanged().await.unwrap().activation, + PlannedActivation::AlreadyActive, + "settled retained work does not block an unchanged package", + ); + install_v0_43_0_attachment_verification(&database.admin).await; let before = ( registry_state_snapshot(&database.admin).await, diff --git a/crates/registry-breg/tests/postgres_webhook_outbox.rs b/crates/registry-breg/tests/postgres_webhook_outbox.rs index 107e50574b..a30c00ef35 100644 --- a/crates/registry-breg/tests/postgres_webhook_outbox.rs +++ b/crates/registry-breg/tests/postgres_webhook_outbox.rs @@ -71,6 +71,17 @@ async fn real_postgres_webhook_outbox_capture_is_atomic_package_bound_and_determ Some(MutationError::Unavailable), "a source/inventory mismatch is a service fault before mutation I/O" ); + let mut mismatched_value = + serde_json::to_value(&compiled).expect("compiled registry serializes"); + mismatched_value["eventDeliveryInventory"]["deliveries"][0]["principal"] = + json!("substituted-hook-authority"); + let mismatched = + serde_json::from_value(mismatched_value).expect("strict mismatch deserializes"); + assert_eq!( + MutationPlan::from_compiled(&mismatched, "records.case.create").err(), + Some(MutationError::Unavailable), + "a source/authority mismatch is a service fault before mutation I/O" + ); install_compiled_schema(&migration, &compiled, &database.runtime_role) .await diff --git a/crates/registry-breg/tests/startup_http.rs b/crates/registry-breg/tests/startup_http.rs index b96a238763..5cca881081 100644 --- a/crates/registry-breg/tests/startup_http.rs +++ b/crates/registry-breg/tests/startup_http.rs @@ -512,7 +512,7 @@ const AUDIT_DESTINATION_REASON: &str = "the audit file could not be opened: audi const EVENT_DESTINATION_REASON: &str = "the configured delivery key file is unavailable"; -fn startup_errors() -> [StartupError; 41] { +fn startup_errors() -> [StartupError; 42] { [ // The wrapped cause never changes the rendered operational message: it // only lets `bregctl doctor` name it. Any `RuntimeConfigError` variant @@ -577,6 +577,7 @@ fn startup_errors() -> [StartupError; 41] { configured_instance_id: "instance-id-private-canary".to_owned(), pending_deliveries: 2, }, + StartupError::ReviewInitiatorUpgrade, StartupError::ReviewAuthorityMissing { authority: "review-authority-private-canary".to_owned(), retained_submissions: 2, @@ -864,6 +865,9 @@ fn expected_startup_error(error: StartupError) -> &'static str { StartupError::ReviewBindings | StartupError::ReviewAuthorityMissing { .. } => { "the Registry retained review bindings were refused" } + StartupError::ReviewInitiatorUpgrade => { + "retained Review requests use the previous release's initiator format. Use the previous matching Registry Stack release to finish or cancel the affected work before retrying" + } StartupError::AttachmentStorage => { "the Registry attachment storage or verification binding was refused" } diff --git a/crates/registry-bregctl/src/apply_lifecycle.rs b/crates/registry-bregctl/src/apply_lifecycle.rs index 3f4b12cecc..24fee1429c 100644 --- a/crates/registry-bregctl/src/apply_lifecycle.rs +++ b/crates/registry-bregctl/src/apply_lifecycle.rs @@ -523,6 +523,12 @@ async fn prepare_proposal_compatibility( let pool = connection .build_pool() .map_err(|_| ApplyLifecycleError::DatabaseConfiguration)?; + registry_breg::review_store::check_review_initiator_upgrade(&pool) + .await + .map_err(|error| match error { + MigrationError::ReviewInitiatorUpgrade => ApplyLifecycleError::Apply(error), + _ => ApplyLifecycleError::ProposalCompatibility, + })?; match registry_breg::proposal_retention::prepare_proposal_activation_compatibility( &pool, current, diff --git a/crates/registry-bregctl/src/doctor.rs b/crates/registry-bregctl/src/doctor.rs index f0c252adea..c74d85ef4d 100644 --- a/crates/registry-bregctl/src/doctor.rs +++ b/crates/registry-bregctl/src/doctor.rs @@ -404,6 +404,11 @@ fn startup_diagnostic(error: StartupError) -> Diagnostic { "reviewBindings", "the retained review authority or executor bindings were refused", ), + StartupError::ReviewInitiatorUpgrade => ( + "startup.review.initiator-upgrade", + "reviewBindings", + "retained Review requests use the previous release's initiator format. Use the previous matching Registry Stack release to finish or cancel the affected work before retrying", + ), StartupError::AttachmentStorage => ( "startup.attachment-storage.refused", "attachmentStorage", diff --git a/crates/registry-bregctl/src/identity_facts.rs b/crates/registry-bregctl/src/identity_facts.rs index d359a0f2ad..fcbb301646 100644 --- a/crates/registry-bregctl/src/identity_facts.rs +++ b/crates/registry-bregctl/src/identity_facts.rs @@ -313,6 +313,16 @@ pub(crate) fn facts( ) -> Result { let entry = selected(config, issuer)?; let several_issuers = config.authentication().oidc().issuers().count() > 1; + let hook_profiles = registry_breg::auth::proposing_hook_profiles(compiled); + if entry + .access_profiles() + .is_some_and(|listed| listed.iter().any(|profile| hook_profiles.contains(profile))) + { + return Err(unstatable(format!( + "authentication.oidc.issuers.{}.accessProfiles explicitly reaches an internal access profile selected by a proposing Record hook. Remove that profile from the issuer entry", + entry.id() + ))); + } let verifier = entry.token_verifier_config(); let [audience] = verifier.audiences.as_slice() else { return Err(unstatable(format!( @@ -366,6 +376,9 @@ pub(crate) fn facts( let mut profiles: BTreeMap = BTreeMap::new(); let mut omitted_agent_profiles = BTreeSet::new(); for grant in compiled_grants(compiled) { + if hook_profiles.contains(grant.id) { + continue; + } if !entry.reaches_profile(grant.id) { continue; } diff --git a/crates/registry-bregctl/src/init_from_model/render.rs b/crates/registry-bregctl/src/init_from_model/render.rs index 3c9d39f357..277eaba384 100644 --- a/crates/registry-bregctl/src/init_from_model/render.rs +++ b/crates/registry-bregctl/src/init_from_model/render.rs @@ -22,7 +22,7 @@ pub(crate) const SELECTION_PATH: &str = "model/selection.yaml"; /// The registry-wide operator profile the project grants everything to. pub(crate) const OPERATOR_PROFILE: &str = "operator"; -/// The read-only profile the project grants the non-restricted entities to. +/// The optional read-only profile generated from the reporting selection. pub(crate) const READER_PROFILE: &str = "reader"; /// The placeholder identity the plain `init` runtime example carries, which @@ -74,7 +74,9 @@ fn development_plan(plan: &Plan) -> String { yaml.line(0, "people:"); let callers = [ Some((OPERATOR_PROFILE, operator_principal(plan))), - (!reader_entities(plan).is_empty()).then(|| (READER_PROFILE, reader_principal(plan))), + plan.reporting + .is_some() + .then(|| (READER_PROFILE, reader_principal(plan))), ]; for (profile, subject) in callers.into_iter().flatten() { yaml.line(1, &format!("{profile}:")); @@ -98,7 +100,7 @@ fn service_roles(plan: &Plan) -> String { yaml.line(0, "roles:"); let profiles = [ Some(OPERATOR_PROFILE), - (!reader_entities(plan).is_empty()).then_some(READER_PROFILE), + plan.reporting.is_some().then_some(READER_PROFILE), ]; for profile in profiles.into_iter().flatten() { yaml.line(1, &format!("{profile}:")); @@ -133,15 +135,6 @@ fn development_journeys(plan: &Plan) -> String { yaml.finish() } -/// The entities the reader profile may read: those not classified -/// `restricted`. -pub(crate) fn reader_entities(plan: &Plan) -> Vec<&PlannedEntity> { - plan.entities - .iter() - .filter(|entity| entity.classification != Classification::Restricted) - .collect() -} - /// The fields classified above their entity, which `check` reports as /// `breg.access.profile-higher-classification` for every profile reading them. /// This mixes two distinct causes: a field the model marks sensitive inside @@ -565,15 +558,12 @@ fn registry(plan: &Plan) -> String { yaml.line(5, &format!("writableFields: {}", flow_list(&all))); yaml.line(5, &format!("filterableFields: {}", flow_list(&filterable))); } - let readers = reader_entities(plan); - if !readers.is_empty() { + if let Some(reporting) = &plan.reporting { yaml.blank(); yaml.comment( 1, - "A read-only profile over the entities that are not classified `restricted`, \ - reading only their fields that are not either. Its reporting scope and purpose \ - admit whole-collection reads; add `rowBoundaries` if reporting callers must be \ - separated by tenant or jurisdiction.", + "Reporting uses the fields and purpose you selected. It admits whole-collection reads. \ + Add `rowBoundaries` if reporting callers must be separated by tenant or jurisdiction.", ); yaml.line(1, &format!("{}:", scalar(READER_PROFILE))); yaml.line(2, "principalClaim: registry_principal"); @@ -581,26 +571,27 @@ fn registry(plan: &Plan) -> String { 2, &format!("requiredScopes: [{}]", scalar(&read_scope(plan))), ); - yaml.line(2, "requiredPurposes: [registry-reporting]"); + yaml.line( + 2, + &format!( + "requiredPurposes: {}", + flow_list(&[reporting.purpose.as_str()]) + ), + ); yaml.line(2, "permissions:"); yaml.line(3, "records:"); - for entity in readers { - let readable: Vec<&str> = entity - .all_fields() - .filter(|field| field.classification != Classification::Restricted) - .map(|field| field.id.as_str()) - .collect(); - yaml.entry(4, "- recordType", &entity.id); + for grant in &reporting.records { + let readable: Vec<&str> = grant.readable_fields.iter().map(String::as_str).collect(); + yaml.entry(4, "- recordType", &grant.record_type); yaml.line(5, "rowBoundaries: unrestricted"); yaml.line(5, "operations: [get, list]"); yaml.line(5, &format!("readableFields: {}", flow_list(&readable))); - yaml.line( - 5, - &format!( - "filterableFields: {}", - flow_list(&[entity.identifier.id.as_str()]) - ), - ); + if let Some(identifier) = &grant.filterable_identifier { + yaml.line( + 5, + &format!("filterableFields: {}", flow_list(&[identifier.as_str()])), + ); + } } } yaml.finish() @@ -893,28 +884,30 @@ fn journeys(plan: &Plan) -> String { steps_in_journey += ENTITY_JOURNEY_STEPS; } - for entity in reader_entities(plan) { - if steps_in_journey + 1 > FIXTURE_MAX_STEPS_PER_JOURNEY { - journey_index += 1; - steps_in_journey = 0; - open_journey(&mut yaml, journey_index); + if let Some(reporting) = &plan.reporting { + for grant in &reporting.records { + if steps_in_journey + 1 > FIXTURE_MAX_STEPS_PER_JOURNEY { + journey_index += 1; + steps_in_journey = 0; + open_journey(&mut yaml, journey_index); + } + yaml.line( + 3, + &format!( + "- id: {}", + fixture_id("read-", &format!("{}-as-{READER_PROFILE}", grant.route)) + ), + ); + yaml.entry(4, "recordType", &grant.record_type); + yaml.entry(4, "accessProfile", READER_PROFILE); + yaml.line(4, "claims:"); + yaml.entry(5, "principal", &reader_principal(plan)); + yaml.line(5, &format!("scopes: [{}]", scalar(&read_scope(plan)))); + yaml.entry(5, "purpose", &reporting.purpose); + yaml.line(4, "request: {type: list}"); + yaml.line(4, "expect: {outcome: success, status: 200, count: 1}"); + steps_in_journey += 1; } - yaml.line( - 3, - &format!( - "- id: {}", - fixture_id("read-", &format!("{}-as-{READER_PROFILE}", entity.route)) - ), - ); - yaml.entry(4, "recordType", &entity.id); - yaml.entry(4, "accessProfile", READER_PROFILE); - yaml.line(4, "claims:"); - yaml.entry(5, "principal", &reader_principal(plan)); - yaml.line(5, &format!("scopes: [{}]", scalar(&read_scope(plan)))); - yaml.line(5, "purpose: registry-reporting"); - yaml.line(4, "request: {type: list}"); - yaml.line(4, "expect: {outcome: success, status: 200, count: 1}"); - steps_in_journey += 1; } yaml.finish() } @@ -1285,23 +1278,23 @@ fn readme(plan: &Plan) -> String { "- `{OPERATOR_PROFILE}` may create, read, list, and patch every entity and every \ field. It is the default profile used by `tests/journeys.yaml`." ); - if reader_entities(plan).is_empty() { + if plan.reporting.is_some() { let _ = writeln!( out, - "- Every entity is classified `restricted`, so the project declares no read-only \ - profile. Add one when you decide which fields a reader may see." + "- `{READER_PROFILE}` may read and list the Record types and fields named in \ + `reporting` in `{SELECTION_PATH}`." ); } else { let _ = writeln!( out, - "- `{READER_PROFILE}` may read and list the entities that are not classified \ - `restricted`, and only their fields that are not either." + "- To generate a reporting profile, add `reporting` to a selection with the \ + purpose and exact fields the reader needs." ); } let _ = writeln!( out, "\nThe generated profiles bind whole-collection access to explicit scopes and purposes. If \ - separate callers within either profile must see different rows, add `rowBoundaries` \ + separate callers within a profile must see different rows, add `rowBoundaries` \ for the field that carries the registry's tenant or jurisdiction before packaging." ); let _ = writeln!( @@ -1770,6 +1763,7 @@ mod tests { registry_title: "Synthetic Registry".to_owned(), model, entities, + reporting: None, vocabularies: Vec::new(), classification_ceiling: Classification::Internal, connectors: Vec::new(), @@ -1786,6 +1780,7 @@ mod tests { }, entities: Vec::new(), vocabularies: Vec::new(), + reporting: None, }; (plan, selection) } @@ -1811,10 +1806,10 @@ mod tests { #[test] fn a_selection_large_enough_to_exceed_one_journeys_step_bound_is_split_across_several() { - // 33 internal entities, none referencing another, produce 4 steps - // each (create, get, operator list, reader list): 132, past the + // 43 operator-only Record types produce 3 steps + // each (create, get, list): 129, past the // fixture's 128-step-per-journey bound. - let (plan, selection) = synthetic_plan(33); + let (plan, selection) = synthetic_plan(43); let files = render(&plan, &selection); let (_root, path) = write_project(&files); let authoring = compile(&path, ProfileArg::Authoring, "init").unwrap_or_else(|failure| { @@ -1831,7 +1826,7 @@ mod tests { steps }) .sum(); - assert_eq!(total_steps, 33 * 4); + assert_eq!(total_steps, 43 * 3); validate_fixture_journeys(&files[FIXTURE_JOURNEYS_PATH], &authoring) .unwrap_or_else(|error| panic!("{error}")); } @@ -2050,12 +2045,59 @@ mod tests { ); let profiles = registry["accessProfiles"].as_object().expect("profiles"); assert!(profiles.contains_key(OPERATOR_PROFILE)); - let reader_person = &profiles[READER_PROFILE]["permissions"]["records"][0]; - assert_eq!(reader_person["recordType"], "person"); - let readable = reader_person["readableFields"] + assert!(!profiles.contains_key(READER_PROFILE)); + } + + #[test] + fn the_reporting_selection_refuses_contextually_sensitive_subjects() { + let source = "apiVersion: id.registrystack.org/formats/breg/model-selection/v1alpha1 +kind: BRegModelSelection +model: publicschema +registry: + id: public-services + title: Public services +recordTypes: + - concept: ServiceApplication + properties: + - name: subject_uri + - concept: AdministrativeDecision + properties: + - name: subject_uri + - concept: ServiceCapacityObservation + properties: + - name: subject_uri +"; + let report_on = |record_type| { + let authored = format!( + "{source}reporting:\n purpose: registry-reporting\n records:\n - recordType: {record_type}\n readableFields: [subject-uri]\n" + ); + Selection::parse("public-services", authored.as_bytes()).expect("the selection parses") + }; + let model = publicschema::model().expect("the snapshot reads"); + for record_type in ["service-application", "administrative-decision"] { + let refusal = resolve(&report_on(record_type), &model) + .expect_err("a protected subject is refused even when named explicitly"); + assert_eq!(refusal.code, "init.selection.reporting"); + assert_eq!(refusal.path, "/reporting/records/0/readableFields/0"); + } + let selection = report_on("service-capacity-observation"); + let plan = resolve(&selection, &model).expect("the selection resolves"); + let files = render(&plan, &selection); + let (_root, path) = write_project(&files); + compile(&path, ProfileArg::Authoring, "init").unwrap_or_else(|failure| { + panic!("{}", serde_json::to_string_pretty(&failure).unwrap()) + }); + let registry = yaml(&files, "registry.yaml"); + let permissions = registry["accessProfiles"][READER_PROFILE]["permissions"]["records"] .as_array() - .expect("readable"); - assert!(!readable.iter().any(|field| field == "marital-status")); + .expect("reader permissions"); + assert_eq!(permissions.len(), 1); + assert_eq!(permissions[0]["recordType"], "service-capacity-observation"); + assert_eq!( + permissions[0]["readableFields"], + yaml_value("[subject-uri]") + ); + assert_eq!(permissions[0]["operations"], yaml_value("[get, list]")); } #[test] @@ -2081,21 +2123,17 @@ mod tests { let files = render(&plan, &selection); let development = yaml(&files, "dev.yaml"); let people = development["people"].as_object().expect("people"); - assert_eq!(people.len(), 2); + assert_eq!(people.len(), 1); let operator = &people[OPERATOR_PROFILE]; assert_eq!(operator["subject"], "household-registry-operator"); assert_eq!(operator["roles"][0], OPERATOR_PROFILE); assert!(operator.get("grants").is_none()); - assert_eq!(people[READER_PROFILE]["roles"][0], READER_PROFILE); let service = yaml(&files, "service.yaml"); assert_eq!( service["roles"][OPERATOR_PROFILE]["accessProfiles"]["breg"][0], OPERATOR_PROFILE ); - assert_eq!( - service["roles"][READER_PROFILE]["accessProfiles"]["breg"][0], - READER_PROFILE - ); + assert!(service["roles"].get(READER_PROFILE).is_none()); let journeys = yaml(&files, FIXTURE_JOURNEYS_PATH); let steps = journeys["journeys"][0]["steps"].as_array().expect("steps"); assert_eq!(steps[0]["id"], "create-person"); @@ -2122,7 +2160,7 @@ mod tests { ); assert!(steps .iter() - .any(|step| step["id"] == "read-persons-as-reader")); + .all(|step| step["accessProfile"] == OPERATOR_PROFILE)); let runtime = String::from_utf8(files["runtime.example.yaml"].clone()).expect("UTF-8"); assert!(runtime.contains("instanceId: household-registry-1")); assert!(!runtime.contains(RUNTIME_EXAMPLE_PLACEHOLDER)); diff --git a/crates/registry-bregctl/src/init_from_model/resolve.rs b/crates/registry-bregctl/src/init_from_model/resolve.rs index 91b493231c..74a04552ac 100644 --- a/crates/registry-bregctl/src/init_from_model/resolve.rs +++ b/crates/registry-bregctl/src/init_from_model/resolve.rs @@ -16,10 +16,13 @@ use registry_breg::{Diagnostic, RelatedDiagnostic}; use registry_linkml::publicschema::{self, Sensitivity, LANGUAGES}; use registry_linkml::{ClassDef, EnumDef, Model, Range, SlotDef}; use registry_manifest_core::MAX_CODELIST_CONCEPTS; +use registry_platform_config::identity_facts::{valid_purpose, MAXIMUM_NAME_BYTES}; use registry_platform_yaml::{lookalike_local_id_pairs, DisplayText}; use serde_json::{json, Value}; -use super::selection::{EntitySelection, PropertySelection, Selection, VocabularyMode}; +use super::selection::{ + EntitySelection, PropertySelection, ReportingSelection, Selection, VocabularyMode, +}; use crate::diagnostic; /// An enumeration with more values than this is carried as a bounded code @@ -127,6 +130,7 @@ pub(crate) struct Plan { pub registry_title: String, pub model: ModelFacts, pub entities: Vec, + pub reporting: Option, /// The closed vocabularies at least one field draws from, in identifier /// order. pub vocabularies: Vec, @@ -139,6 +143,20 @@ pub(crate) struct Plan { pub connectors: Vec, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PlannedReporting { + pub purpose: String, + pub records: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PlannedReportingRecord { + pub record_type: String, + pub route: String, + pub readable_fields: Vec, + pub filterable_identifier: Option, +} + impl Plan { /// The entities no reference field connects to another entity, in plan /// order. Empty when the plan has one entity, since there is nothing to @@ -283,6 +301,13 @@ impl PlannedEntity { pub(crate) fn all_fields(&self) -> impl Iterator { std::iter::once(&self.identifier).chain(self.fields.iter()) } + + pub(super) fn reporting_fields(&self) -> impl Iterator { + self.all_fields().filter(|field| { + self.classification != Classification::Restricted + && field.classification != Classification::Restricted + }) + } } #[derive(Clone, Debug, PartialEq)] @@ -573,18 +598,97 @@ pub(crate) fn resolve(selection: &Selection, model: &Model) -> Result Result { + let refusal = |path: &str, message: &str| diagnostic("init.selection.reporting", path, message); + if !valid_purpose(&reporting.purpose) { + return Err(refusal( + "/reporting/purpose", + &format!("write a reporting purpose of 1 to {MAXIMUM_NAME_BYTES} printable ASCII characters without spaces"), + )); + } + if reporting.records.is_empty() { + return Err(refusal( + "/reporting/records", + "name at least one reporting Record type", + )); + } + let mut record_types = BTreeSet::new(); + let mut records = Vec::new(); + for (index, grant) in reporting.records.iter().enumerate() { + let path = format!("/reporting/records/{index}"); + let record_type_path = format!("{path}/recordType"); + let entity = entities + .iter() + .find(|entity| entity.id == grant.record_type) + .ok_or_else(|| refusal(&record_type_path, "name a generated Record type by its id"))?; + if entity.classification == Classification::Restricted { + return Err(refusal( + &record_type_path, + "choose a public or internal Record type for whole-collection reporting", + )); + } + if !record_types.insert(entity.id.as_str()) { + return Err(refusal( + &record_type_path, + "list each reporting Record type once", + )); + } + if grant.readable_fields.is_empty() { + return Err(refusal( + &format!("{path}/readableFields"), + "name at least one readable field", + )); + } + let eligible: BTreeSet<&str> = entity + .reporting_fields() + .map(|field| field.id.as_str()) + .collect(); + for (index, field) in grant.readable_fields.iter().enumerate() { + let field_path = format!("{path}/readableFields/{index}"); + if !eligible.contains(field.as_str()) { + return Err(refusal( + &field_path, + "name a generated public or internal field on this Record type", + )); + } + } + records.push(PlannedReportingRecord { + record_type: entity.id.clone(), + route: entity.route.clone(), + readable_fields: grant.readable_fields.clone().into_vec(), + filterable_identifier: grant + .readable_fields + .contains(&entity.identifier.id) + .then(|| entity.identifier.id.clone()), + }); + } + Ok(PlannedReporting { + purpose: reporting.purpose.clone(), + records, + }) +} + /// The enumerations the selected properties draw from, by model name: every /// one, and the ones carried as a closed vocabulary in the project. #[derive(Default)] @@ -755,7 +859,7 @@ fn resolve_entity( ), )); } - let classification = slot_classification(slot) + let classification = slot_classification(model, class, slot) .map_err(|error| convention_error(&property_path, &error))? .max(floor); fields.push(PlannedField { @@ -1165,7 +1269,7 @@ fn object_schema(model: &Model, class: &ClassDef) -> Option { } Range::Class(_) => continue, }; - classification = classification.max(slot_classification(slot).ok()?); + classification = classification.max(slot_classification(model, class, slot).ok()?); let schema = if slot.multivalued { json!({"type": "array", "maxItems": LIST_MAX_ITEMS, "items": item}) } else { @@ -1186,12 +1290,18 @@ fn object_schema(model: &Model, class: &ClassDef) -> Option { }) } -/// The classification a property's own sensitivity earns. -fn slot_classification(slot: &SlotDef) -> Result { - Ok(match publicschema::sensitivity(slot)? { - Some(Sensitivity::Sensitive | Sensitivity::Restricted) => Classification::Restricted, - None => Classification::Internal, - }) +/// The classification a property earns in the concept that carries it. +fn slot_classification( + model: &Model, + class: &ClassDef, + slot: &SlotDef, +) -> Result { + Ok( + match publicschema::sensitivity_in_class(model, class, slot)? { + Some(Sensitivity::Sensitive | Sensitivity::Restricted) => Classification::Restricted, + None => Classification::Internal, + }, + ) } /// The schema of a GeoJSON geometry: the object shape every geometry shares, @@ -1691,6 +1801,72 @@ mod tests { assert_eq!(plan.classification_ceiling, Classification::Internal); } + #[test] + fn contextual_subject_sensitivity_is_limited_to_the_two_public_service_contexts() { + for concept in ["ServiceApplication", "AdministrativeDecision"] { + let plan = resolved(&format!( + "recordTypes:\n - concept: {concept}\n properties:\n - name: subject_uri\n" + )); + assert_eq!( + field(&plan, &kebab_case(concept), "subject-uri").classification, + Classification::Restricted, + "{concept}.subject_uri" + ); + assert_eq!(plan.classification_ceiling, Classification::Restricted); + } + + let unrelated = resolved( + "recordTypes:\n - concept: ServiceCapacityObservation\n properties:\n - name: subject_uri\n", + ); + assert_eq!( + field(&unrelated, "service-capacity-observation", "subject-uri").classification, + Classification::Internal + ); + assert_eq!(unrelated.classification_ceiling, Classification::Internal); + } + + #[test] + fn reporting_requires_a_purpose_and_distinct_generated_records() { + let source = "recordTypes:\n - concept: Person\n id: residents\n properties:\n - name: given_name\n"; + for (entries, location) in [ + ( + "purpose: ' '\n records: [{recordType: residents, readableFields: [given-name]}]", + "/reporting/purpose", + ), + ( + "purpose: 'staff reporting'\n records: [{recordType: residents, readableFields: [given-name]}]", + "/reporting/purpose", + ), + ("purpose: directory\n records: []", "/reporting/records"), + ( + "purpose: directory\n records: [{recordType: person, readableFields: [given-name]}]", + "/reporting/records/0/recordType", + ), + ( + "purpose: directory\n records: [{recordType: residents, readableFields: []}]", + "/reporting/records/0/readableFields", + ), + ( + "purpose: directory\n records: [{recordType: residents, readableFields: [missing]}]", + "/reporting/records/0/readableFields/0", + ), + ( + "purpose: directory\n records:\n - {recordType: residents, readableFields: [given-name]}\n - {recordType: residents, readableFields: [residents-code]}", + "/reporting/records/1/recordType", + ), + ] { + let error = refused(&format!("{source}reporting:\n {entries}\n")); + assert_eq!(error.code, "init.selection.reporting", "{entries}"); + assert_eq!(error.path, location, "{entries}"); + } + let too_long = "x".repeat(registry_platform_config::identity_facts::MAXIMUM_NAME_BYTES + 1); + let error = refused(&format!( + "{source}reporting:\n purpose: {too_long}\n records: [{{recordType: residents, readableFields: [given-name]}}]\n" + )); + assert_eq!(error.code, "init.selection.reporting"); + assert_eq!(error.path, "/reporting/purpose"); + } + #[test] fn an_entity_classification_is_taken_from_the_selection_and_checked() { let plan = resolved( diff --git a/crates/registry-bregctl/src/init_from_model/selection.rs b/crates/registry-bregctl/src/init_from_model/selection.rs index 29fc02453d..c14f9b65c9 100644 --- a/crates/registry-bregctl/src/init_from_model/selection.rs +++ b/crates/registry-bregctl/src/init_from_model/selection.rs @@ -13,6 +13,7 @@ use std::fmt; use registry_breg::literal_text::{LiteralText, WRITE_THE_VALUE}; use registry_platform_yaml::{ ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader, RemovedKey, Report, RetiredApiVersion, + UniqueList, }; use serde::{Deserialize, Serialize}; @@ -82,6 +83,38 @@ pub(crate) struct Selection { pub entities: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub vocabularies: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reporting: Option, +} + +/// The exact grant for the optional, whole-collection reporting profile. +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(crate) struct ReportingSelection { + /// The purpose a verified reader token must carry. + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 128), regex(pattern = r"^[\x21-\x7E]+$")) + )] + pub purpose: String, + #[cfg_attr(feature = "schema", schemars(length(min = 1)))] + pub records: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(crate) struct ReportingRecordSelection { + /// The generated Record type id, including any selected id override. + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub record_type: String, + /// Exact generated field ids to grant. + #[cfg_attr( + feature = "schema", + schemars(with = "UniqueList", length(min = 1)) + )] + pub readable_fields: UniqueList, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] @@ -254,6 +287,23 @@ recordTypes: assert_eq!((source.line, source.column), (Some(7), Some(10))); } + #[test] + fn reporting_readable_fields_refuse_duplicates() { + let document = format!( + "{MINIMAL}reporting:\n purpose: directory-statistics\n records:\n - recordType: thing\n readableFields: [label, label]\n" + ); + let report = Selection::parse("selection.yaml", document.as_bytes()) + .expect_err("duplicate readable fields are refused"); + let diagnostic = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.duplicate-item") + .expect("the shared unique-list diagnostic is retained"); + assert_eq!(diagnostic.path, "/reporting/records/0/readableFields/1"); + let source = diagnostic.source.as_ref().expect("positioned"); + assert_eq!((source.line, source.column), (Some(16), Some(31))); + } + #[test] fn the_echo_round_trips() { let selection = Selection::parse("test", MINIMAL.as_bytes()).expect("parses"); diff --git a/crates/registry-bregctl/src/init_from_model/wizard.rs b/crates/registry-bregctl/src/init_from_model/wizard.rs index 963b5da6bd..204a4adfb7 100644 --- a/crates/registry-bregctl/src/init_from_model/wizard.rs +++ b/crates/registry-bregctl/src/init_from_model/wizard.rs @@ -15,7 +15,7 @@ //! decision is a pure function beneath a thin prompt layer, and the prompt //! layer only turns those functions' output into questions. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use inquire::error::InquireError; use inquire::validator::{MinLengthValidator, Validation}; @@ -24,11 +24,12 @@ use inquire::{Confirm, CustomUserError, MultiSelect, Select, Text}; use registry_breg::Diagnostic; use registry_linkml::publicschema::{self, Sensitivity}; use registry_linkml::{ClassDef, Model, Range, SlotDef}; +use registry_platform_config::identity_facts::{valid_purpose, MAXIMUM_NAME_BYTES}; use super::resolve::{self, INLINE_VOCABULARY_THRESHOLD}; use super::selection::{ - EntitySelection, ModelName, PropertySelection, RegistrySelection, Selection, VocabularyMode, - VocabularySelection, API_VERSION, KIND, + EntitySelection, ModelName, PropertySelection, RegistrySelection, ReportingRecordSelection, + ReportingSelection, Selection, VocabularyMode, VocabularySelection, API_VERSION, KIND, }; use crate::diagnostic; @@ -192,7 +193,7 @@ pub(super) fn gather(model_name: ModelName, model: &Model) -> Result Result Result, Diagnost Ok(chosen.into_iter().map(|option| option.index).collect()) } +fn ask_reporting(plan: &resolve::Plan) -> Result, Diagnostic> { + let fields: Vec<_> = plan + .entities + .iter() + .flat_map(|entity| { + entity + .reporting_fields() + .map(move |field| (entity.id.as_str(), field.id.as_str())) + }) + .collect(); + if fields.is_empty() + || !Confirm::new("Add a read-only reporting profile?") + .with_default(false) + .with_help_message("the reader may list every row of each Record type you choose") + .prompt() + .map_err(prompt_error)? + { + return Ok(None); + } + let purpose = Text::new("Reporting purpose") + .with_help_message("the exact purpose the reader's token must carry") + .with_validator(|input: &str| -> Result { + Ok(if valid_purpose(input) { + Validation::Valid + } else { + Validation::Invalid( + format!( + "use 1 to {MAXIMUM_NAME_BYTES} printable ASCII characters without spaces" + ) + .into(), + ) + }) + }) + .prompt() + .map_err(prompt_error)?; + let labels = fields + .iter() + .map(|(record_type, field)| format!("{record_type}.{field}")) + .collect(); + let chosen = MultiSelect::new("Which fields may the reporting profile read?", labels) + .with_validator(MinLengthValidator::new(1)) + .with_help_message("space to toggle, type to filter, enter to confirm") + .raw_prompt() + .map_err(prompt_error)?; + let mut records = BTreeMap::<&str, Vec>::new(); + for option in chosen { + let (record_type, field) = fields[option.index]; + records + .entry(record_type) + .or_default() + .push(field.to_owned()); + } + Ok(Some(ReportingSelection { + purpose, + records: records + .into_iter() + .map(|(record_type, readable_fields)| ReportingRecordSelection { + record_type: record_type.to_owned(), + readable_fields: registry_platform_yaml::UniqueList::new(readable_fields) + .expect("the interactive selection contains distinct fields"), + }) + .collect(), + })) +} + /// Shows the selection the answers describe and asks whether to derive from /// it. fn confirm_selection(selection: &Selection, note: Option) -> Result { @@ -513,13 +580,14 @@ fn property_offer( let slots = model .induced_slots(concept) .map_err(|error| resolve::model_error("model", &error))?; + let class = &model.classes[concept]; let mut offered = Vec::new(); let mut withheld = Vec::new(); for slot in slots { match resolve::property_support(model, slot, concepts) { Ok(()) => offered.push(PropertyOption { name: slot.name.clone(), - label: property_label(model, slot, concepts)?, + label: property_label(model, class, slot, concepts)?, ticked: ticked(slot)? || refers_to_chosen(model, slot, concepts), }), Err(reason) => withheld.push(WithheldProperty { @@ -536,11 +604,12 @@ fn property_offer( /// behind the model record it. fn property_label( model: &Model, + class: &ClassDef, slot: &SlotDef, concepts: &[String], ) -> Result { let mut label = format!("{}: {}", slot.name, shape(model, slot, concepts)); - match publicschema::sensitivity(slot) + match publicschema::sensitivity_in_class(model, class, slot) .map_err(|error| resolve::convention_error("model", &error))? { Some(Sensitivity::Sensitive) => label.push_str(", sensitive"), @@ -864,6 +933,7 @@ fn assemble( }) .collect(), vocabularies, + reporting: None, } } @@ -1142,6 +1212,24 @@ mod tests { ); } + #[test] + fn contextual_subject_sensitivity_is_visible_in_the_property_offer() { + for concept in ["ServiceApplication", "AdministrativeDecision"] { + let choices = offer(concept, &[concept]); + assert!( + offered(&choices, "subject_uri") + .label + .ends_with(", sensitive"), + "{concept}.subject_uri" + ); + } + let unrelated = offer( + "ServiceCapacityObservation", + &["ServiceCapacityObservation"], + ); + assert_eq!(offered(&unrelated, "subject_uri").label, "subject_uri: URI"); + } + #[test] fn properties_are_ticked_when_the_evidence_says_most_systems_record_them() { let offer = offer("Person", &["Person"]); diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 2156ddf508..1572923e10 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -8477,6 +8477,14 @@ fn lifecycle_failure(command: &'static str, error: ApplyLifecycleError) -> Failu DiagnosticArtifact::DataOperation, SuggestedAction::CorrectDataBinding, ), + error @ registry_breg::migration::MigrationError::ReviewInitiatorUpgrade => { + return source_failure( + command, + diagnostic("apply.review.initiator-upgrade", "database", &error.to_string()), + DiagnosticArtifact::PackageActivation, + SuggestedAction::RestoreActiveProposalRecovery, + ); + } registry_breg::migration::MigrationError::ActiveProposalRecoveryUnavailable => ( "apply.proposals.recovery-required", "proposal", diff --git a/crates/registry-bregctl/tests/cli.rs b/crates/registry-bregctl/tests/cli.rs index d7de4ac72d..7395c08f9e 100644 --- a/crates/registry-bregctl/tests/cli.rs +++ b/crates/registry-bregctl/tests/cli.rs @@ -5542,6 +5542,133 @@ recordTypes: } } +#[test] +fn init_from_publicschema_reporting_uses_only_authored_grants() { + let workspace = tempfile::tempdir().unwrap(); + let root = workspace.path().canonicalize().unwrap(); + let selection = root.join("selection.yaml"); + let model = r#"apiVersion: id.registrystack.org/formats/breg/model-selection/v1alpha1 +kind: BRegModelSelection +model: publicschema +registry: + id: civil-directory + title: Civil directory +recordTypes: + - concept: Person + properties: + - name: given_name + - name: date_of_birth +"#; + let reporting = r#"reporting: + purpose: directory-statistics + records: + - recordType: person + readableFields: [given-name] +"#; + for (name, options) in [("operator-only", ""), ("with-reporting", reporting)] { + let project = root.join(name); + fs::write(&selection, format!("{model}{options}")).unwrap(); + let initialized = bregctl(&[ + "init", + path(&project), + "--from", + "publicschema", + "--selection", + path(&selection), + ]); + assert!(initialized.status.success(), "{initialized:?}"); + let checked = bregctl(&["check", path(&project)]); + assert!(checked.status.success(), "{checked:?}"); + let check_development = || { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .args(["rstack-dev", "check", "--json", "--", path(&project)]) + .env("REGISTRY_STACK_POSTURE", "development") + .env("RSTACK_BREGCTL_BIN", env!("CARGO_BIN_EXE_bregctl")) + .output() + .unwrap() + }; + let checked = check_development(); + assert!(checked.status.success(), "{checked:?}"); + let yaml = |file: &str| -> Value { + serde_norway::from_slice(&fs::read(project.join(file)).unwrap()).unwrap() + }; + let registry = yaml("registry.yaml"); + let service = yaml("service.yaml"); + let development = yaml("dev.yaml"); + assert!(registry["accessProfiles"].get("operator").is_some()); + assert_eq!( + service["roles"]["operator"]["accessProfiles"]["breg"], + json!(["operator"]) + ); + assert_eq!( + development["people"]["operator"]["roles"], + json!(["operator"]) + ); + let reader = registry["accessProfiles"].get("reader"); + let role = service["roles"].get("reader"); + let actor = development["people"].get("reader"); + if options.is_empty() { + assert!(reader.is_none() && role.is_none() && actor.is_none()); + } else { + let reader = reader.expect("reporting profile"); + assert_eq!(reader["requiredPurposes"], json!(["directory-statistics"])); + assert_eq!( + reader["permissions"]["records"], + json!([{ + "recordType": "person", + "operations": ["get", "list"], + "readableFields": ["given-name"], + "rowBoundaries": "unrestricted" + }]) + ); + assert_eq!(role.unwrap()["accessProfiles"]["breg"], json!(["reader"])); + assert_eq!(actor.unwrap()["roles"], json!(["reader"])); + assert_eq!( + yaml("model/selection.yaml")["reporting"], + serde_norway::from_str::(reporting).unwrap()["reporting"] + ); + + let mut service = service; + service["roles"].as_object_mut().unwrap().remove("reader"); + fs::write( + project.join("service.yaml"), + serde_norway::to_string(&service).unwrap(), + ) + .unwrap(); + let refused = check_development(); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + let diagnostic = &json_stdout(&refused)["diagnostics"][0]; + assert_eq!(diagnostic["path"], "/people/reader/roles"); + assert_eq!( + diagnostic["message"], + "A role is missing from service.yaml." + ); + } + } + + let invalid = reporting.replace("given-name", "unknown-field"); + fs::write(&selection, format!("{model}{invalid}")).unwrap(); + let destination = root.join("refused"); + let refused = bregctl(&[ + "--format", + "json", + "init", + path(&destination), + "--from", + "publicschema", + "--selection", + path(&selection), + ]); + assert_eq!(refused.status.code(), Some(1), "{refused:?}"); + let report = json_stdout(&refused); + assert_eq!(report["diagnostics"][0]["code"], "init.selection.reporting"); + assert_eq!( + report["diagnostics"][0]["path"], + "/reporting/records/0/readableFields/0" + ); + assert!(!destination.exists()); +} + #[test] fn init_from_publicschema_reports_the_derived_project_in_the_report_shape() { let project = TestProject::asset_fixture(); diff --git a/crates/registry-bregctl/tests/identity_facts.rs b/crates/registry-bregctl/tests/identity_facts.rs index 05ec8c6f38..b8b55f88d9 100644 --- a/crates/registry-bregctl/tests/identity_facts.rs +++ b/crates/registry-bregctl/tests/identity_facts.rs @@ -123,6 +123,122 @@ fn generate_with( ) } +/// A valid project with one ordinary HTTP profile and one caller-independent +/// profile reserved for a proposing Record hook. +fn project_with_internal_hook(root: &Path) -> PathBuf { + let project = root.join("hook-project"); + std::fs::create_dir(&project).unwrap(); + std::fs::write( + project.join("registry.yaml"), + r#"apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: identity-facts-hook + version: 0.1.0 + defaultLanguage: en + canonicalBaseIri: https://identity-facts.example.invalid +datasets: + records: {} +recordTypes: + record: + primaryDataset: records + route: records + mutationMode: mutable + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + hooks: + - id: record-created + phase: after + trigger: created + principal: hook-worker + projection: [label] + handler: {type: url, destinationId: record-events} + followup: + primaryDataset: records + route: followups + mutationMode: create-only + fields: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} +actions: + open-followup: + execution: {mode: immediate} + inputs: + - {id: label, type: string, required: true, maximumLength: 100, classification: public} + plan: + type: fixed + effects: + - id: followup + target: {recordType: followup} + operation: create + set: {label: {fromInput: label}} +accessProfiles: + ordinary-reader: + default: true + principalClaim: registry_principal + requiredScopes: [registry:generic:read] + requiredPurposes: [registry-operations] + permissions: + records: + - recordType: record + operations: [get] + readableFields: [label] + rowBoundaries: unrestricted + hook-worker: + principalClaim: registry_principal + requiredScopes: unrestricted + permissions: + actions: + - action: open-followup + operations: [invoke] + targets: + - {recordType: followup, rowBoundaries: unrestricted} + results: [followup] +"#, + ) + .unwrap(); + project +} + +#[test] +fn omitted_issuer_profiles_generate_ordinary_facts_with_an_internal_hook() { + let scratch = tempfile::tempdir().unwrap(); + let runtime = runtime(scratch.path()); + let project = project_with_internal_hook(scratch.path()); + let output = scratch.path().join("facts.yaml"); + + let (ok, stdout, stderr) = generate_for(&project, &runtime, &output); + assert!(ok, "{stdout}\n{stderr}"); + let facts = read_facts(&output); + assert_eq!( + facts + .access_profiles + .iter() + .map(|profile| profile.id.as_str()) + .collect::>(), + vec!["ordinary-reader"] + ); +} + +#[test] +fn an_explicit_internal_hook_profile_is_refused_for_identity_facts() { + let scratch = tempfile::tempdir().unwrap(); + let runtime = runtime(scratch.path()); + edit_runtime( + &runtime, + " allowedClients: [generic-registry-client]\n", + " allowedClients: [generic-registry-client]\n accessProfiles: [hook-worker]\n", + ); + let project = project_with_internal_hook(scratch.path()); + let output = scratch.path().join("facts.yaml"); + + let (ok, stdout, stderr) = generate_for(&project, &runtime, &output); + assert!(!ok, "{stdout}\n{stderr}"); + assert!(!output.exists()); + let report = format!("{stdout}{stderr}"); + assert!(report.contains("identity-facts.unstatable"), "{report}"); + assert!(report.contains("internal access profile"), "{report}"); +} + #[test] fn the_maintained_fixture_states_golden_facts_without_paths_or_secrets() { let scratch = tempfile::tempdir().unwrap(); diff --git a/crates/registry-bregctl/tests/publicschema_inline_value_lists.rs b/crates/registry-bregctl/tests/publicschema_inline_value_lists.rs index 63d3530ecd..b2de4f94ce 100644 --- a/crates/registry-bregctl/tests/publicschema_inline_value_lists.rs +++ b/crates/registry-bregctl/tests/publicschema_inline_value_lists.rs @@ -222,7 +222,7 @@ fn journey_source() -> String { let reader_claims = json!({ "principal": "inline-value-list-reader", "scopes": ["registry:inline-value-list:read"], - "purpose": "registry-reporting" + "purpose": "licensing-report" }); let operator_step = |id: &str, record_type: &str, request: Value, expect: Value| { json!({ @@ -286,6 +286,16 @@ fn journey_source() -> String { "profession-code": revised_professions }} })); + let mut no_purpose = reader_claims.clone(); + no_purpose.as_object_mut().unwrap().remove("purpose"); + steps.push(json!({ + "id": "reader-without-purpose-is-refused", + "recordType": "professional-license", + "accessProfile": "reader", + "claims": no_purpose, + "request": {"type": "get", "recordCapture": "revised-license"}, + "expect": {"outcome": "refusal", "status": 403, "problemCode": "profile.not-authorized"} + })); steps.push(operator_step( "reject-missing-code-scheme", "professional-license", @@ -417,6 +427,10 @@ fn credential_source() -> String { ("get-license", "operator-token"), ("patch-license", "operator-token"), ("reader-gets-license", "reader-token"), + ( + "reader-without-purpose-is-refused", + "reader-without-purpose-token", + ), ("reject-missing-code-scheme", "operator-token"), ("reject-more-than-fifty-professions", "operator-token"), ( @@ -516,7 +530,17 @@ impl ProjectFixture { "aud": AUDIENCE, "registry_actor_kind": "service", "registry_principal": "inline-value-list-reader", - "registry_purpose": "registry-reporting", + "registry_purpose": "licensing-report", + "scope": "registry:inline-value-list:read", + })) + .as_bytes(), + ); + write_secret( + &secrets.join("reader-without-purpose-token"), + idp.mint_token(json!({ + "aud": AUDIENCE, + "registry_actor_kind": "service", + "registry_principal": "inline-value-list-reader", "scope": "registry:inline-value-list:read", })) .as_bytes(), @@ -559,6 +583,13 @@ recordTypes: - concept: DrivingEntitlement properties: - name: driving_condition_codes +reporting: + purpose: licensing-report + records: + - recordType: professional-license + readableFields: [professional-license-code, profession-code] + - recordType: driving-entitlement + readableFields: [driving-entitlement-code] "# } diff --git a/crates/registry-bregctl/tests/tool_schema.rs b/crates/registry-bregctl/tests/tool_schema.rs index d4f6bbc454..d1e9a251b3 100644 --- a/crates/registry-bregctl/tests/tool_schema.rs +++ b/crates/registry-bregctl/tests/tool_schema.rs @@ -181,6 +181,39 @@ fn model_selection_registry_title_uses_display_text() { } } +#[test] +fn model_selection_reporting_requires_a_purpose_and_explicit_fields() { + let documents = documents().expect("the tool schemas generate"); + let schema = compile(&documents["model-selection.v1alpha1.schema.json"]); + let mut selection = example("crates/registry-linkml/publicschema/starters/household.yaml"); + selection["reporting"] = json!({ + "purpose": "directory-statistics", + "records": [{"recordType": "person", "readableFields": ["given-name"]}] + }); + assert!(schema.is_valid(&selection)); + let mut duplicate = selection.clone(); + duplicate["reporting"]["records"][0]["readableFields"] = json!(["given-name", "given-name"]); + assert!(!schema.is_valid(&duplicate)); + for (pointer, value) in [ + ("/reporting/purpose", json!("")), + ("/reporting/purpose", json!("staff reporting")), + ( + "/reporting/purpose", + json!("x".repeat(registry_platform_config::identity_facts::MAXIMUM_NAME_BYTES + 1)), + ), + ("/reporting/records", json!([])), + ("/reporting/records/0/readableFields", json!([])), + ( + "/reporting/records/0/readableFields", + json!({"upToClassification": "internal"}), + ), + ] { + let mut refused = selection.clone(); + *refused.pointer_mut(pointer).unwrap() = value; + assert!(!schema.is_valid(&refused), "{pointer}"); + } +} + /// Every committed file under `root` named `name`, outside hidden /// directories. fn committed(root: &str, name: &str) -> Vec { 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 34f498f61c..4b9202480c 100644 --- a/crates/registry-casework-client-node/__test__/facade.test-d.ts +++ b/crates/registry-casework-client-node/__test__/facade.test-d.ts @@ -1,6 +1,6 @@ import './ask-timing.test-d' import { CaseworkClient, CaseworkClientError, submissionDigest, type ContentDigest, type SubjectBinding, - type PolicyBinding, type ReviewCreateRequest, type ReviewRequestAccepted, + type HumanIdentity, type PolicyBinding, type ReviewCreateRequest, type ReviewRequestAccepted, type ReviewTask, type SupervisoryReviewTask, type StaffingDiagnostic, type ReviewTaskDecisionRequest, type ReviewStaffingQuery, type ReviewTaskMarker, type ReviewCaseloadMoveRequest, type ReviewClockRecomputeRequest, type ReviewPolicyClosure, type ReviewStagePolicy, type RoutingRule } from '../client' @@ -29,6 +29,12 @@ const stageOutcomes: ReadonlyArray | undefined = explainedStage.outcomes const ruleLabel: string | undefined = explainedRule.label void policyLabel; void stageLabel; void stagePublicProgressCode; void stageOutcomes; void ruleLabel const submitted: ReviewCreateRequest = { policy, subject, requesterReference: 'proposal-1', context: { mode: 'submitted', snapshot: { reference: 'proposal-1' } } } +const initiator: HumanIdentity = { issuer: 'https://issuer.example.test', principalClaim: 'sub', subject: 'person-1' } +const initiated: ReviewCreateRequest = { ...submitted, initiator } +void initiated +// @ts-expect-error a human identity must carry the claim that gives its value meaning +const unboundInitiator: HumanIdentity = { issuer: 'https://issuer.example.test', subject: 'person-1' } +void unboundInitiator const current: ReviewCreateRequest = { ...submitted, context: { mode: 'current-source', binding: { reference: 'proposal-1' } } } void client.createOrRecoverReviewRequest(token, 'requester', 'submit-1', current, digest) const computed: ContentDigest = submissionDigest('producer', subject.source, submitted) diff --git a/crates/registry-casework-client-node/client.d.ts b/crates/registry-casework-client-node/client.d.ts index e4bc790537..d23da125a9 100644 --- a/crates/registry-casework-client-node/client.d.ts +++ b/crates/registry-casework-client-node/client.d.ts @@ -232,7 +232,7 @@ export interface SubjectBinding { source: string; type: string; id: string; vers export interface PolicyBinding { id: string; version: string; digest: ContentDigest } /** Select the current admitted policy by ID, or require one complete exact pin. */ export type PolicySelection = { id: string; version?: never; digest?: never } | PolicyBinding -export interface HumanIdentity { issuer: string; subject: string } +export interface HumanIdentity { issuer: string; principalClaim: string; subject: string } export type ReviewContext = | { mode: 'submitted'; snapshot: Readonly> } | { mode: 'current-source'; binding: { reference: string } } 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 f2a618dc17..67073fa74c 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 @@ -460,6 +460,7 @@ class PolicyIdSelection(TypedDict): PolicySelection: TypeAlias = PolicyIdSelection | PolicyBinding class HumanIdentity(TypedDict): issuer: str + principalClaim: str subject: str class SourceContextBinding(TypedDict): reference: str diff --git a/crates/registry-casework-client-py/tests/python/test_typing_contract.py b/crates/registry-casework-client-py/tests/python/test_typing_contract.py index ab1d0cae36..d32ddff71d 100644 --- a/crates/registry-casework-client-py/tests/python/test_typing_contract.py +++ b/crates/registry-casework-client-py/tests/python/test_typing_contract.py @@ -285,6 +285,12 @@ def test_review_create_request_requires_wire_mandatory_fields(self) -> None: } optional = classes["_ReviewCreateRequestOptional"] request = classes["ReviewCreateRequest"] + identity = classes["HumanIdentity"] + + self.assertEqual( + {node.target.id for node in identity.body if isinstance(node, ast.AnnAssign)}, + {"issuer", "principalClaim", "subject"}, + ) self.assertEqual( {node.target.id for node in optional.body if isinstance(node, ast.AnnAssign)}, diff --git a/crates/registry-casework-core/src/config.rs b/crates/registry-casework-core/src/config.rs index 8f04502b85..7c6e72de0d 100644 --- a/crates/registry-casework-core/src/config.rs +++ b/crates/registry-casework-core/src/config.rs @@ -1415,9 +1415,60 @@ impl CaseworkProject { "Declare the review policies they submit under reviewPolicies, or remove trustedProducers.", ); } + let producer_profiles: BTreeSet<&str> = self + .trusted_producers + .iter() + .map(|producer| producer.profile.as_str()) + .collect(); + let human_claims: BTreeSet<&str> = self + .access_profiles + .iter() + .filter(|profile| !producer_profiles.contains(profile.id.as_str())) + .map(|profile| profile.principal_claim.as_str()) + .collect(); + let human_principal_claim = if human_claims.len() == 1 { + human_claims.first().copied() + } else { + None + }; for producer in &self.trusted_producers { let at = keyed("trustedProducers", &producer.id); producer.findings(findings, &at); + match ( + producer.trusted_initiator_issuer.as_ref(), + producer.trusted_initiator_principal_claim.as_ref(), + ) { + (Some(_), None) => findings.push( + "casework.review-producer.missing-trusted-initiator-principal-claim", + format!("{at}/trustedInitiatorPrincipalClaim"), + "trustedInitiatorIssuer needs the principal claim that names the same person to BReg and Casework", + "Add trustedInitiatorPrincipalClaim matching the principalClaim used by every human Casework access profile.", + ), + (None, Some(_)) => findings.push( + "casework.review-producer.missing-trusted-initiator-issuer", + format!("{at}/trustedInitiatorIssuer"), + "trustedInitiatorPrincipalClaim needs the issuer that authenticates initiators", + "Add trustedInitiatorIssuer, or remove trustedInitiatorPrincipalClaim.", + ), + _ => {} + } + if let (Some(expected), Some(actual)) = ( + human_principal_claim, + producer.trusted_initiator_principal_claim.as_deref(), + ) { + if actual != expected { + findings.push( + "casework.review-producer.incompatible-trusted-initiator-principal-claim", + format!("{at}/trustedInitiatorPrincipalClaim"), + format!( + "trusted initiators use principal claim \"{actual}\", but human Casework profiles use \"{expected}\"" + ), + format!( + "Set trustedInitiatorPrincipalClaim to \"{expected}\", and configure the producer to send that claim." + ), + ); + } + } if self .access_profiles .iter() @@ -1459,7 +1510,8 @@ impl CaseworkProject { ); } } - let mut exclusion_reported = producer.trusted_initiator_issuer.is_some(); + let mut exclusion_reported = producer.trusted_initiator_issuer.is_some() + || producer.trusted_initiator_principal_claim.is_some(); let mut asks_reported = producer.reads_asks; for (policy_index, policy_id) in producer.review_policies.iter().enumerate() { let Some(policy) = self @@ -1989,6 +2041,10 @@ pub struct ReviewProducerPolicy { )] #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] pub trusted_initiator_issuer: Option, + /// The claim the trusted initiator issuer uses to name the person. It must + /// match the one human Casework profiles read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trusted_initiator_principal_claim: Option, /// The requester profile a person named as this producer's initiator /// authenticates with to read the requester-visible history of their own /// requests. Absent, no initiator reads anything. @@ -2061,6 +2117,12 @@ impl ReviewProducerPolicy { 256, "casework.review-producer.invalid-trusted-initiator-issuer", ), + ( + "trustedInitiatorPrincipalClaim", + self.trusted_initiator_principal_claim.as_ref(), + 128, + "casework.review-producer.invalid-trusted-initiator-principal-claim", + ), ] { if value.is_some_and(|value| !bounded_config_text(value, maximum)) { findings.push( diff --git a/crates/registry-casework-core/tests/format_alignment.rs b/crates/registry-casework-core/tests/format_alignment.rs index df190d891e..4f980ae2f1 100644 --- a/crates/registry-casework-core/tests/format_alignment.rs +++ b/crates/registry-casework-core/tests/format_alignment.rs @@ -200,7 +200,7 @@ fn two_of_each(order: [usize; 2]) -> String { contextProviders:\n{}\ reviewPolicies:\n{}\ taskTemplates:\n{}\ - trustedProducers:\n notice-service: {{profile: producer, issuer: \"https://issuer.example\", subject: notice-service, trustedInitiatorIssuer: \"https://people.example\", sourceNamespaces: [notice-source], reviewPolicies: [alpha, beta], retention: {{receiptRetentionDays: 7}}}}\n", + trustedProducers:\n notice-service: {{profile: producer, issuer: \"https://issuer.example\", subject: notice-service, trustedInitiatorIssuer: \"https://people.example\", trustedInitiatorPrincipalClaim: principal, sourceNamespaces: [notice-source], reviewPolicies: [alpha, beta], retention: {{receiptRetentionDays: 7}}}}\n", ordered([provider("alpha"), provider("beta")]), ordered([policy("alpha"), policy("beta")]), ordered([template("alpha"), template("beta")]), diff --git a/crates/registry-casework-core/tests/policy_compiler.rs b/crates/registry-casework-core/tests/policy_compiler.rs index a54557d1b7..cb4159dd56 100644 --- a/crates/registry-casework-core/tests/policy_compiler.rs +++ b/crates/registry-casework-core/tests/policy_compiler.rs @@ -22,7 +22,7 @@ fn project_value() -> Value { "outcomes":{"approved":{"label":"Approve","settlement":"approved","reasonRequired":false,"publicReason":"optional"},"rejected":{"label":"Reject","settlement":"rejected","reasonRequired":true,"publicReason":"required"}}, "displaySchema":{"type":"object","additionalProperties":false,"required":["title"],"properties":{"title":{"type":"string","maxLength":160},"region":{"type":"string","maxLength":20}}} }}, - "trustedProducers":{"notice-service":{"profile":"producer","issuer":"https://issuer.example","subject":"notice-service","trustedInitiatorIssuer":"https://people.example","sourceNamespaces":["notice-source"],"reviewPolicies":["notice-review"],"retention":{"receiptRetentionDays":7}}} + "trustedProducers":{"notice-service":{"profile":"producer","issuer":"https://issuer.example","subject":"notice-service","trustedInitiatorIssuer":"https://people.example","trustedInitiatorPrincipalClaim":"principal","sourceNamespaces":["notice-source"],"reviewPolicies":["notice-review"],"retention":{"receiptRetentionDays":7}}} }) } fn decode(value: Value) -> CaseworkProject { diff --git a/crates/registry-casework-core/tests/principal_claims.rs b/crates/registry-casework-core/tests/principal_claims.rs index 7d424f2c3d..596c0872dd 100644 --- a/crates/registry-casework-core/tests/principal_claims.rs +++ b/crates/registry-casework-core/tests/principal_claims.rs @@ -31,7 +31,7 @@ fn project_value() -> Value { "outcomes":{"approved":{"label":"Approve","settlement":"approved","reasonRequired":false,"publicReason":"optional"},"rejected":{"label":"Reject","settlement":"rejected","reasonRequired":true,"publicReason":"required"}}, "displaySchema":{"type":"object","additionalProperties":false,"required":["title"],"properties":{"title":{"type":"string","maxLength":160}}} }}, - "trustedProducers":{"notice-service":{"profile":"producer","issuer":"https://issuer.example","subject":"notice-service","trustedInitiatorIssuer":"https://people.example","initiatorProfile":"initiator","sourceNamespaces":["notice-source"],"reviewPolicies":["notice-review"],"retention":{"receiptRetentionDays":7}}} + "trustedProducers":{"notice-service":{"profile":"producer","issuer":"https://issuer.example","subject":"notice-service","trustedInitiatorIssuer":"https://people.example","trustedInitiatorPrincipalClaim":"principal","initiatorProfile":"initiator","sourceNamespaces":["notice-source"],"reviewPolicies":["notice-review"],"retention":{"receiptRetentionDays":7}}} }) } @@ -53,6 +53,43 @@ fn the_baseline_project_loads() { assert_eq!(refusals(&project_value()), Vec::new()); } +#[test] +fn an_initiator_excluding_producer_pins_the_human_principal_claim() { + for (member, code) in [ + ( + "trustedInitiatorPrincipalClaim", + "casework.review-producer.missing-trusted-initiator-principal-claim", + ), + ( + "trustedInitiatorIssuer", + "casework.review-producer.missing-trusted-initiator-issuer", + ), + ] { + let mut value = project_value(); + value["trustedProducers"]["notice-service"] + .as_object_mut() + .unwrap() + .remove(member); + let refused = refusals(&value); + assert!( + refused.iter().any(|finding| finding.0 == code), + "{member}: {refused:?}" + ); + } + + let mut value = project_value(); + value["trustedProducers"]["notice-service"]["trustedInitiatorPrincipalClaim"] = + json!("registry_principal"); + let refused = refusals(&value); + assert_eq!(refused.len(), 1, "{refused:?}"); + assert_eq!( + refused[0].0, + "casework.review-producer.incompatible-trusted-initiator-principal-claim" + ); + assert!(refused[0].1.contains("registry_principal")); + assert!(refused[0].1.contains("principal")); +} + #[test] fn every_human_profile_kind_must_share_the_claim_of_the_others() { // Reviewer roles are staff, supervisor and administrator; the other two @@ -88,6 +125,8 @@ fn one_claim_everywhere_loads() { { profile["principalClaim"] = json!(claim); } + value["trustedProducers"]["notice-service"]["trustedInitiatorPrincipalClaim"] = + json!(claim); assert_eq!(refusals(&value), Vec::new(), "{claim}"); } } diff --git a/crates/registry-casework/examples/problem-catalog.rs b/crates/registry-casework/examples/problem-catalog.rs index ff1fdaf6d9..f29e82cca6 100644 --- a/crates/registry-casework/examples/problem-catalog.rs +++ b/crates/registry-casework/examples/problem-catalog.rs @@ -147,7 +147,7 @@ fn review_wire_examples() -> Result>, serde_js typed_examples::(vec![ json!({"policy":{"id":"address-review"},"subject":subject,"requesterReference":"case-current-policy","context":{"mode":"submitted","snapshot":{"field":"value"}}}), json!({"policy":policy,"subject":subject,"requesterReference":"case-1","context":{"mode":"submitted","snapshot":{"field":"value"}},"resultConstraints":{"type":"object"}}), - json!({"policy":policy,"subject":subject,"requesterReference":"case-1","initiator":{"issuer":"https://issuer.example","subject":"person-1"},"context":{"mode":"current-source","binding":{"reference":"source-ref"}}}), + json!({"policy":policy,"subject":subject,"requesterReference":"case-1","initiator":{"issuer":"https://issuer.example","principalClaim":"sub","subject":"person-1"},"context":{"mode":"current-source","binding":{"reference":"source-ref"}}}), ])?, ), ( diff --git a/crates/registry-casework/src/pinned_work.rs b/crates/registry-casework/src/pinned_work.rs index 1dbfe76334..f585d295b7 100644 --- a/crates/registry-casework/src/pinned_work.rs +++ b/crates/registry-casework/src/pinned_work.rs @@ -18,7 +18,7 @@ pub struct StrandedWork { impl StrandedWork { pub fn describe(&self) -> String { format!( - "{} open review(s) of policy {} version {}: {}", + "{} review(s) of policy {} version {}: {}", self.reviews, self.policy, self.version, self.reason ) } @@ -43,7 +43,10 @@ pub fn pinned_work_verdict(items: &[StrandedWork], _digest: &str) -> PinnedWorkV } } pub fn stranded_work_refusal(items: &[StrandedWork], _digest: &str) -> String { - format!("the package would orphan pinned reviews: {}. Keep the prior package until these reviews finish, or cancel them through their bound producer before activation",describe_stranded_work(items)) + format!( + "the package would orphan pinned reviews: {}. Keep the previous compatible release and package running. Finish active reviews or have their bound producer cancel them. Let settled reviews reach the end of accountability retention, or start this release with a fresh database", + describe_stranded_work(items) + ) } #[derive(Clone, Debug)] pub(crate) struct PinnedReviewGroup { @@ -53,9 +56,16 @@ pub(crate) struct PinnedReviewGroup { pub active_stage_index: usize, pub reviews: u64, } +#[derive(Clone, Debug)] +pub(crate) struct RetainedInitiatorGroup { + pub policy: ReviewPolicyClosure, + pub producer_id: String, + pub reviews: u64, +} #[derive(Default)] pub(crate) struct PinnedWorkInventory { pub reviews: Vec, + pub retained_initiators: Vec, } pub async fn stranded_pinned_work( store: &PostgresStore, @@ -194,9 +204,49 @@ pub(crate) fn compare_pinned_work( }); } } + let active_human_claim = human_principal_claim( + &project.access_profiles, + project + .trusted_producers + .iter() + .map(|producer| producer.profile.as_str()), + ); + for group in &inventory.retained_initiators { + let retained_claim = group + .policy + .dependencies + .trusted_producers + .iter() + .find(|producer| producer.id == group.producer_id) + .and_then(|producer| producer.trusted_initiator_principal_claim.as_deref()); + let reason = match (retained_claim, active_human_claim) { + (Some(retained), Some(active)) if retained == active => continue, + (Some(_), Some(_)) => "the retained initiator principal claim changed", + _ => "the retained initiator principal claim cannot be established", + }; + conflicts.push(StrandedWork { + policy: group.policy.identity.id.clone(), + version: group.policy.identity.version.clone(), + reviews: group.reviews, + reason: reason.to_owned(), + }); + } conflicts } +fn human_principal_claim<'a>( + profiles: &'a [registry_casework_core::AccessProfile], + producer_profiles: impl Iterator, +) -> Option<&'a str> { + let producer_profiles: BTreeSet<_> = producer_profiles.collect(); + let claims: BTreeSet<_> = profiles + .iter() + .filter(|profile| !producer_profiles.contains(profile.id.as_str())) + .map(|profile| profile.principal_claim.as_str()) + .collect(); + (claims.len() == 1).then(|| *claims.first().expect("one human principal claim")) +} + fn profile_preserved(project: &CaseworkProject, policy: &ReviewPolicyClosure, id: &str) -> bool { match ( project @@ -218,3 +268,23 @@ fn profile_preserved(project: &CaseworkProject, policy: &ReviewPolicyClosure, id _ => false, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retained_work_refusal_names_active_and_settled_recovery_paths() { + let items = vec![StrandedWork { + policy: "licence-review".into(), + version: "2".into(), + reviews: 3, + reason: "the retained initiator principal claim changed".into(), + }]; + + assert_eq!( + stranded_work_refusal(&items, "unused-package-digest"), + "the package would orphan pinned reviews: 3 review(s) of policy licence-review version 2: the retained initiator principal claim changed. Keep the previous compatible release and package running. Finish active reviews or have their bound producer cancel them. Let settled reviews reach the end of accountability retention, or start this release with a fresh database" + ); + } +} diff --git a/crates/registry-casework/src/review.rs b/crates/registry-casework/src/review.rs index 8a778a8014..31e60e7078 100644 --- a/crates/registry-casework/src/review.rs +++ b/crates/registry-casework/src/review.rs @@ -2869,11 +2869,18 @@ impl PostgresStore { let initiator = match ( request.initiator.as_ref(), producer.trusted_initiator_issuer.as_deref(), + producer.trusted_initiator_principal_claim.as_deref(), ) { - (Some(initiator), Some(issuer)) if initiator.issuer == issuer => Some(initiator), - (Some(_), None) if !requires_initiator => None, - (None, _) if requires_initiator => return Err(ReviewRuntimeError::InitiatorRequired), - (None, _) => None, + (Some(initiator), Some(issuer), Some(principal_claim)) + if initiator.issuer == issuer && initiator.principal_claim == principal_claim => + { + Some(initiator) + } + (Some(_), None, None) if !requires_initiator => None, + (None, _, _) if requires_initiator => { + return Err(ReviewRuntimeError::InitiatorRequired) + } + (None, _, _) => None, _ => return Err(ReviewRuntimeError::Invalid), }; match (&snapshot.context, &request.context) { diff --git a/crates/registry-casework/src/store.rs b/crates/registry-casework/src/store.rs index 7ccb572efd..6105b7f26a 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -863,6 +863,7 @@ pub(crate) async fn pinned_work_inventory_in( ) -> Result { refuse_reviews_stored_by_an_earlier_release(tx).await?; let rows=tx.query("SELECT policy_snapshot,producer_id,source_namespace,active_stage_index,count(*) FROM casework_review_requests WHERE lifecycle='reviewing' GROUP BY policy_snapshot,producer_id,source_namespace,active_stage_index",&[]).await?; + let retained_initiators=tx.query("SELECT policy_snapshot,producer_id,count(*) FROM casework_review_requests WHERE initiator_issuer IS NOT NULL AND initiator_subject IS NOT NULL GROUP BY policy_snapshot,producer_id",&[]).await?; Ok(crate::pinned_work::PinnedWorkInventory { reviews: rows .into_iter() @@ -878,6 +879,17 @@ pub(crate) async fn pinned_work_inventory_in( }) }) .collect::, StoreError>>()?, + retained_initiators: retained_initiators + .into_iter() + .map(|row| { + Ok(crate::pinned_work::RetainedInitiatorGroup { + policy: stored_policy(row.get(0))?, + producer_id: row.get(1), + reviews: u64::try_from(row.get::<_, i64>(2)) + .map_err(|_| StoreError::Corrupt)?, + }) + }) + .collect::, StoreError>>()?, }) } diff --git a/crates/registry-casework/src/task_grants/http_tests.rs b/crates/registry-casework/src/task_grants/http_tests.rs index 2c0b9badeb..1b695f0e79 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -208,7 +208,7 @@ async fn fixture_for_role_with_templates( "teams":{"team":{"label":"Review team","serves":["review"],"memberProfiles":["staff"],"supervisorProfiles":["supervisor"]}}, "contextProviders":{"source":{"deploymentRef":"source","sourceNamespace":"source","capabilities":["human-display","service-status","task-grant-context"],"serviceProfiles":{"service-status":"status-reader","task-grant-context":"task-reader"}}}, "reviewPolicies":{"external-review":{"version":"1","purpose":"approval","context":{"mode":"current-source","provider":"source","contract":context_contract()},"stages":[{"id":"review","queue":"review","decidingProfiles":[profile_id],"requiredApprovals":1,"excludeInitiator":true,"excludePreviousStageReviewers":false}],"retention":{"terminalRetentionDays":30,"accountabilityRetentionDays":90},"displaySchema":context_schema(),"outcomes":{"approved":{"label":"Approve","settlement":"approved","reasonRequired":false,"publicReason":"optional"}}}}, - "trustedProducers":{"producer":{"profile":"producer","issuer":ISSUER,"subject":"producer","trustedInitiatorIssuer":ISSUER,"sourceNamespaces":["source"],"reviewPolicies":["external-review"],"retention":{"receiptRetentionDays":30}}} + "trustedProducers":{"producer":{"profile":"producer","issuer":ISSUER,"subject":"producer","trustedInitiatorIssuer":ISSUER,"trustedInitiatorPrincipalClaim":"sub","sourceNamespaces":["source"],"reviewPolicies":["external-review"],"retention":{"receiptRetentionDays":30}}} })).unwrap(); project.task_templates = vec![template, review_template]; if lifetime > TASK_GRANT_LIFETIME_SECONDS { diff --git a/crates/registry-casework/src/task_grants/native_exchange_tests.rs b/crates/registry-casework/src/task_grants/native_exchange_tests.rs index 9ab0e6acb1..3786d60644 100644 --- a/crates/registry-casework/src/task_grants/native_exchange_tests.rs +++ b/crates/registry-casework/src/task_grants/native_exchange_tests.rs @@ -1232,7 +1232,7 @@ async fn fixture( }; context_export.check().unwrap(); let context_export_path = "context-providers/source.json"; - let mut project:CaseworkProject=serde_json::from_value(json!({"apiVersion":CASEWORK_API_VERSION,"kind":CASEWORK_KIND,"project":{"id":"native-tasks","version":"1"},"accessProfiles":{"staff":{"principalClaim":"sub","requiredScopes":["casework:staff"],"actsAs":"staff"},"supervisor":{"principalClaim":"sub","requiredScopes":["casework:supervisor"],"actsAs":"supervisor"},"administrator":{"principalClaim":"sub","requiredScopes":["casework:admin"],"actsAs":"administrator"},"producer":{"principalClaim":"sub","requiredScopes":["casework:reviews:request"],"actsAs":"requester"}},"queues":{"review":{"label":"Review"}},"teams":{"team":{"label":"Review team","serves":["review"],"memberProfiles":["staff"],"supervisorProfiles":["supervisor"]}},"contextProviders":{"source":{"deploymentRef":"source","sourceNamespace":"source","description":context_export_path,"capabilities":["human-display","service-status","task-grant-context"],"serviceProfiles":{"service-status":"status-reader","task-grant-context":"task-reader"}}},"reviewPolicies":{"external-review":{"version":"1","purpose":"approval","context":{"mode":"current-source","provider":"source","contract":context_contract},"stages":[{"id":"review","queue":"review","decidingProfiles":["staff"],"requiredApprovals":1,"excludeInitiator":true,"excludePreviousStageReviewers":false}],"retention":{"terminalRetentionDays":30,"accountabilityRetentionDays":90},"displaySchema":context_schema,"outcomes":{"approved":{"label":"Approve","settlement":"approved","reasonRequired":false,"publicReason":"optional"}}}},"trustedProducers":{"producer":{"profile":"producer","issuer":issuer.url(),"subject":"native-producer","trustedInitiatorIssuer":issuer.url(),"sourceNamespaces":["source"],"reviewPolicies":["external-review"],"retention":{"receiptRetentionDays":7}}}})).unwrap(); + let mut project:CaseworkProject=serde_json::from_value(json!({"apiVersion":CASEWORK_API_VERSION,"kind":CASEWORK_KIND,"project":{"id":"native-tasks","version":"1"},"accessProfiles":{"staff":{"principalClaim":"sub","requiredScopes":["casework:staff"],"actsAs":"staff"},"supervisor":{"principalClaim":"sub","requiredScopes":["casework:supervisor"],"actsAs":"supervisor"},"administrator":{"principalClaim":"sub","requiredScopes":["casework:admin"],"actsAs":"administrator"},"producer":{"principalClaim":"sub","requiredScopes":["casework:reviews:request"],"actsAs":"requester"}},"queues":{"review":{"label":"Review"}},"teams":{"team":{"label":"Review team","serves":["review"],"memberProfiles":["staff"],"supervisorProfiles":["supervisor"]}},"contextProviders":{"source":{"deploymentRef":"source","sourceNamespace":"source","description":context_export_path,"capabilities":["human-display","service-status","task-grant-context"],"serviceProfiles":{"service-status":"status-reader","task-grant-context":"task-reader"}}},"reviewPolicies":{"external-review":{"version":"1","purpose":"approval","context":{"mode":"current-source","provider":"source","contract":context_contract},"stages":[{"id":"review","queue":"review","decidingProfiles":["staff"],"requiredApprovals":1,"excludeInitiator":true,"excludePreviousStageReviewers":false}],"retention":{"terminalRetentionDays":30,"accountabilityRetentionDays":90},"displaySchema":context_schema,"outcomes":{"approved":{"label":"Approve","settlement":"approved","reasonRequired":false,"publicReason":"optional"}}}},"trustedProducers":{"producer":{"profile":"producer","issuer":issuer.url(),"subject":"native-producer","trustedInitiatorIssuer":issuer.url(),"trustedInitiatorPrincipalClaim":"sub","sourceNamespaces":["source"],"reviewPolicies":["external-review"],"retention":{"receiptRetentionDays":7}}}})).unwrap(); project.task_templates = vec![template, evidence_template, scheduling_template]; project.check().unwrap(); diff --git a/crates/registry-casework/tests/access_profile_selection.rs b/crates/registry-casework/tests/access_profile_selection.rs index 37305fb5da..befe829b2b 100644 --- a/crates/registry-casework/tests/access_profile_selection.rs +++ b/crates/registry-casework/tests/access_profile_selection.rs @@ -709,6 +709,7 @@ trustedProducers: subject: producer-b-sub initiatorProfile: initiator trustedInitiatorIssuer: {idp_issuer} + trustedInitiatorPrincipalClaim: sub sourceNamespaces: [standalone] reviewPolicies: [decision] retention: diff --git a/crates/registry-casework/tests/breg_review_journey.rs b/crates/registry-casework/tests/breg_review_journey.rs index 7e2a67a717..09dd8e0ea8 100644 --- a/crates/registry-casework/tests/breg_review_journey.rs +++ b/crates/registry-casework/tests/breg_review_journey.rs @@ -158,10 +158,10 @@ fn project(root: &std::path::Path, idp: &MockIdp, context: &BregContextExport) - "apiVersion":"id.registrystack.org/formats/casework/project/v1alpha1","kind":"CaseworkProject", "project":{"id":"facility-review-journey","version":"1"}, "accessProfiles":{ - "staff":{"principalClaim":"sub","requiredScopes":["casework:staff"],"actsAs":"staff"}, - "supervisor":{"principalClaim":"sub","requiredScopes":["casework:supervisor"],"actsAs":"supervisor"}, - "administrator":{"principalClaim":"sub","requiredScopes":["casework:admin"],"actsAs":"administrator"}, - "requester":{"principalClaim":"sub","requiredScopes":["casework:reviews:request"],"actsAs":"requester"} + "staff":{"principalClaim":"registry_principal","requiredScopes":["casework:staff"],"actsAs":"staff"}, + "supervisor":{"principalClaim":"registry_principal","requiredScopes":["casework:supervisor"],"actsAs":"supervisor"}, + "administrator":{"principalClaim":"registry_principal","requiredScopes":["casework:admin"],"actsAs":"administrator"}, + "requester":{"principalClaim":"registry_principal","requiredScopes":["casework:reviews:request"],"actsAs":"requester"} }, "queues":{"review":{"label":"Facility reviews"}}, "teams":{"reviewers":{"label":"Reviewers","serves":["review"],"memberProfiles":["staff"],"supervisorProfiles":["supervisor"]}}, @@ -178,7 +178,7 @@ fn project(root: &std::path::Path, idp: &MockIdp, context: &BregContextExport) - "rejected":{"label":"Reject","settlement":"rejected","reasonRequired":true,"publicReason":"required"}, "changes-requested":{"label":"Request changes","settlement":"changes-requested","reasonRequired":true,"publicReason":"optional"}}}}, "trustedProducers":{"facility-registry":{"profile":"requester","issuer":idp.issuer(), - "subject":"facility-review-producer","trustedInitiatorIssuer":idp.issuer(), + "subject":"facility-review-producer","trustedInitiatorIssuer":idp.issuer(),"trustedInitiatorPrincipalClaim":"registry_principal", "sourceNamespaces":[SOURCE],"reviewPolicies":["facility-address-review"],"retention":{"receiptRetentionDays":7}}} }); fs::write( @@ -236,21 +236,21 @@ fn approval_pattern_project( .unwrap(); let (profiles, queues, stages, team_profiles) = match pattern { ApprovalPattern::SingleReviewer => ( - json!({"staff":{"principalClaim":"sub","requiredScopes":["casework:staff"],"actsAs":"staff"}}), + json!({"staff":{"principalClaim":"registry_principal","requiredScopes":["casework:staff"],"actsAs":"staff"}}), json!({"reviews":{"label":"Reviews awaiting approval"}}), json!([{"id":"review","queue":"reviews","decidingProfiles":["staff"],"requiredApprovals":1,"excludeInitiator":true}]), json!(["staff"]), ), ApprovalPattern::TwoPeer => ( - json!({"staff":{"principalClaim":"sub","requiredScopes":["casework:staff"],"actsAs":"staff"}}), + json!({"staff":{"principalClaim":"registry_principal","requiredScopes":["casework:staff"],"actsAs":"staff"}}), json!({"reviews":{"label":"Reviews awaiting approval"}}), json!([{"id":"review","queue":"reviews","decidingProfiles":["staff"],"requiredApprovals":2,"excludeInitiator":true}]), json!(["staff"]), ), ApprovalPattern::TechnicalThenAuthorization => ( json!({ - "technical-reviewer":{"principalClaim":"sub","requiredScopes":["casework:technical-reviewer"],"actsAs":"staff"}, - "authorizer":{"principalClaim":"sub","requiredScopes":["casework:authorizer"],"actsAs":"staff"} + "technical-reviewer":{"principalClaim":"registry_principal","requiredScopes":["casework:technical-reviewer"],"actsAs":"staff"}, + "authorizer":{"principalClaim":"registry_principal","requiredScopes":["casework:authorizer"],"actsAs":"staff"} }), json!({ "technical-checks":{"label":"Technical checks"}, @@ -266,9 +266,9 @@ fn approval_pattern_project( let mut access_profiles = profiles.as_object().unwrap().clone(); access_profiles.extend( json!({ - "requester":{"principalClaim":"sub","requiredScopes":["casework:reviews:request"],"actsAs":"requester"}, - "supervisor":{"principalClaim":"sub","requiredScopes":["casework:supervisor"],"actsAs":"supervisor"}, - "administrator":{"principalClaim":"sub","requiredScopes":["casework:admin"],"actsAs":"administrator"} + "requester":{"principalClaim":"registry_principal","requiredScopes":["casework:reviews:request"],"actsAs":"requester"}, + "supervisor":{"principalClaim":"registry_principal","requiredScopes":["casework:supervisor"],"actsAs":"supervisor"}, + "administrator":{"principalClaim":"registry_principal","requiredScopes":["casework:admin"],"actsAs":"administrator"} }) .as_object() .unwrap() @@ -299,7 +299,7 @@ fn approval_pattern_project( "changes-requested":{"label":"Request changes","settlement":"changes-requested","reasonRequired":true,"publicReason":"optional"} }}}, "trustedProducers":{"facility-registry":{"profile":"requester","issuer":idp.issuer(), - "subject":"facility-review-producer","trustedInitiatorIssuer":idp.issuer(), + "subject":"facility-review-producer","trustedInitiatorIssuer":idp.issuer(),"trustedInitiatorPrincipalClaim":"registry_principal", "sourceNamespaces":[SOURCE],"reviewPolicies":[pattern.id()],"retention":{"receiptRetentionDays":7}}} }); fs::write( diff --git a/crates/registry-casework/tests/review_acceptance_postgres.rs b/crates/registry-casework/tests/review_acceptance_postgres.rs index 11f316b15f..5b48f16e6b 100644 --- a/crates/registry-casework/tests/review_acceptance_postgres.rs +++ b/crates/registry-casework/tests/review_acceptance_postgres.rs @@ -33,7 +33,7 @@ fn project_value(source: bool, routing: bool) -> Value { "clocks":["deadline"],"retention":{"terminalRetentionDays":30,"accountabilityRetentionDays":90}, "outcomes":{"approved":{"label":"Approve","settlement":"approved","reasonRequired":false,"publicReason":"optional"},"rejected":{"label":"Reject","settlement":"rejected","reasonRequired":true,"publicReason":"required"}}, "displaySchema":{"type":"object","additionalProperties":false,"required":["title","region"],"properties":{"title":{"type":"string","maxLength":160},"region":{"type":"string","maxLength":20}}}}}, - "trustedProducers":{"notice-service":{"profile":"producer","issuer":"https://issuer.test","subject":"notice-service","trustedInitiatorIssuer":"https://issuer.test","sourceNamespaces":["notice-source"],"reviewPolicies":["notice-review"],"retention":{"receiptRetentionDays":7}}} + "trustedProducers":{"notice-service":{"profile":"producer","issuer":"https://issuer.test","subject":"notice-service","trustedInitiatorIssuer":"https://issuer.test","trustedInitiatorPrincipalClaim":"sub","sourceNamespaces":["notice-source"],"reviewPolicies":["notice-review"],"retention":{"receiptRetentionDays":7}}} }); if source { let bytes = registry_platform_canonical_json::canonicalize_json( @@ -269,6 +269,7 @@ impl Fixture { requester_reference: format!("ref-{id}"), initiator: Some(HumanIdentity { issuer: "https://issuer.test".into(), + principal_claim: "sub".into(), subject: "initiator".into(), }), context: if self.project.context_providers.is_empty() { diff --git a/crates/registry-casework/tests/review_http.rs b/crates/registry-casework/tests/review_http.rs index 1d5ac95d4f..d192125d81 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -54,6 +54,7 @@ struct DelegatedSourceBarrier { const AUDIENCE: &str = "urn:test:casework-review"; const TEST_SOURCE_AUDIENCE: &str = "urn:test:breg-review-source"; +const REVIEW_PRINCIPAL_CLAIM: &str = "registry_principal"; #[derive(Clone, Default)] struct InboxLogs(Arc>>); @@ -255,7 +256,7 @@ fn profile(id: &str, role: CaseworkActsAs) -> AccessProfile { id: id.to_owned(), label: None, description: None, - principal_claim: "registry_principal".to_owned(), + principal_claim: REVIEW_PRINCIPAL_CLAIM.to_owned(), required_scopes: vec![format!("casework:{id}")], acts_as: role, default: false, @@ -380,6 +381,7 @@ fn project(issuer: &str) -> CaseworkProject { issuer: issuer.to_owned(), subject: "registry-service".to_owned(), trusted_initiator_issuer: Some(issuer.to_owned()), + trusted_initiator_principal_claim: Some(REVIEW_PRINCIPAL_CLAIM.to_owned()), initiator_profile: Some("initiator".to_owned()), reads_asks: false, source_namespaces: vec!["registry".to_owned()], @@ -398,6 +400,7 @@ fn project(issuer: &str) -> CaseworkProject { issuer: issuer.to_owned(), subject: "registry-service".to_owned(), trusted_initiator_issuer: Some(issuer.to_owned()), + trusted_initiator_principal_claim: Some(REVIEW_PRINCIPAL_CLAIM.to_owned()), initiator_profile: None, reads_asks: false, source_namespaces: vec!["registry".to_owned()], @@ -439,6 +442,7 @@ fn review_request_for_subject( requester_reference: reference.to_owned(), initiator: Some(HumanIdentity { issuer: issuer.to_owned(), + principal_claim: REVIEW_PRINCIPAL_CLAIM.to_owned(), subject: "initiator".to_owned(), }), context: ReviewContext::CurrentSource { @@ -5225,6 +5229,7 @@ async fn an_excluded_initiator_and_a_missing_initiator_get_their_own_problem_cod // with a code a UI can explain. request.initiator = Some(HumanIdentity { issuer: idp.issuer(), + principal_claim: REVIEW_PRINCIPAL_CLAIM.to_owned(), subject: "reviewer".to_owned(), }); let (status, created) = send(create_http_request(&request, Some(&token(&idp)))).await; diff --git a/crates/registry-casework/tests/review_payment_fixture_postgres.rs b/crates/registry-casework/tests/review_payment_fixture_postgres.rs index 7d76bd666b..00a8b0993a 100644 --- a/crates/registry-casework/tests/review_payment_fixture_postgres.rs +++ b/crates/registry-casework/tests/review_payment_fixture_postgres.rs @@ -438,6 +438,7 @@ fn project(issuer: &str) -> CaseworkProject { issuer: issuer.to_owned(), subject: "payment-service".to_owned(), trusted_initiator_issuer: None, + trusted_initiator_principal_claim: None, initiator_profile: None, reads_asks: false, source_namespaces: vec!["payments".to_owned()], diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index 4ee4204b73..8aa2a8ad34 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -381,6 +381,7 @@ fn project(version: &str) -> CaseworkProject { issuer: "https://issuer.test".to_owned(), subject: "registry-service".to_owned(), trusted_initiator_issuer: Some("https://issuer.test".to_owned()), + trusted_initiator_principal_claim: Some("sub".to_owned()), initiator_profile: None, reads_asks: false, source_namespaces: vec!["registry".to_owned()], @@ -406,6 +407,34 @@ fn project(version: &str) -> CaseworkProject { } } +fn multi_producer_project(version: &str) -> CaseworkProject { + let mut project = project(version); + project + .access_profiles + .iter_mut() + .find(|profile| profile.id == "producer") + .expect("primary producer profile") + .principal_claim = "client_id".to_owned(); + let mut other_producer_profile = profile("other-producer", CaseworkActsAs::Requester); + other_producer_profile.principal_claim = "client_id".to_owned(); + project.access_profiles.push(other_producer_profile); + + let mut other_policy = project.review_policies[0].clone(); + other_policy.id = "other-review".to_owned(); + project.review_policies.push(other_policy); + + let mut other_producer = project.trusted_producers[0].clone(); + other_producer.id = "other-registry".to_owned(); + other_producer.profile = "other-producer".to_owned(); + other_producer.subject = "other-registry-service".to_owned(); + other_producer.source_namespaces = vec!["other-registry".to_owned()]; + other_producer.review_policies = vec!["other-review".to_owned()]; + other_producer.completion = None; + project.trusted_producers.push(other_producer); + project.check().expect("multi-producer project"); + project +} + fn answer_project(completion: bool) -> CaseworkProject { let mut project = project("answer-1"); let kind = &mut project.review_policies[0]; @@ -493,6 +522,7 @@ fn request(subject_id: &str, requester_reference: &str) -> ReviewCreateRequest { requester_reference: requester_reference.to_owned(), initiator: Some(HumanIdentity { issuer: "https://issuer.test".to_owned(), + principal_claim: "sub".to_owned(), subject: "initiator".to_owned(), }), context: ReviewContext::Submitted { @@ -502,6 +532,68 @@ fn request(subject_id: &str, requester_reference: &str) -> ReviewCreateRequest { } } +fn pre_binding_policy_snapshot() -> ReviewPolicyClosure { + let project = project("1"); + let mut snapshot = project + .compile_policy("registry-correction") + .expect("compile the current policy before modelling its old wire shape"); + snapshot.dependencies.trusted_producers[0].trusted_initiator_principal_claim = None; + + // Reproduce the policy's canonical behavioural digest after removing the + // field that did not exist when this retained closure was admitted. This + // bypasses current authoring validation only in the fixture; production + // reads still verify the stored closure normally. + let mut policy = project.review_policies[0].clone(); + policy.label = None; + for stage in &mut policy.stages { + stage.label = None; + } + for outcome in &mut policy.outcomes { + outcome.label.clear(); + } + for rule in &mut policy.routing { + rule.label = None; + rule.because.clear(); + } + let mut dependencies = snapshot.dependencies.clone(); + for queue in &mut dependencies.queues { + queue.label.clear(); + } + for team in &mut dependencies.teams { + team.label.clear(); + } + for template in &mut dependencies.task_templates { + template.label.clear(); + } + for clock in &mut dependencies.clocks { + if let ClockPolicy::Stage { steps, .. } = clock { + for step in steps { + step.because.clear(); + } + } + } + for profile in &mut dependencies.access_profiles { + profile.label = None; + profile.description = None; + } + if let Some(provider) = &mut dependencies.context_provider { + provider.description = None; + } + let value = json!({ + "schema": "registry-casework-review-policy/v1", + "policy": policy, + "dependencies": dependencies, + }); + snapshot.identity.digest = ContentDigest::for_bytes( + ®istry_platform_canonical_json::canonicalize_json(&value) + .expect("canonicalize the old policy closure"), + ); + snapshot + .verify() + .expect("the pre-binding stored closure has a valid canonical digest"); + snapshot +} + fn bind_request( service: &CaseworkService, mut request: ReviewCreateRequest, @@ -2890,6 +2982,133 @@ async fn activation_preflight_counts_in_flight_reviews_a_package_would_strand() ); } +#[tokio::test] +async fn activation_preserves_the_claim_binding_of_retained_initiators() { + let fixture = fixture().await; + let cancelled = request( + "record-retained-initiator", + "producer-ref-retained-initiator", + ); + let request_id = fixture + .service_v1 + .create_review_request( + &fixture.producer, + cancelled.clone(), + "create-retained-initiator", + ) + .await + .expect("create review with an initiator") + .accepted + .request_id; + fixture + .service_v1 + .cancel_review_request( + &fixture.producer, + request_id, + ReviewCancelRequest { + subject: cancelled.subject, + reason: "no longer needed".to_owned(), + }, + "cancel-retained-initiator", + ) + .await + .expect("retain the cancelled review result"); + + let mut changed = project("2"); + for profile in &mut changed.access_profiles { + if profile.id != "producer" { + profile.principal_claim = "registry_principal".to_owned(); + } + } + changed.trusted_producers[0].trusted_initiator_principal_claim = + Some("registry_principal".to_owned()); + changed.check().expect("candidate project"); + assert_eq!( + registry_casework::stranded_pinned_work(&fixture.store, &changed, &[]) + .await + .expect("preflight changed initiator claim"), + vec![registry_casework::StrandedWork { + policy: "registry-correction".into(), + version: "1".into(), + reviews: 1, + reason: "the retained initiator principal claim changed".into(), + }] + ); + + let legacy_snapshot = serde_json::to_value(pre_binding_policy_snapshot()) + .expect("serialize a pre-binding retained policy"); + fixture + .database + .execute( + "UPDATE casework_review_requests + SET policy_snapshot=$2 + WHERE request_id=$1", + &[&request_id, &legacy_snapshot], + ) + .await + .expect("model a retained request admitted before the claim binding was stored"); + assert_eq!( + registry_casework::stranded_pinned_work(&fixture.store, &project("2"), &[]) + .await + .expect("preflight legacy retained initiator"), + vec![registry_casework::StrandedWork { + policy: "registry-correction".into(), + version: "1".into(), + reviews: 1, + reason: "the retained initiator principal claim cannot be established".into(), + }] + ); +} + +#[tokio::test] +async fn activation_uses_the_accepted_producers_pin_in_a_multi_producer_project() { + let fixture = fixture().await; + let retained_project = multi_producer_project("1"); + let service = CaseworkService::new( + fixture.store.clone(), + retained_project, + Vec::>::new(), + ) + .expect("multi-producer service"); + let cancelled = bind_request( + &service, + request( + "record-retained-multi-producer", + "producer-ref-retained-multi-producer", + ), + ); + let request_id = service + .create_review_request( + &fixture.producer, + cancelled.clone(), + "create-retained-multi-producer", + ) + .await + .expect("create review under the primary producer") + .accepted + .request_id; + service + .cancel_review_request( + &fixture.producer, + request_id, + ReviewCancelRequest { + subject: cancelled.subject, + reason: "no longer needed".to_owned(), + }, + "cancel-retained-multi-producer", + ) + .await + .expect("retain the cancelled review result"); + + assert!( + registry_casework::stranded_pinned_work(&fixture.store, &multi_producer_project("2"), &[],) + .await + .expect("preflight the retained multi-producer review") + .is_empty(), + "an unrelated producer profile is not a human claim" + ); +} + /// Removing a bound producer must not orphan its open review. The candidate /// becomes safe only once the producer has settled or cancelled that review. #[tokio::test] @@ -12257,12 +12476,25 @@ async fn an_initiator_is_refused_by_name_and_is_only_recorded_from_a_trusted_iss Err(ReviewRuntimeError::InitiatorRequired) )); + // The issuer alone cannot establish that the producer and Casework name + // the same person. Refuse a claim-name mismatch before storing the review. + let mut mismatched = request("record-wrong-initiator-claim", "producer-ref-wrong-claim"); + mismatched.initiator.as_mut().unwrap().principal_claim = "registry_principal".into(); + assert!(matches!( + fixture + .service_v1 + .create_review_request(&fixture.producer, mismatched, "create-wrong-claim") + .await, + Err(ReviewRuntimeError::Invalid) + )); + // A producer trusted with no initiator issuer submits only kinds that // exclude nobody. An initiator it names is not evidence of anyone, so it // is admitted without being recorded. let mut project = answer_project(false); project.review_policies[0].stages[0].exclude_initiator = false; project.trusted_producers[0].trusted_initiator_issuer = None; + project.trusted_producers[0].trusted_initiator_principal_claim = None; project.check().expect("untrusted initiator test project"); let service = CaseworkService::new( fixture.store.clone(), diff --git a/crates/registry-caseworkctl/src/identity.rs b/crates/registry-caseworkctl/src/identity.rs index ee5f1a7d42..9f11bcaa2b 100644 --- a/crates/registry-caseworkctl/src/identity.rs +++ b/crates/registry-caseworkctl/src/identity.rs @@ -469,7 +469,7 @@ mod tests { "command": "generate-identity-facts", "output": report["output"], "product": "casework", - "claims": 1, + "claims": 2, "accessProfiles": 4, "assertionIssuers": 0, }) diff --git a/crates/registry-caseworkctl/src/provider_add.rs b/crates/registry-caseworkctl/src/provider_add.rs index df6c547350..dd65e155bc 100644 --- a/crates/registry-caseworkctl/src/provider_add.rs +++ b/crates/registry-caseworkctl/src/provider_add.rs @@ -141,6 +141,9 @@ pub(crate) enum ProviderAddFailure { action_id: String, record_type: String, }, + AmbiguousHumanPrincipalClaim { + action_id: String, + }, ExistingMismatch { path: String, remedy: &'static str, @@ -221,6 +224,12 @@ impl ProviderAddFailure { "the Action's alternative profiles have different row boundary sets, so an explicit reviewer grant is required", "Author the reviewer's Proposal context and records.get permissions with the intended row boundaries, then run provider add again.", ), + Self::AmbiguousHumanPrincipalClaim { action_id } => ( + "casework.provider-add.human-principal-claim-ambiguous", + format!("actions[id={action_id}].execution.proposal.permissions"), + "the BReg explanation does not identify one principal claim for human reviewers", + "Set principalClaim on the human BReg access profile that grants get-review-context, or use one principalClaim across the BReg access profiles. Run provider add again.", + ), Self::ExistingMismatch { path, remedy } => ( "casework.provider-add.existing-project-mismatch", path.clone(), @@ -297,6 +306,7 @@ struct AddPlan { inputs_only_alternative: Option, service_profile: String, service_scopes: Vec, + human_principal_claim: String, } fn bregctl_version(bregctl: &Path) -> Result<()> { @@ -1197,6 +1207,20 @@ fn plan( .is_some_and(|profile| record_grants_ready(access, profile, &required_reads)) }); let human_permission = complete_human_permission.or_else(|| human_permissions.first().copied()); + let explicit_human_claim = human_permission + .and_then(|permission| permission["principalClaim"].as_str()) + .filter(|claim| !claim.is_empty()); + let sole_claim = access["claimContract"]["principalClaims"] + .as_array() + .filter(|claims| claims.len() == 1) + .and_then(|claims| claims[0].as_str()) + .filter(|claim| !claim.is_empty()); + let human_principal_claim = explicit_human_claim + .or(sole_claim) + .ok_or_else(|| ProviderAddFailure::AmbiguousHumanPrincipalClaim { + action_id: action_id.into(), + })? + .to_owned(); let human_profile = human_permission .and_then(|permission| permission["profileId"].as_str()) .map_or_else( @@ -1345,7 +1369,7 @@ fn plan( } let mut profile = json!({ "actorKind":"human", "requesterClients":human_clients, - "principalClaim":human_permission.and_then(|permission|permission["principalClaim"].as_str()).unwrap_or("registry_principal"), + "principalClaim":human_principal_claim, "requiredScopes":required_scopes, "permissions":permissions }); @@ -1363,7 +1387,7 @@ fn plan( changes.push(ProviderAddChange { path: format!("accessProfiles/{service_profile}"), explanation: "Lets one purpose-specific service client read Review status only for this Review authority.".into(), - yaml: json!({"accessProfiles":{(service_profile.clone()):{"actorKind":"service","principalClaim":"registry_principal","requesterClients":service_clients.clone(),"requiredScopes":["registry:proposal:review-status"],"requiredPurposes":["registry-review"],"permissions":{"proposals":[{"action":action_id,"operations":["get-review-status"],"reviewAuthority":authority_id}]}}}}), + yaml: json!({"accessProfiles":{(service_profile.clone()):{"actorKind":"service","principalClaim":human_principal_claim,"requesterClients":service_clients.clone(),"requiredScopes":["registry:proposal:review-status"],"requiredPurposes":["registry-review"],"permissions":{"proposals":[{"action":action_id,"operations":["get-review-status"],"reviewAuthority":authority_id}]}}}}), }); } let deployment = vec![ @@ -1422,6 +1446,7 @@ fn plan( inputs_only_alternative, service_profile, service_scopes, + human_principal_claim, }) } @@ -1479,6 +1504,14 @@ fn configure_project( let provider_id = local_id(action_id, "context"); let description = format!("context-providers/{provider_id}.json"); let mut document = crate::templates::approval_project(pattern)?; + for (_, profile) in document["accessProfiles"] + .as_object_mut() + .into_iter() + .flat_map(|profiles| profiles.iter_mut()) + .filter(|(id, _)| id.as_str() != "requester") + { + profile["principalClaim"] = json!(plan.human_principal_claim); + } document["project"]["id"] = json!(plan.policy_id); let template_policy = document["reviewPolicies"] .as_object_mut() @@ -1507,6 +1540,7 @@ fn configure_project( "issuer":"https://identity.example.test", "subject":format!("{producer_id}.example.test"), "trustedInitiatorIssuer":"https://identity.example.test", + "trustedInitiatorPrincipalClaim":plan.human_principal_claim, "sourceNamespaces":[plan.source_namespace], "reviewPolicies":[plan.policy_id], "retention":{"receiptRetentionDays":30} @@ -1711,6 +1745,15 @@ fn existing_agreement( } .into()); } + if producer["trustedInitiatorPrincipalClaim"].as_str() + != Some(plan.human_principal_claim.as_str()) + { + return Err(ProviderAddFailure::ExistingMismatch { + path: format!("/trustedProducers/{producer_id}/trustedInitiatorPrincipalClaim"), + remedy: PATTERN_REMEDY, + } + .into()); + } let expected = crate::templates::approval_project(pattern)?; let expected_policy = &expected["reviewPolicies"][pattern]; if comparable_review_stages(policy) != comparable_review_stages(expected_policy) { @@ -2247,7 +2290,10 @@ exit 1 fn explanations(action: Value, authorities: Value) -> (Value, Value, Value) { let proposals = json!({"actions":[action.clone()]}); let actions = json!({"registryId":"facility-registry","reviewAuthorities":authorities,"actions":[action],"recordTypes":[{"id":"facility","fields":[{"id":"address-line","encrypted":false}]}]}); - let access = json!({"recordTypes":[{"recordType":"facility","mutationPolicy":{},"profiles":[{"id":"direct-editor","operations":["patch"],"writableFields":["address-line","name"]}]}]}); + let access = json!({ + "claimContract":{"principalClaims":["registry_principal"]}, + "recordTypes":[{"recordType":"facility","mutationPolicy":{},"profiles":[{"id":"direct-editor","operations":["patch"],"writableFields":["address-line","name"]}]}] + }); (proposals, actions, access) } @@ -2789,6 +2835,46 @@ exit 1 ); } + #[test] + fn generated_breg_profiles_use_the_inferred_claim_contract() { + let context = json!({"id":"address-context","fields":{"facilityId":{"type":"input","input":"facility"},"changes":{"type":"changes","recordType":"facility","fields":["address-line"]}}}); + let permissions = json!([ + {"profileId":"human-reviewer","actorKind":"human","requesterClients":["review-ui"],"operations":["get-review-context"],"readableContextFields":["facilityId"],"requiredScopes":[],"requiredPurposes":[],"targets":[{"recordType":"facility","rowBoundaries":[]}]} + ]); + let review = json!({"type":"required","authority":"casework","source":"facility-registry","policy":{"id":"facility-address-review"}}); + let (proposals, actions, mut access) = explanations( + action(review, context, permissions), + json!([{"id":"casework","protocol":"id.registrystack.org/protocols/review/v1"}]), + ); + access["claimContract"] = json!({"principalClaims":["person_id"]}); + + let planned = plan( + "correct-address", + "single-reviewer-approval", + &proposals, + &actions, + &access, + ) + .unwrap(); + for path in [ + "accessProfiles/human-reviewer", + "accessProfiles/correct-address-review-status", + ] { + let profile = &planned + .changes + .iter() + .find(|change| change.path == path) + .unwrap_or_else(|| panic!("missing generated profile {path}")) + .yaml["accessProfiles"] + .as_object() + .unwrap() + .values() + .next() + .unwrap(); + assert_eq!(profile["principalClaim"], "person_id", "{path}"); + } + } + #[test] fn inputs_only_context_omits_empty_record_permissions() { let context = json!({"id":"address-context","fields":{"facilityId":{"type":"input","input":"facility"}}}); @@ -3038,6 +3124,35 @@ exit 1 assert_eq!(planned.service_profile, "status-reader"); } + #[test] + fn selected_human_permission_claim_wins_when_the_claim_contract_is_ambiguous() { + let (mut proposals, actions, mut access) = facility_explanations(); + access["claimContract"]["principalClaims"] = json!(["registry_principal", "reviewer_id"]); + let permission = proposals["actions"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|action| action["id"] == "correct-address") + .unwrap()["execution"]["proposal"]["permissions"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|permission| permission["actorKind"] == "human") + .unwrap(); + permission["principalClaim"] = json!("reviewer_id"); + + let planned = plan( + "correct-address", + "single-reviewer-approval", + &proposals, + &actions, + &access, + ) + .unwrap(); + + assert_eq!(planned.human_principal_claim, "reviewer_id"); + } + #[test] fn readiness_requires_one_human_profile_to_hold_context_and_record_grants() { let context = json!({"id":"address-context","fields":{"facilityId":{"type":"input","input":"facility"},"changes":{"type":"changes","recordType":"facility","fields":["address-line"]}}}); @@ -3631,6 +3746,14 @@ exit 1 authored["trustedProducers"]["correct-address-review-producer"]["sourceNamespaces"], json!(["facility-registry"]) ); + assert_eq!( + authored["accessProfiles"]["requester"]["principalClaim"], "sub", + "the generated requester service credential keeps its subject claim" + ); + assert_eq!( + authored["accessProfiles"]["staff"]["principalClaim"], "registry_principal", + "human profiles use the BReg human claim" + ); assert!( authored["trustedProducers"]["correct-address-review-producer"]["issuer"] .as_str() @@ -4241,6 +4364,60 @@ exit 1 assert!(!failed_project.exists()); } + #[cfg(unix)] + #[test] + fn ambiguous_human_claim_refuses_before_writing_a_project() { + let temporary = crate::canonical_tempdir(); + let breg_project = temporary.path().join("breg-project"); + fs::create_dir(&breg_project).unwrap(); + let (mut proposals, actions, mut access) = facility_explanations(); + access["claimContract"]["principalClaims"] = json!(["sub", "registry_principal"]); + let permission = proposals["actions"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|action| action["id"] == "correct-address") + .unwrap()["execution"]["proposal"]["permissions"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|permission| permission["actorKind"] == "human") + .unwrap(); + permission.as_object_mut().unwrap().remove("principalClaim"); + let fake_root = temporary.path().join("ambiguous-claim-fake"); + fs::create_dir(&fake_root).unwrap(); + let bregctl = fake_bregctl(&fake_root, &proposals, &actions, &access, true, None); + let project = temporary.path().join("ambiguous-claim-review"); + + let error = add( + &project, + &breg_project, + "correct-address", + "single-reviewer-approval", + None, + None, + &bregctl, + DEVELOPMENT_POSTURE, + ) + .unwrap_err(); + + let failure = error.downcast_ref::().unwrap(); + assert!(matches!( + failure, + ProviderAddFailure::AmbiguousHumanPrincipalClaim { .. } + )); + assert_eq!( + failure.diagnostic(), + ( + "casework.provider-add.human-principal-claim-ambiguous", + "actions[id=correct-address].execution.proposal.permissions".into(), + "the BReg explanation does not identify one principal claim for human reviewers", + "Set principalClaim on the human BReg access profile that grants get-review-context, or use one principalClaim across the BReg access profiles. Run provider add again.", + ) + ); + assert!(!project.exists()); + } + #[cfg(unix)] #[test] fn breg_explain_and_diff_preserve_peer_exit_classes() { diff --git a/crates/registry-caseworkctl/src/templates.rs b/crates/registry-caseworkctl/src/templates.rs index b8a446a325..6bf2475ba5 100644 --- a/crates/registry-caseworkctl/src/templates.rs +++ b/crates/registry-caseworkctl/src/templates.rs @@ -39,6 +39,7 @@ pub(crate) fn approval_project(pattern: &str) -> Result { "issuer":"https://identity.example.test", "subject":"review-producer.example.test", "trustedInitiatorIssuer":"https://identity.example.test", + "trustedInitiatorPrincipalClaim":"sub", "sourceNamespaces":["submitted"], "reviewPolicies":[pattern], "retention":{"receiptRetentionDays":30} diff --git a/crates/registry-caseworkctl/tests/fixtures/identity/facts-canonical-review.yaml b/crates/registry-caseworkctl/tests/fixtures/identity/facts-canonical-review.yaml index e048ca33c9..549677d10a 100644 --- a/crates/registry-caseworkctl/tests/fixtures/identity/facts-canonical-review.yaml +++ b/crates/registry-caseworkctl/tests/fixtures/identity/facts-canonical-review.yaml @@ -7,11 +7,14 @@ allowedClients: - casework-client claims: registry_actor_kind: string + registry_principal: string accessProfiles: - id: administrator scopes: - casework:admin actorKind: human + requiredClaims: + - registry_principal - id: requester scopes: - casework:request @@ -19,7 +22,11 @@ accessProfiles: scopes: - casework:staff actorKind: human + requiredClaims: + - registry_principal - id: supervisor scopes: - casework:supervisor actorKind: human + requiredClaims: + - registry_principal diff --git a/crates/registry-caseworkctl/tests/fixtures/identity/facts-task-authority.yaml b/crates/registry-caseworkctl/tests/fixtures/identity/facts-task-authority.yaml index ff238347ea..45255fe79a 100644 --- a/crates/registry-caseworkctl/tests/fixtures/identity/facts-task-authority.yaml +++ b/crates/registry-caseworkctl/tests/fixtures/identity/facts-task-authority.yaml @@ -9,11 +9,14 @@ allowedClients: - task-status claims: registry_actor_kind: string + registry_principal: string accessProfiles: - id: administrator scopes: - casework:admin actorKind: human + requiredClaims: + - registry_principal - id: requester scopes: - casework:request @@ -21,10 +24,14 @@ accessProfiles: scopes: - casework:staff actorKind: human + requiredClaims: + - registry_principal - id: supervisor scopes: - casework:supervisor actorKind: human + requiredClaims: + - registry_principal - id: task-status scopes: - casework:grants:status diff --git a/crates/registry-caseworkctl/tests/identity_facts.rs b/crates/registry-caseworkctl/tests/identity_facts.rs index 2fd944f5a7..094ff4995d 100644 --- a/crates/registry-caseworkctl/tests/identity_facts.rs +++ b/crates/registry-caseworkctl/tests/identity_facts.rs @@ -505,13 +505,15 @@ browserApps: origin: https://staff.casework.example redirectUris: [https://staff.casework.example/auth/callback] product: casework - tokenAttributes: [registry_actor_kind] + tokenAttributes: [registry_actor_kind, registry_principal] roles: [staff] users: - id: officer-one username: officer-one email: officer.one@agency.example passwordRef: secret:env/OFFICER_ONE_PASSWORD + claims: + registry_principal: officer-one roles: [staff] "; let service = GenerateSource { @@ -526,6 +528,7 @@ roles: casework: [requester] staff: actorKind: human + claims: [registry_principal] accessProfiles: casework: [staff] ", @@ -560,13 +563,15 @@ browserApps: origin: https://batch.casework.example redirectUris: [https://batch.casework.example/auth/callback] product: casework - tokenAttributes: [registry_actor_kind] + tokenAttributes: [registry_actor_kind, registry_principal] roles: [staff] users: - id: officer-one username: officer-one email: officer.one@agency.example passwordRef: secret:env/OFFICER_ONE_PASSWORD + claims: + registry_principal: officer-one roles: [staff] "; let error = identity_generate::generate(&GenerateInputs { diff --git a/crates/registry-caseworkctl/tests/provider_add.rs b/crates/registry-caseworkctl/tests/provider_add.rs index 4eafb63cab..8ad2e5aba8 100644 --- a/crates/registry-caseworkctl/tests/provider_add.rs +++ b/crates/registry-caseworkctl/tests/provider_add.rs @@ -226,6 +226,25 @@ fn real_bregctl_facility_generates_and_reruns_every_approval_pattern() { report["providerId"], "correct-address-context", "{pattern}: {report}" ); + let generated = read_yaml(&project.join("casework.yaml")); + assert_eq!( + generated["accessProfiles"]["requester"]["principalClaim"], "sub", + "{pattern}: the Casework service keeps its own subject claim" + ); + assert_eq!( + generated["trustedProducers"]["correct-address-review-producer"] + ["trustedInitiatorPrincipalClaim"], + "registry_principal", + "{pattern}: the producer pins the human claim inferred from BReg" + ); + for (id, profile) in generated["accessProfiles"].as_object().unwrap() { + if id != "requester" { + assert_eq!( + profile["principalClaim"], "registry_principal", + "{pattern}: human profile {id} uses the BReg claim" + ); + } + } for arguments in [ vec!["--format", "json", "check", project.to_str().unwrap()], diff --git a/crates/registry-coordinator/src/operations.rs b/crates/registry-coordinator/src/operations.rs index 8618487451..ac9a942828 100644 --- a/crates/registry-coordinator/src/operations.rs +++ b/crates/registry-coordinator/src/operations.rs @@ -313,6 +313,15 @@ const fn unkeyed_mutation(id: &'static str, product: &'static str) -> OperationD } } +const fn submit_review(id: &'static str) -> OperationDescriptor { + // The retained execution binding includes the initiator's claim name. + // A snapshot sealed for the previous binding cannot dispatch under it. + OperationDescriptor { + version: 2, + ..mutation(id, "casework", false, false) + } +} + const fn evaluation(id: &'static str, product: &'static str) -> OperationDescriptor { OperationDescriptor { id, @@ -346,7 +355,7 @@ macro_rules! operation_catalog { InvokeBregAction => "breg.invoke-action/v1", declared_mutation("breg", false, true), invoke_breg_action; ExternalGet => "external.get/v1", read("external-http"), external_get; EvaluateDecision => "evaluation.evaluate/v1", evaluation("evaluation"), evaluate; - SubmitReviewRequest => "casework.submit-review-request/v1", mutation("casework", false, false), submit_review_request; + SubmitReviewRequest => "casework.submit-review-request/v1", submit_review(), submit_review_request; CancelReviewRequest => "casework.cancel-review-request/v1", mutation("casework", false, false), cancel_review_request; PreviewAvailability => "scheduling.preview-availability/v1", read("scheduling"), preview_availability; ExternalCommand => "external.command/v1", declared_mutation("external-http", false, false), external_command; diff --git a/crates/registry-coordinator/tests/authoring.rs b/crates/registry-coordinator/tests/authoring.rs index 1244874aff..fda617aed6 100644 --- a/crates/registry-coordinator/tests/authoring.rs +++ b/crates/registry-coordinator/tests/authoring.rs @@ -575,6 +575,29 @@ fn canonical(value: &Value) -> String { String::from_utf8(registry_platform_canonical_json::canonicalize_json(value).unwrap()).unwrap() } +#[test] +fn snapshots_refuse_the_previous_review_submission_contract() { + let project = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/coordinator/examples/standalone-review"); + let current = Definition::load(&project).unwrap().snapshot().unwrap(); + assert!(Definition::from_snapshot(¤t).is_ok()); + + let mut prior: Value = serde_json::from_str(¤t).unwrap(); + let review_submission = prior["operationIdentities"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|identity| identity["id"] == "casework.submit-review-request/v1") + .unwrap(); + review_submission["version"] = json!(1); + + assert_eq!( + refused(Definition::from_snapshot(&canonical(&prior))).code, + "definition.abi", + ); + assert!(Definition::from_snapshot(&fixture().snapshot().unwrap()).is_ok()); +} + #[test] fn snapshots_refuse_missing_changed_extra_or_reordered_operation_contracts() { let original: Value = serde_json::from_str(&fixture().snapshot().unwrap()).unwrap(); diff --git a/crates/registry-linkml/README.md b/crates/registry-linkml/README.md index 94ce8a0f8e..b18c6e2e05 100644 --- a/crates/registry-linkml/README.md +++ b/crates/registry-linkml/README.md @@ -33,11 +33,11 @@ Keys whose absence would change a class's shape are refused rather than dropped: `attributes` and `union_of` on a class; `any_of`, `exactly_one_of`, `all_of`, and `none_of` on a slot; `inherits`, `include`, `minus`, and `reachable_from` on an enum. A bundle that relies on them fails to read -instead of reading wrong. A class's `slot_usage` is read only when it -documents a slot the class already carries (`description`, `comments`, -`examples`, `see_also`); the reader ignores those refinements, and refuses a -refinement with any other key or of a slot the class does not carry. Other -LinkML keys are ignored. +instead of reading wrong. For a slot the class already carries, `slot_usage` +can refine `annotations.sensitivity` for that class and its inheritors. The reader also accepts +documentation refinements in `description`, `comments`, `examples` and +`see_also`. It refuses other refinements and any refinement of a slot the +class does not carry. Other LinkML keys are ignored. ## The PublicSchema snapshot diff --git a/crates/registry-linkml/publicschema/PIN.yaml b/crates/registry-linkml/publicschema/PIN.yaml index 02a8183588..abd89c243f 100644 --- a/crates/registry-linkml/publicschema/PIN.yaml +++ b/crates/registry-linkml/publicschema/PIN.yaml @@ -1,7 +1,7 @@ # Written by sync-snapshot.sh; do not edit by hand. repository: https://github.com/PublicSchema/publicschema.org -commit: e5cfbbc0161e4d2c802d1acd752ec193253f7820 -commitDate: 2026-09-24 +commit: af10377ab57a416b07e93cc8277764895e974689 +commitDate: 2026-12-03 version: "0.3.0" license: CC-BY-4.0 licenseUrl: https://creativecommons.org/licenses/by/4.0/ diff --git a/crates/registry-linkml/publicschema/schema/agriculture_holdings.yaml b/crates/registry-linkml/publicschema/schema/agriculture_holdings.yaml index db94c52028..4ce6e80217 100644 --- a/crates/registry-linkml/publicschema/schema/agriculture_holdings.yaml +++ b/crates/registry-linkml/publicschema/schema/agriculture_holdings.yaml @@ -242,8 +242,8 @@ classes: OrganizationAgriculturalHolderRole: class_uri: publicschema:agri/OrganizationAgriculturalHolderRole title: Organization Agricultural Holder Role - description: An agricultural holder role borne by one organization with legal personality, such as - a company, cooperative or public body. It does not assert ownership, registration or benefit entitlement. + description: An agricultural holder role borne by one organization, such as a company, cooperative + or public body. It does not assert ownership, registration or benefit entitlement. slots: - holder_organization status: bibo:draft @@ -253,11 +253,9 @@ classes: source_domain: agri label_es: Rol de productor agropecuario (organización) label_fr: Rôle d'exploitant agricole (organisation) - description_es: Un rol de productor agropecuario asumido por una sola organización con personalidad - jurídica, como una empresa, una cooperativa o un organismo público. No afirma propiedad, registro + description_es: Un rol de productor agropecuario asumido por una sola organización, como una empresa, una cooperativa o un organismo público. No afirma propiedad, registro ni derecho a una prestación. - description_fr: Un rôle d'exploitant agricole assumé par une seule organisation dotée de la personnalité - juridique, telle qu'une entreprise, une coopérative ou un organisme public. Il n'affirme ni propriété, + description_fr: Un rôle d'exploitant agricole assumé par une seule organisation, telle qu'une entreprise, une coopérative ou un organisme public. Il n'affirme ni propriété, ni enregistrement, ni droit à une prestation. bibliography_refs: '["fao-wca-2020-vol1", "fao-wca-2030"]' is_a: AgriculturalHolderRole diff --git a/crates/registry-linkml/publicschema/schema/common.yaml b/crates/registry-linkml/publicschema/schema/common.yaml index e4776fa17b..6759632106 100644 --- a/crates/registry-linkml/publicschema/schema/common.yaml +++ b/crates/registry-linkml/publicschema/schema/common.yaml @@ -306,17 +306,18 @@ slots: issued_to: slot_uri: publicschema:issued_to title: Issued to - description: The party (person, household, or group) to whom the document, voucher, or credential - is issued. + description: The party (person, household, group, or organization) to whom the document, voucher, + or credential is issued. range: Party multivalued: false status: bibo:draft annotations: label_es: Emitido a label_fr: Délivré à - description_es: La parte (persona, hogar o grupo) a la que se emite el documento, vale o credencial. - description_fr: La partie (personne, ménage ou groupe) à laquelle le document, le bon ou l'attestation - est délivré. + description_es: La parte (persona, hogar, grupo u organización) a la que se emite el documento, + vale o credencial. + description_fr: La partie (personne, ménage, groupe ou organisation) à laquelle le document, le + bon ou l'attestation est délivré. convergence_json: '{"system_count": 0, "total_systems": 6}' issuing_authority: slot_uri: publicschema:issuing_authority @@ -657,7 +658,7 @@ slots: title: Subject description: 'The person or group that the profile or scoring event is about. Ranged at Party (not Agent) because Profiles observe receivers: persons and organised groups of persons (Household and - Family). Institutional actors (Organizations) are described through their own Organization records, + Family). Organizations are Parties too, but they are described through their own Organization records, not as subjects of a Profile.' range: Party multivalued: false @@ -667,10 +668,10 @@ slots: label_fr: Sujet description_es: 'La persona o grupo sobre el que trata el perfil o evento de puntuación. Tipado como Party (no Agent) porque los Profile observan receptores: personas y grupos organizados de - personas (Household, Family). Los actores institucionales (Organizations) se describen mediante + personas (Household, Family). Las Organizations también son Party, pero se describen mediante sus propios registros Organization, no como sujetos de un Profile.' description_fr: 'La personne ou le groupe sur lequel porte le profil ou l''événement de notation. Typé sur Party (et non Agent) parce que les Profiles observent des bénéficiaires : personnes et - groupes organisés de personnes (Household, Family). Les acteurs institutionnels (Organizations) - sont décrits par leurs propres enregistrements Organization, non comme sujets d''un Profile.' + groupes organisés de personnes (Household, Family). Les Organizations sont aussi des Party, mais + elles sont décrites par leurs propres enregistrements Organization, non comme sujets d''un Profile.' convergence_json: '{"system_count": 2, "total_systems": 3}' diff --git a/crates/registry-linkml/publicschema/schema/consent.yaml b/crates/registry-linkml/publicschema/schema/consent.yaml index 147f2a73e2..60dbca7807 100644 --- a/crates/registry-linkml/publicschema/schema/consent.yaml +++ b/crates/registry-linkml/publicschema/schema/consent.yaml @@ -272,9 +272,9 @@ slots: slot_uri: publicschema:data_subject title: Data subject description: 'The natural person (or occasionally group) whose personal data is being processed under - this record. Party is the abstract supertype covering Person and Group. Farm is excluded: farms - are not natural persons or legal beneficiaries under any data protection law. When ''data_subject'' - is a Group, ''delegation_type'' must not be ''self''.' + this record. Party is the abstract supertype covering Person, Group and Organization. When ''data_subject'' + is a Group, ''delegation_type'' must not be ''self''. An organization is a Party but is not a data + subject: data protection law protects natural persons.' range: Party multivalued: false status: bibo:draft @@ -284,14 +284,15 @@ slots: label_es: Persona interesada label_fr: Personne concernée description_es: 'La persona física (o en ocasiones el grupo) cuyos datos personales se tratan bajo - este registro. Party es el supertipo abstracto que abarca Person y Group. Farm está excluido: - las explotaciones agrícolas no son personas físicas ni beneficiarias legales bajo ninguna ley - de protección de datos. Cuando ''data_subject'' es un Group, ''delegation_type'' no debe ser ''self''.' + este registro. Party es el supertipo abstracto que abarca Person, Group y Organization. Cuando ''data_subject'' es un Group, ''delegation_type'' no debe ser ''self''. + Una organización es una Party pero no es una persona interesada: la legislación de protección + de datos protege a las personas físicas.' description_fr: 'La personne physique (ou parfois le groupe) dont les données personnelles sont - traitées dans le cadre de cet enregistrement. Party est le supertype abstrait couvrant Person - et Group. Farm est exclu : les exploitations agricoles ne sont pas des personnes physiques ni - des bénéficiaires légaux au titre d''aucune loi sur la protection des données. Lorsque ''data_subject'' - est un Group, ''delegation_type'' ne doit pas être ''self''.' + traitées dans le cadre de cet enregistrement. Party est le supertype abstrait couvrant Person, + Group et Organization. Lorsque ''data_subject'' + est un Group, ''delegation_type'' ne doit pas être ''self''. Une organisation est une Party mais + n''est pas une personne concernée : la législation sur la protection des données protège les personnes + physiques.' category: consent_parties immutable_after_status: given external_alignments_json: '[{"label": "has data subject", "match": "close", "note": "DPV models diff --git a/crates/registry-linkml/publicschema/schema/core.yaml b/crates/registry-linkml/publicschema/schema/core.yaml index 9545aeae5b..1d126b0eb5 100644 --- a/crates/registry-linkml/publicschema/schema/core.yaml +++ b/crates/registry-linkml/publicschema/schema/core.yaml @@ -142,9 +142,9 @@ classes: Party: class_uri: publicschema:Party title: Party - description: 'A person or organized group of persons that can be identified, enrolled in programs, - and receive benefits or services. Party is the shared supertype for Person and Group, enabling references - that accept either. + description: 'A person, an organized group of persons or an organization that can be identified, enrolled + in programs, and receive benefits or services. Party is the shared supertype for Person, Group and + Organization, enabling references that accept any of them. ' slots: @@ -157,16 +157,17 @@ classes: annotations: label_es: Parte label_fr: Partie - description_es: Una persona o grupo organizado de personas que puede ser identificado, inscrito - en programas y recibir beneficios o servicios. Party es el supertipo compartido para Person y - Group, que permite referencias que acepten cualquiera de los dos. - description_fr: Une personne ou un groupe organisé de personnes pouvant être identifié, inscrit - dans des programmes et recevoir des prestations ou des services. Party est le supertype commun - de Person et Group, permettant de les désigner indifféremment dans une référence. + description_es: Una persona, un grupo organizado de personas o una organización que puede ser + identificado, inscrito en programas y recibir beneficios o servicios. Party es el supertipo compartido + para Person, Group y Organization, que permite referencias que acepten cualquiera de ellos. + description_fr: Une personne, un groupe organisé de personnes ou une organisation pouvant être + identifié, inscrit dans des programmes et recevoir des prestations ou des services. Party est + le supertype commun de Person, Group et Organization, permettant de les désigner indifféremment + dans une référence. external_alignments_json: '[{"label": "Person (Core Person)", "match": "related", "note": "SEMIC - Core Person covers the individual human. Party is the beneficiary-side supertype for persons and - organized groups of persons (Household, Family) that can be enrolled in programs and receive - services. The broader SEMIC/foaf:Agent vocabulary for acting entities maps to our Agent concept, + Core Person covers the individual human. Party is the beneficiary-side supertype for persons, + organized groups of persons (Household, Family) and organizations that can be enrolled in programs + and receive services. The broader SEMIC/foaf:Agent vocabulary for acting entities maps to our Agent concept, not to Party.", "uri": "http://www.w3.org/ns/person#Person", "vocabulary": "Core Person", "vocabulary_id": "semic"}]' convergence_json: '{"notes": "Party is a PublicSchema abstract supertype; no mapped system exposes @@ -183,7 +184,8 @@ slots: slot_uri: publicschema:identity_documents title: Identity documents description: Identity documents held by this party, such as passports, national identity cards, civil - registration certificates, and program-issued beneficiary cards. + registration certificates, and program-issued beneficiary cards, or, for an organization, a certificate + of registration. range: IdentityDocument multivalued: true status: bibo:draft @@ -191,7 +193,9 @@ slots: label_es: Documentos de identidad label_fr: Documents d'identité description_es: Documentos de identidad que posee esta parte, como pasaportes, tarjetas de identidad - nacional, actas de registro civil y tarjetas de beneficiario emitidas por programas. + nacional, actas de registro civil y tarjetas de beneficiario emitidas por programas o, para una + organización, un certificado de inscripción registral. description_fr: Documents d'identité détenus par cette partie, tels que passeports, cartes d'identité - nationale, actes d'état civil et cartes de bénéficiaire délivrées par des programmes. + nationale, actes d'état civil et cartes de bénéficiaire délivrées par des programmes ou, pour + une organisation, un certificat d'immatriculation. category: identity diff --git a/crates/registry-linkml/publicschema/schema/document.yaml b/crates/registry-linkml/publicschema/schema/document.yaml index aac0acf442..a8c3739bdc 100644 --- a/crates/registry-linkml/publicschema/schema/document.yaml +++ b/crates/registry-linkml/publicschema/schema/document.yaml @@ -47,7 +47,7 @@ classes: class_uri: publicschema:IdentityDocument title: Identity Document description: 'A physical or digital document that asserts one or more identifiers about a party (person, - household, or group). Distinct from the identifier itself: the number on a passport is an Identifier; + household, group, or organization). Distinct from the identifier itself: the number on a passport is an Identifier; the passport book is an IdentityDocument. Documents have their own lifecycle (issue date, expiry, issuing authority) independent of the identifier value, and the same identifier may appear on successive documents. Distinct from Certificate (a re-issuable extract of a civil-status record under CIEC @@ -71,14 +71,14 @@ classes: label_es: Documento de identidad label_fr: Document d'identité description_es: 'Un documento físico o digital que acredita uno o más identificadores sobre una - parte (persona, hogar o grupo). Distinto del identificador en sí: el número del pasaporte es un + parte (persona, hogar, grupo u organización). Distinto del identificador en sí: el número del pasaporte es un Identifier; la libreta del pasaporte es un IdentityDocument. Los documentos tienen su propio ciclo de vida (fecha de emisión, expiración, autoridad emisora) independiente del valor del identificador, y el mismo identificador puede aparecer en documentos sucesivos. Distinto de Certificate (un extracto reeditable de un acta de estado civil bajo las convenciones CIEC) y de IdentityCredential (la envoltura de credencial verificable que puede acreditar un IdentityDocument en forma digital).' description_fr: 'Un document physique ou numérique qui atteste d''un ou plusieurs identifiants concernant - une partie (personne, ménage ou groupe). Distinct de l''identifiant lui-même: le numéro sur un + une partie (personne, ménage, groupe ou organisation). Distinct de l''identifiant lui-même: le numéro sur un passeport est un Identifier; le livret du passeport est un IdentityDocument. Les documents ont leur propre cycle de vie (date de délivrance, expiration, autorité émettrice) indépendamment de la valeur de l''identifiant, et le même identifiant peut apparaître sur des documents successifs. diff --git a/crates/registry-linkml/publicschema/schema/identity.yaml b/crates/registry-linkml/publicschema/schema/identity.yaml index 5f4815d025..0896bb3822 100644 --- a/crates/registry-linkml/publicschema/schema/identity.yaml +++ b/crates/registry-linkml/publicschema/schema/identity.yaml @@ -102,10 +102,11 @@ classes: Person: class_uri: publicschema:Person title: Person - description: 'The unique individual human being who is a subject of record within a social protection - system. Person is the persistent, indivisible unit of identity in registries; operational statuses + description: 'The unique individual human being who is a subject of record. Person is the persistent, indivisible unit of identity in registries; operational statuses such as Registrant, Applicant, or Beneficiary are transient roles defined by the person''s relationship - to a specific Program, not properties of the person themselves. + to a specific Program, not properties of the person themselves. A person who runs a business that + the register of its jurisdiction does not treat as a distinct body, such as many sole traders, remains + a Person; the business is an Organization only where the register treats it as one. ' is_a: Party @@ -153,14 +154,17 @@ classes: annotations: label_es: Persona label_fr: Personne - description_es: El individuo único que es sujeto de registro en un sistema de protección social. - La persona es la unidad indivisible y persistente de identidad en los registros; los estados operacionales + description_es: El individuo único que es sujeto de registro. La persona es la unidad indivisible y persistente de identidad en los registros; los estados operacionales como inscrito, solicitante o beneficiario son roles transitorios definidos por la relación de - la persona con un programa específico. - description_fr: L'individu unique qui fait l'objet d'un enregistrement dans un système de protection - sociale. La personne est l'unité indivisible et persistante d'identité dans les registres. Les + la persona con un programa específico. Una persona que explota un negocio que el registro de su + jurisdicción no trata como un organismo distinto, como muchos comerciantes individuales, sigue + siendo una Person; el negocio es una Organization solo cuando el registro lo trata como tal. + description_fr: L'individu unique qui fait l'objet d'un enregistrement. La personne est l'unité indivisible et persistante d'identité dans les registres. Les statuts opérationnels tels que Registrant, demandeur ou bénéficiaire sont des rôles transitoires - définis par la relation de la personne à un programme spécifique. + définis par la relation de la personne à un programme spécifique. Une personne qui exploite une + activité que le registre de sa juridiction ne traite pas comme un organisme distinct, comme de + nombreux entrepreneurs individuels, reste une Person ; l'activité n'est une Organization que lorsque + le registre la traite comme telle. featured: true external_alignments_json: '[{"label": "Person", "match": "exact", "uri": "http://www.w3.org/ns/person#Person", "vocabulary": "Core Person", "vocabulary_id": "semic"}, {"label": "Person", "match": "close", @@ -463,21 +467,28 @@ classes: Organization: class_uri: publicschema:Organization title: Organization - description: 'A legally or administratively identifiable body that can act within a public delivery - process: a government agency, ministry, NGO, UN agency, statistical office, health facility, civil - registration office, court, or standards publisher. Organizations are the institutional actors that - administer instruments, publish methodologies, evaluate submissions, issue certificates, and operate - programs. An Organization''s location refers to its own registered or primary site, not to the place - where an action it performed happened. Event-level place remains a property of the event record. + description: 'A legally or administratively identifiable body, public or private, for profit or not, + such as a company, cooperative, association, non-governmental organization, government agency, ministry, + UN agency, health facility, court or standards publisher. An organization can act in a process, for + example by administering a program, deciding a case or issuing a certificate, and it can also receive + services or benefits, for example as an enrolled beneficiary or a licence holder. An Organization''s + location refers to its own registered or primary site, not to the place where an action it performed + happened. A sole proprietorship is recorded as an Organization where the register of its jurisdiction + treats the business as a body distinct from the person who runs it; otherwise it is recorded on the + Person, and an application profile states which pattern applies. ' is_a: Agent + mixins: + - Party slots: - name - identifiers - location - legal_form + - economic_activities - formation_date + - dissolution_date status: bibo:status/forthcoming exact_mappings: - foaf:Organization @@ -492,22 +503,28 @@ classes: featured: true label_es: Organización label_fr: Organisation - description_es: 'Un organismo identificable jurídica o administrativamente capaz de actuar en un - proceso de prestación pública: una agencia gubernamental, un ministerio, una ONG, una agencia - de las Naciones Unidas, una oficina estadística, un establecimiento de salud, una oficina de registro - civil, un tribunal o un editor de normas. Las organizaciones son los actores institucionales que - administran instrumentos, publican metodologías, evalúan expedientes, emiten certificados y operan - programas. La ubicación de una Organization se refiere a su propio sitio registrado o principal, - no al lugar donde ocurrió una acción que realizó. La ubicación a nivel de evento sigue siendo - una propiedad del registro del evento.' - description_fr: 'Un organisme identifiable juridiquement ou administrativement capable d''agir dans - un processus de prestation publique : agence gouvernementale, ministère, ONG, agence des Nations - unies, office statistique, établissement de santé, office d''état civil, tribunal ou éditeur de - normes. Les organisations sont les acteurs institutionnels qui administrent des instruments, publient - des méthodologies, évaluent des dossiers, délivrent des certificats et opèrent des programmes. - La localisation d''une Organization désigne son propre site enregistré ou principal, et non le - lieu où une action qu''elle a accomplie s''est déroulée. La localisation d''un événement reste - une propriété du registre de l''événement.' + description_es: 'Un organismo identificable jurídica o administrativamente, público o privado, con + o sin fines de lucro, como una empresa, una cooperativa, una asociación, una organización no gubernamental, + una agencia gubernamental, un ministerio, una agencia de las Naciones Unidas, un establecimiento + de salud, un tribunal o un editor de normas. Una organización puede actuar en un proceso, por + ejemplo administrando un programa, resolviendo un expediente o emitiendo un certificado, y también + puede recibir servicios o prestaciones, por ejemplo como beneficiaria inscrita o titular de una + licencia. La ubicación de una Organization se refiere a su propio sitio registrado o principal, + no al lugar donde ocurrió una acción que realizó. Una empresa individual se registra como Organization + cuando el registro de su jurisdicción trata el negocio como un organismo distinto de la persona + que lo explota; de lo contrario se registra en la Person, y un perfil de aplicación indica qué + modelo se aplica.' + description_fr: 'Un organisme identifiable juridiquement ou administrativement, public ou privé, + à but lucratif ou non, par exemple une entreprise, une coopérative, une association, une organisation + non gouvernementale, une agence gouvernementale, un ministère, une agence des Nations unies, un + établissement de santé, un tribunal ou un éditeur de normes. Une organisation peut agir dans un + processus, par exemple en administrant un programme, en statuant sur un dossier ou en délivrant + un certificat, et elle peut aussi recevoir des services ou des prestations, par exemple comme + bénéficiaire inscrite ou titulaire d''une licence. La localisation d''une Organization désigne + son propre site enregistré ou principal, et non le lieu où une action qu''elle a accomplie s''est + déroulée. Une entreprise individuelle est enregistrée comme Organization lorsque le registre de + sa juridiction traite l''entreprise comme un organisme distinct de la personne qui l''exploite ; + sinon, elle est enregistrée sur la Person, et un profil d''application précise quel modèle s''applique.' external_alignments_json: '[{"label": "Organization", "match": "exact", "note": "foaf:Organization is the direct equivalent: a kind of agent corresponding to social institutions such as companies, societies, and so on.", "uri": "http://xmlns.com/foaf/0.1/Organization", "vocabulary": "FOAF", @@ -536,12 +553,14 @@ classes: In practice, organizations appear as free-text publisher names on instruments, as implicit issuers on certificates, and as unmodelled administrative context around program operations. Standards bodies are consistent: FOAF, schema.org, PROV-O, and FHIR all have a named Organization concept. - Minimum property set (name, identifiers, location) is pragmatic; richer modelling (parent_organization, - legal_form, jurisdiction, contact points, multi-site locations) is deferred to a later iteration.\n", + ADR-008 set a pragmatic minimum property set (name, identifiers, location). ADR-025 added legal_form + and formation_date, and records parent organizations and contact points as InstitutionalRelationship + and ContactPoint records; ADR-028 added economic_activities and dissolution_date. Jurisdiction + and multi-site locations remain deferred.\n", "system_count": 0, "total_systems": 6}' property_groups_json: '[{"category": "identity", "properties": ["name", "identifiers"]}, {"category": "location", "properties": ["location"]}, {"category": "administrative", "properties": ["legal_form", - "formation_date"]}]' + "economic_activities", "formation_date", "dissolution_date"]}]' bibliography_refs: '["fhir-r4", "foaf", "schema-org", "semic-cpov", "uk-companies-house-api", "w3c-prov-o", "w3c-regorg"]' RegistrationOffice: @@ -1203,6 +1222,30 @@ slots: category: demographics sensitivity: sensitive bibliography_refs: '["egriss-iris"]' + dissolution_date: + slot_uri: publicschema:dissolution_date + title: Dissolution date + description: The date on which the organization ceased to exist or was removed from the register, such + as by dissolution, liquidation or striking off. It is the counterpart of the formation date. + range: date + multivalued: false + status: bibo:draft + close_mappings: + - https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/resources/companyprofile?v=latest + annotations: + label_es: Fecha de disolución + label_fr: Date de dissolution + description_es: La fecha en que la organización dejó de existir o fue dada de baja del registro, + por ejemplo por disolución, liquidación o cancelación de oficio. Es la contrapartida de la fecha + de formación. + description_fr: La date à laquelle l'organisation a cessé d'exister ou a été radiée du registre, + par exemple par dissolution, liquidation ou radiation d'office. Elle est le pendant de la date + de formation. + category: administrative + external_alignments_json: '[{"label": "date_of_cessation", "match": "close", "note": "Companies House + records the date a company was converted or closed, dissolved or removed.", "uri": "https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/resources/companyprofile?v=latest", + "vocabulary": "Companies House Public Data API", "vocabulary_id": "uk-companies-house-api"}]' + bibliography_refs: '["uk-companies-house-api"]' domicile: slot_uri: publicschema:domicile title: Domicile @@ -1244,6 +1287,37 @@ slots: convergence_json: '{"notes": "Proxy means testing input, not a standard registry field.", "system_count": 0, "total_systems": 4}' bibliography_refs: '["un-census-rev3"]' + economic_activities: + slot_uri: publicschema:economic_activities + title: Economic activities + description: The economic activities the organization carries out, each coded in a classification of + economic activities. ISIC is the international reference; a register may use NACE, NAICS or a national + adaptation. The order of the values does not mark a principal activity. + range: CodedValue + multivalued: true + status: bibo:draft + close_mappings: + - http://www.w3.org/ns/regorg#orgActivity + - https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/resources/companyprofile?v=latest + annotations: + label_es: Actividades económicas + label_fr: Activités économiques + description_es: Las actividades económicas que ejerce la organización, cada una codificada en + una clasificación de actividades económicas. La CIIU es la referencia internacional; un registro + puede usar la NACE, el SCIAN o una adaptación nacional. El orden de los valores no indica una + actividad principal. + description_fr: Les activités économiques exercées par l'organisation, chacune codée dans une + classification des activités économiques. La CITI est la référence internationale ; un registre + peut utiliser la NACE, le SCIAN ou une adaptation nationale. L'ordre des valeurs n'indique pas + d'activité principale. + category: classification + external_alignments_json: '[{"label": "orgActivity", "match": "close", "note": "RegOrg records the + activities of a registered organization as concepts from a controlled vocabulary, many of which + map to ISIC.", "uri": "http://www.w3.org/ns/regorg#orgActivity", "vocabulary": "Registered Organization + Vocabulary", "vocabulary_id": "w3c-regorg"}, {"label": "sic_codes", "match": "close", "note": "Companies + House lists the UK SIC codes of a company.", "uri": "https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/resources/companyprofile?v=latest", + "vocabulary": "Companies House Public Data API", "vocabulary_id": "uk-companies-house-api"}]' + bibliography_refs: '["uk-companies-house-api", "unsd-isic-rev4", "w3c-regorg"]' education_level: slot_uri: publicschema:education_level title: Education level diff --git a/crates/registry-linkml/publicschema/schema/misc.yaml b/crates/registry-linkml/publicschema/schema/misc.yaml index 6e1a4c6115..428dfc461f 100644 --- a/crates/registry-linkml/publicschema/schema/misc.yaml +++ b/crates/registry-linkml/publicschema/schema/misc.yaml @@ -1377,8 +1377,8 @@ slots: recipient: slot_uri: publicschema:recipient title: Recipient - description: The person or group that received or is intended to receive the payment. The recipient - may differ from the enrolled beneficiary, for example when a guardian, payment proxy, or survivor + description: The person, group or organization that received or is intended to receive the payment. + The recipient may differ from the enrolled beneficiary, for example when a guardian, payment proxy, or survivor collects on behalf of the beneficiary. range: Party multivalued: false @@ -1386,10 +1386,12 @@ slots: annotations: label_es: Beneficiario label_fr: Destinataire du paiement - description_es: La persona o el grupo que recibió o está destinado a recibir el pago. El destinatario + description_es: La persona, el grupo o la organización que recibió o está destinado a recibir el + pago. El destinatario puede diferir del beneficiario inscrito, por ejemplo cuando un tutor, apoderado de pago o sobreviviente cobra en nombre del beneficiario. - description_fr: La personne ou le groupe qui a reçu ou est destiné à recevoir le paiement. Le destinataire + description_fr: La personne, le groupe ou l'organisation qui a reçu ou est destiné à recevoir le + paiement. Le destinataire peut différer du bénéficiaire inscrit, par exemple lorsqu'un tuteur, un mandataire de paiement ou un survivant perçoit au nom du bénéficiaire. convergence_json: '{"system_count": 2, "total_systems": 6}' @@ -1435,15 +1437,18 @@ slots: redeemable_by: slot_uri: publicschema:redeemable_by title: Redeemable by - description: The person or group authorized to redeem this voucher on behalf of the beneficiary. + description: The person, group or organization authorized to redeem this voucher on behalf of the + beneficiary. range: Party multivalued: true status: bibo:draft annotations: label_es: Canjeable por label_fr: Échangeable par - description_es: La persona o grupo autorizado para canjear este vale en nombre del beneficiario. - description_fr: La personne ou le groupe autorisé à échanger ce bon au nom du bénéficiaire. + description_es: La persona, grupo u organización autorizado para canjear este vale en nombre del + beneficiario. + description_fr: La personne, le groupe ou l'organisation autorisé à échanger ce bon au nom du + bénéficiaire. convergence_json: '{"system_count": 0, "total_systems": 6}' redeemed_by: slot_uri: publicschema:redeemed_by diff --git a/crates/registry-linkml/publicschema/schema/program.yaml b/crates/registry-linkml/publicschema/schema/program.yaml index 447b564e47..9481468f2b 100644 --- a/crates/registry-linkml/publicschema/schema/program.yaml +++ b/crates/registry-linkml/publicschema/schema/program.yaml @@ -326,7 +326,7 @@ slots: beneficiary: slot_uri: publicschema:beneficiary title: Beneficiary - description: The person or group enrolled in the program. + description: The person, group or organization enrolled in the program. range: Party multivalued: false status: bibo:status/forthcoming @@ -334,8 +334,8 @@ slots: label_es: Beneficiario label_fr: Bénéficiaire domain_override: "null" - description_es: La persona o grupo inscrito en el programa. - description_fr: La personne ou le groupe inscrit dans le programme. + description_es: La persona, grupo u organización inscrito en el programa. + description_fr: La personne, le groupe ou l'organisation inscrit dans le programme. convergence_json: '{"system_count": 5, "total_systems": 6}' benefit_description: slot_uri: publicschema:sp/benefit_description diff --git a/crates/registry-linkml/publicschema/schema/public_services.yaml b/crates/registry-linkml/publicschema/schema/public_services.yaml index e6c06be87e..8803c25c22 100644 --- a/crates/registry-linkml/publicschema/schema/public_services.yaml +++ b/crates/registry-linkml/publicschema/schema/public_services.yaml @@ -72,6 +72,10 @@ classes: - request_submission_date - evidence_assertions - recorded_at + slot_usage: + subject_uri: + annotations: + sensitivity: sensitive status: bibo:draft annotations: label_es: Solicitud de servicio @@ -112,6 +116,10 @@ classes: - resolves_appeal - evidence_assertions - recorded_at + slot_usage: + subject_uri: + annotations: + sensitivity: sensitive status: bibo:draft annotations: label_es: Decisión administrativa diff --git a/crates/registry-linkml/publicschema/starters/household.yaml b/crates/registry-linkml/publicschema/starters/household.yaml index 95af7a314c..587c57882c 100644 --- a/crates/registry-linkml/publicschema/starters/household.yaml +++ b/crates/registry-linkml/publicschema/starters/household.yaml @@ -13,7 +13,7 @@ apiVersion: id.registrystack.org/formats/breg/model-selection/v1alpha1 kind: BRegModelSelection model: publicschema modelVersion: "0.3.0" -modelRevision: "e5cfbbc0161e4d2c802d1acd752ec193253f7820" +modelRevision: "af10377ab57a416b07e93cc8277764895e974689" registry: id: household-registry title: Household Registry diff --git a/crates/registry-linkml/src/model.rs b/crates/registry-linkml/src/model.rs index c398d7b389..dc5c882c6f 100644 --- a/crates/registry-linkml/src/model.rs +++ b/crates/registry-linkml/src/model.rs @@ -49,6 +49,8 @@ pub struct ClassDef { /// The slots the class declares itself, in declaration order. Inherited /// slots are not listed here; see [`Model::induced_slots`]. pub slots: Vec, + /// Sensitivity refinements this class declares for slots it carries. + pub slot_sensitivity: BTreeMap, /// Scalar annotations, with booleans and numbers rendered as text. pub annotations: BTreeMap, /// The `name` of the schema file that defined the class. diff --git a/crates/registry-linkml/src/publicschema.rs b/crates/registry-linkml/src/publicschema.rs index 7e54230499..0230f1f80a 100644 --- a/crates/registry-linkml/src/publicschema.rs +++ b/crates/registry-linkml/src/publicschema.rs @@ -12,7 +12,7 @@ //! it assigns, and the property groups it presents a class by. They are //! observations about the published model, not registry semantics. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use registry_platform_yaml::{EnvelopeRule, Expect, FormatSpec, Reader, Report}; use serde::Deserialize; @@ -407,7 +407,44 @@ pub fn property_groups(class: &ClassDef) -> Result, Conventio /// The sensitivity PublicSchema assigns to a property, when it assigns one. pub fn sensitivity(slot: &SlotDef) -> Result, ConventionError> { - match slot.annotations.get("sensitivity").map(String::as_str) { + parse_sensitivity( + slot, + slot.annotations.get("sensitivity").map(String::as_str), + ) +} + +/// Read class usage before inherited usage and the shared slot annotation. +pub fn sensitivity_in_class( + model: &Model, + class: &ClassDef, + slot: &SlotDef, +) -> Result, ConventionError> { + if let Some(value) = class.slot_sensitivity.get(&slot.name) { + return parse_sensitivity(slot, Some(value.as_str())); + } + // Follow LinkML's class-ancestor order: discover direct mixins and the + // superclass before walking their parents, with the last discovered first. + let mut seen = BTreeSet::from([class.name.as_str()]); + let mut pending = vec![class]; + while let Some(context) = pending.pop() { + for name in context.mixins.iter().chain(&context.is_a) { + if seen.insert(name.as_str()) { + let ancestor = &model.classes[name]; + if let Some(value) = ancestor.slot_sensitivity.get(&slot.name) { + return parse_sensitivity(slot, Some(value.as_str())); + } + pending.push(ancestor); + } + } + } + sensitivity(slot) +} + +fn parse_sensitivity( + slot: &SlotDef, + value: Option<&str>, +) -> Result, ConventionError> { + match value { None => Ok(None), Some("sensitive") => Ok(Some(Sensitivity::Sensitive)), Some("restricted") => Ok(Some(Sensitivity::Restricted)), @@ -454,6 +491,7 @@ mod tests { mixins: Vec::new(), is_abstract: false, slots: Vec::new(), + slot_sensitivity: BTreeMap::new(), annotations: annotations .iter() .map(|(key, value)| ((*key).to_owned(), (*value).to_owned())) diff --git a/crates/registry-linkml/src/reader.rs b/crates/registry-linkml/src/reader.rs index a9525d0879..9fc48beed5 100644 --- a/crates/registry-linkml/src/reader.rs +++ b/crates/registry-linkml/src/reader.rs @@ -51,9 +51,8 @@ const ABSOLUTE_URI_SCHEMES: &[&str] = &["urn", "did", "mailto", "tag", "data", " /// class's induced shape. const UNSUPPORTED_CLASS_KEYS: &[&str] = &["attributes", "union_of"]; -/// The keys a `slot_usage` refinement may carry. They only document the slot -/// in the context of one class, so the reader can ignore them without changing -/// the class's shape; any other key is refused. +/// Documentation refinements can be ignored without changing the slot shape. +/// The only annotation refinement the reader consumes is sensitivity. const DOCUMENTATION_SLOT_USAGE_KEYS: &[&str] = &["description", "comments", "examples", "see_also"]; /// Slot keys the reader refuses because ignoring them would change the @@ -185,7 +184,6 @@ pub fn read_bundle(files: &[(&str, &str)]) -> Result { .unwrap_or_else(|| "string".to_owned()); for (name, class) in &schema.classes { refuse_unsupported(file, "class", name, &class.rest, UNSUPPORTED_CLASS_KEYS)?; - refuse_shape_changing_slot_usage(file, name, &class.slot_usage)?; let definition = ClassDef { name: name.clone(), uri: definition_uri( @@ -201,6 +199,7 @@ pub fn read_bundle(files: &[(&str, &str)]) -> Result { mixins: class.mixins.clone(), is_abstract: class.is_abstract, slots: class.slots.clone(), + slot_sensitivity: read_slot_sensitivity(file, name, &class.slot_usage)?, annotations: scalar_annotations(file, "class", name, &class.annotations)?, schema: schema_name.clone(), }; @@ -451,24 +450,44 @@ impl HasSchema for EnumDef { } } -fn refuse_shape_changing_slot_usage( +fn read_slot_sensitivity( file: &str, owner: &str, - slot_usage: &BTreeMap>>, -) -> Result<(), ReadError> { - for (slot, refinement) in slot_usage { - for key in refinement.iter().flat_map(BTreeMap::keys) { - if !DOCUMENTATION_SLOT_USAGE_KEYS.contains(&key.as_str()) { - return Err(ReadError::Unsupported { - file: file.to_owned(), - kind: "class", - owner: owner.to_owned(), - key: format!("slot_usage.{slot}.{key}"), - }); - } + slot_usage: &BTreeMap>, +) -> Result, ReadError> { + let mut sensitivities = BTreeMap::new(); + for (slot, usage) in slot_usage { + let Some(usage) = usage else { continue }; + let unsupported = |key| ReadError::Unsupported { + file: file.to_owned(), + kind: "class", + owner: owner.to_owned(), + key, + }; + if let Some(key) = usage + .rest + .keys() + .find(|key| !DOCUMENTATION_SLOT_USAGE_KEYS.contains(&key.as_str())) + { + return Err(unsupported(format!("slot_usage.{slot}.{key}"))); + } + if let Some(key) = usage + .annotations + .keys() + .find(|key| key.as_str() != "sensitivity") + { + return Err(unsupported(format!("slot_usage.{slot}.annotations.{key}"))); + } + if let Some(value) = usage.annotations.get("sensitivity") { + let Some(value) = value.as_str() else { + return Err(unsupported(format!( + "slot_usage.{slot}.annotations.sensitivity" + ))); + }; + sensitivities.insert(slot.clone(), value.to_owned()); } } - Ok(()) + Ok(sensitivities) } fn refuse_unsupported( @@ -618,7 +637,15 @@ struct RawClass { #[serde(default)] slots: Vec, #[serde(default)] - slot_usage: BTreeMap>>, + slot_usage: BTreeMap>, + #[serde(default)] + annotations: BTreeMap, + #[serde(flatten)] + rest: BTreeMap, +} + +#[derive(Debug, Deserialize)] +struct RawSlotUsage { #[serde(default)] annotations: BTreeMap, #[serde(flatten)] @@ -1095,6 +1122,58 @@ slots: assert_eq!(slots[0].description, None); } + #[test] + fn slot_usage_sensitivity_respects_class_context_and_inheritance() { + let source = r#"name: r +default_prefix: ex +prefixes: {ex: https://example.org/} +classes: + Base: + slots: [subject] + RestrictedContext: + is_a: Base + slot_usage: + subject: + annotations: {sensitivity: sensitive} + InheritedContext: + is_a: RestrictedContext + MixedContext: + mixins: [RestrictedContext] + NarrowerContext: + is_a: RestrictedContext + slot_usage: + subject: + annotations: {sensitivity: restricted} + OtherContext: + is_a: Base +slots: + subject: + range: uri +"#; + let model = read_bundle(&[("r.yaml", source)]).expect("read sensitivity metadata"); + let slots = model.induced_slots("RestrictedContext").unwrap(); + let slot = slots[0]; + assert_eq!(slot.uri, "https://example.org/subject"); + assert_eq!(slot.range, Range::Type("uri".into())); + assert_eq!(crate::publicschema::sensitivity(slot).unwrap(), None); + use crate::publicschema::{sensitivity_in_class, Sensitivity}; + for class in ["RestrictedContext", "InheritedContext", "MixedContext"] { + assert_eq!( + sensitivity_in_class(&model, &model.classes[class], slot).unwrap(), + Some(Sensitivity::Sensitive), + "{class}", + ); + } + assert_eq!( + sensitivity_in_class(&model, &model.classes["NarrowerContext"], slot).unwrap(), + Some(Sensitivity::Restricted), + ); + assert_eq!( + sensitivity_in_class(&model, &model.classes["OtherContext"], slot).unwrap(), + None, + ); + } + #[test] fn shape_changing_slot_usage_is_refused_rather_than_dropped() { let ranged = "name: r\ndefault_prefix: ex\nprefixes: {ex: https://example.org/}\nclasses:\n Thing:\n slots: [subject]\n slot_usage:\n subject:\n description: Narrower.\n required: true\nslots:\n subject: {}\n"; diff --git a/crates/registry-linkml/tests/snapshot.rs b/crates/registry-linkml/tests/snapshot.rs index 3854f503a1..85eb9ae01a 100644 --- a/crates/registry-linkml/tests/snapshot.rs +++ b/crates/registry-linkml/tests/snapshot.rs @@ -42,7 +42,7 @@ fn the_pin_matches_the_embedded_root_schema() { fn the_snapshot_has_the_pinned_shape() { let model = publicschema::model().expect("the snapshot reads"); assert_eq!(model.classes.len(), 146); - assert_eq!(model.slots.len(), 633); + assert_eq!(model.slots.len(), 635); assert_eq!(model.enums.len(), 132); let values: usize = model.enums.values().map(|e| e.values.len()).sum(); assert_eq!(values, 10_301); @@ -176,6 +176,23 @@ fn slot_conventions_read_from_the_snapshot() { assert_eq!(restricted, 3); } +#[test] +fn public_service_subject_sensitivity_is_declared_by_each_class() { + let model = publicschema::model().expect("the snapshot reads"); + let subject = &model.slots["subject_uri"]; + assert_eq!(sensitivity(subject).unwrap(), None); + for concept in ["ServiceApplication", "AdministrativeDecision"] { + let slots = model.induced_slots(concept).expect("the class resolves"); + assert!(slots.iter().any(|slot| slot.name == subject.name)); + assert_eq!( + publicschema::sensitivity_in_class(&model, &model.classes[concept], subject) + .expect("the contextual sensitivity is valid"), + Some(Sensitivity::Sensitive), + "{concept}.subject_uri", + ); + } +} + #[test] fn inline_value_classes_and_list_properties_are_explicit_in_the_snapshot() { let model = publicschema::model().expect("the snapshot reads"); @@ -228,7 +245,7 @@ fn draft_starter_concepts_preserve_typed_holder_semantics() { let model = publicschema::model().expect("the snapshot reads"); assert_eq!( publicschema::pin().unwrap().commit, - "e5cfbbc0161e4d2c802d1acd752ec193253f7820" + "af10377ab57a416b07e93cc8277764895e974689" ); assert_eq!( model.classes["Farm"].uri, diff --git a/crates/registry-platform-config/src/identity_facts.rs b/crates/registry-platform-config/src/identity_facts.rs index dac57e3995..f5eec10390 100644 --- a/crates/registry-platform-config/src/identity_facts.rs +++ b/crates/registry-platform-config/src/identity_facts.rs @@ -463,6 +463,11 @@ fn valid_text(value: &str) -> bool { && value.bytes().all(|byte| byte.is_ascii_graphic()) } +/// Whether an exact purpose can be carried in a service role's identity facts. +pub fn valid_purpose(purpose: &str) -> bool { + valid_text(purpose) +} + /// An `https` URL without user information, query or fragment. pub fn https_url(value: &str) -> bool { Url::new(value).is_ok() @@ -723,7 +728,10 @@ fn check(document: &Document, facts: &IdentityFacts) -> Vec { } if profile.purposes.len() > MAXIMUM_PURPOSES || !unique(&profile.purposes) - || profile.purposes.iter().any(|purpose| !valid_text(purpose)) + || profile + .purposes + .iter() + .any(|purpose| !valid_purpose(purpose)) { error( &pointer("purposes"), diff --git a/crates/registry-review-client/README.md b/crates/registry-review-client/README.md index 720159179a..82dc1e1bb1 100644 --- a/crates/registry-review-client/README.md +++ b/crates/registry-review-client/README.md @@ -19,6 +19,9 @@ subject and original submission digest. Result lookup requires the accepted request binding and refuses a response unless its request, subject, policy, and submission digest all match exactly. A producer must persist that accepted binding before consuming a terminal result. +An initiator identity includes the claim name that supplied its value. The +client validates that member as part of the request and submission digest; the +provider decides whether it matches the producer's trusted binding. `request_progress` performs one `GET` with `include=progress` and returns the optional bounded `ReviewProgressCode`. It refuses a response unless the full diff --git a/crates/registry-review-protocol/README.md b/crates/registry-review-protocol/README.md index beb89b64e5..0f061443cf 100644 --- a/crates/registry-review-protocol/README.md +++ b/crates/registry-review-protocol/README.md @@ -23,6 +23,10 @@ on both 201 creation and 200 recovery. The accepted JSON envelope is unchanged. The submission digest covers the authenticated producer, source namespace, and complete create request, including its original `PolicySelection`. +When a request names a human initiator, `HumanIdentity` carries the issuer, +the principal claim name, and that claim's value. A provider uses the claim +name only to verify its configured identity agreement. It never reads another +claim from the producer's token. The default selector is `{"id":"review-policy"}` and delegates version choice to the trusted provider at first acceptance. Strict mode adds both `version` and `digest`; partial pins are invalid. The provider atomically persists the diff --git a/crates/registry-review-protocol/src/lib.rs b/crates/registry-review-protocol/src/lib.rs index 9d41064c30..2aad8e7b71 100644 --- a/crates/registry-review-protocol/src/lib.rs +++ b/crates/registry-review-protocol/src/lib.rs @@ -324,17 +324,44 @@ impl From for PolicySelection { } } -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct HumanIdentity { pub issuer: String, + #[serde(skip_serializing_if = "String::is_empty")] + #[cfg_attr(feature = "schema", schemars(required))] + pub principal_claim: String, pub subject: String, } +impl<'de> Deserialize<'de> for HumanIdentity { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct Wire { + issuer: String, + #[serde(default)] + principal_claim: String, + subject: String, + } + + let wire = Wire::deserialize(deserializer)?; + Ok(Self { + issuer: wire.issuer, + principal_claim: wire.principal_claim, + subject: wire.subject, + }) + } +} + impl HumanIdentity { pub fn check(&self) -> Result<(), ProtocolError> { check_bounded_text(&self.issuer, MAXIMUM_REFERENCE_BYTES)?; + check_bounded_text(&self.principal_claim, MAXIMUM_IDENTIFIER_BYTES)?; check_bounded_text(&self.subject, MAXIMUM_REFERENCE_BYTES) } } @@ -977,6 +1004,7 @@ mod tests { requester_reference: "source-request-7".to_owned(), initiator: Some(HumanIdentity { issuer: "https://issuer.example".to_owned(), + principal_claim: "registry_principal".to_owned(), subject: "person-2".to_owned(), }), context: ReviewContext::CurrentSource { @@ -988,6 +1016,18 @@ mod tests { } } + #[test] + fn a_human_identity_requires_its_principal_claim_binding() { + let mut value = serde_json::to_value(request()).unwrap(); + value["initiator"] + .as_object_mut() + .unwrap() + .remove("principalClaim"); + let decoded: ReviewCreateRequest = + serde_json::from_value(value).expect("retained pre-binding requests remain decodable"); + assert_eq!(decoded.check(), Err(ProtocolError::Text)); + } + #[test] fn policy_selection_freezes_the_original_selector_in_submission_identity() { let strict = request(); diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index 45a68cb73e..7c92ba8e86 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -6133,6 +6133,7 @@ mod tests { }); if with_initiator { producer["trustedInitiatorIssuer"] = json!("https://initiator.example.invalid/"); + producer["trustedInitiatorPrincipalClaim"] = json!("sub"); } let casework = json!({ "name": "synthetic-project", diff --git a/crates/registry-stack-client-node/casework/client.d.ts b/crates/registry-stack-client-node/casework/client.d.ts index e4bc790537..d23da125a9 100644 --- a/crates/registry-stack-client-node/casework/client.d.ts +++ b/crates/registry-stack-client-node/casework/client.d.ts @@ -232,7 +232,7 @@ export interface SubjectBinding { source: string; type: string; id: string; vers export interface PolicyBinding { id: string; version: string; digest: ContentDigest } /** Select the current admitted policy by ID, or require one complete exact pin. */ export type PolicySelection = { id: string; version?: never; digest?: never } | PolicyBinding -export interface HumanIdentity { issuer: string; subject: string } +export interface HumanIdentity { issuer: string; principalClaim: string; subject: string } export type ReviewContext = | { mode: 'submitted'; snapshot: Readonly> } | { mode: 'current-source'; binding: { reference: string } } diff --git a/docs/site/src/content/docs/configure/casework.mdx b/docs/site/src/content/docs/configure/casework.mdx index 0699603992..e5c0ab5fd2 100644 --- a/docs/site/src/content/docs/configure/casework.mdx +++ b/docs/site/src/content/docs/configure/casework.mdx @@ -127,7 +127,11 @@ must see the source's current record sets `mode: current-source` and names a [context provider](../../reference/glossary/#context-provider), as [Review a Proposal in Casework](../../tutorials/review-breg-changes-in-casework/) does. `trustedProducers` names each calling system: its access profile, issuer, subject, source -namespaces, and the policies it may request. +namespaces, and the policies it may request. When one of those policies excludes its initiator, +the producer also sets `trustedInitiatorIssuer` and `trustedInitiatorPrincipalClaim`. The latter +must equal the `principalClaim` on every human Casework profile. +Base Registry Engine (BReg) sends that claim name with the initiator's value. +Casework refuses the request if either pin differs. The digest covers the policy's behaviour and everything it depends on: stages, context, outcomes, access profiles, queues, teams, producers, and the clocks and calendars it uses. A producer that @@ -137,7 +141,7 @@ the active digest changes. {/* Evidence: crates/registry-casework-core/src/review.rs, digest_with(); crates/registry-casework-core/src/config.rs, policy_dependencies(), ReviewProducerPolicy; - crates/registry-review-protocol/src/lib.rs, PolicySelection::matches; + crates/registry-review-protocol/src/lib.rs, PolicySelection::matches, HumanIdentity; crates/registry-casework-core/src/http.rs, REVIEW_POLICY_MISMATCH_PROBLEM; crates/registry-casework-core/src/context.rs, ReviewContextPolicy. */} @@ -301,7 +305,7 @@ needs an admitted source profile and `delegatedDisplayExchange` on its provider; Casework exchanges to the source resource rather than forwarding its own bearer. The institution must approve the source agent profile's disclosure ceiling. That service profile does not automatically inherit the staff member's human -Base Registry Engine (BReg) permissions. +BReg permissions. Follow [the staff configuration example](https://github.com/registrystack/registry-stack/blob/main/products/platform/examples/mcp-runtime/README.md) for settings that must match and issuer requirements. `registry-mcp` is currently diff --git a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx index 2d5a65e7e4..70f8a9c77b 100644 --- a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx +++ b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx @@ -78,6 +78,30 @@ database forward in place when you run `messagingctl apply`. crates/registry-bregctl/src/doctor.rs, startup.database.pre-1-0-schema; crates/registry-messaging/migrations/0101_dispatch_lease_expiry.sql (forward migration). */} +## Upgrade workflows that submit reviews + +When a release introduces `initiator.principalClaim`, pause new Review +submissions and let the previous matching release settle outstanding BReg +Proposal reviews. Finish or cancel Coordinator runs that submit reviews on +that release. BReg names unfinished requests using the earlier initiator +format at startup, plan and apply. Coordinator holds runs sealed with the +earlier Review operation binding before dispatch. +Record any needed BReg review status for older reviews with a named initiator +before upgrading. Reading this status afterward requires a pre-upgrade backup +and its matching release. + +Update the Casework producer pin and any authored initiator mapping, then +recheck and package with the target release. Follow the Casework release notes +for its retained-state requirements before restarting the paired runtimes and +clients on the same release. + +{/* Evidence: crates/registry-breg/src/review_store.rs, check_review_initiator_upgrade; + crates/registry-breg/src/startup.rs, review_binding_startup_error; + crates/registry-breg/src/migration.rs, activate; + crates/registry-coordinator/src/operations.rs, submit_review; + crates/registry-coordinator/src/store/recovery.rs, check_runtime_bindings; + products/casework/CHANGELOG.md. */} + ## Upgrade in this order BReg goes first, because Casework and Evidence both read it. Pair Casework with the resulting diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index efc92997e0..e7f898806b 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -88,6 +88,7 @@ An event has at most one handler. If you need fanout, put an external event gateway behind one destination. Production compilation refuses an event without a handler (`breg.event.delivery-required`), because there is no supported outbox consumer API. +A Record hook that declares `principal` also needs a handler during authoring. A Proposal lifecycle hook is declared on the Action under `execution.proposal.hooks`, selects native transitions, and uses its own value-free event schema; it is separate from Record field projections. @@ -105,6 +106,7 @@ owns. {/* Evidence: crates/registry-breg/tests/compiler_webhook.rs outbox_only_event_is_authoring_only_and_production_requires_delivery, + proposal_hook_authority_requires_a_handler_in_authoring, additive_modules_add_nonconflicting_subscriptions_deterministically_and_refuse_conflicts; crates/registry-breg/src/compiler.rs breg.event.delivery-required. */} @@ -205,6 +207,38 @@ input. crates/registry-breg/tests/postgres_ingestion_runs.rs event_inventory_faults_are_unavailable_for_direct_and_ingestion_writes. */} +### Authorize a proposing hook + +A receiver can return a canonical proposal answer only when the Record hook declares `principal`. +That value names the project access profile whose Action grant limits the proposal. It is an +authored authority binding, not a token subject or a claim value supplied by the receiver. + +Every access profile still declares `principalClaim`, because the same profile contract describes +authenticated HTTP callers. A hook does not manufacture that claim, a token, or other caller +context. Its profile must therefore use `requiredScopes: unrestricted` and omit +`requiredPurposes`, `actorKind`, `requesterClients` and `taskGrant`. The Action grant must allow +`invoke`, name the permitted results and use unrestricted target row boundaries. The compiler +refuses an unknown or caller-dependent hook profile. The delivery worker checks the compiled grant +again before applying an answer. + +A profile selected by a proposing hook is also internal-only. BReg removes it from every issuer's +HTTP reach when `accessProfiles` is omitted, and a runtime file that lists it explicitly is refused +with `breg.runtime.hook-profile-http-reachable`. Use a separate profile for ordinary HTTP access. + +Omit `principal` for a notification-only webhook. It can still deliver and acknowledge events, but +any proposal answer is dead-lettered rather than applied. + +{/* Evidence: crates/registry-breg/tests/compiler_webhook.rs, + proposal_hook_authority_requires_a_caller_independent_profile, + proposal_hook_accepts_a_bounded_profile_and_keeps_its_authored_binding, + notification_only_hook_does_not_constrain_unrelated_caller_profiles; + crates/registry-breg/tests/http_auth.rs, + an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes, + an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile; + crates/registry-breg/tests/postgres_hook_changes.rs, + real_postgres_a_loaded_hook_grant_requiring_caller_context_is_refused_without_mutation, + real_postgres_a_hook_without_a_principal_compiles_and_delivers. */} + ## Bind each destination Add a `destinations.hooks` block to the runtime file, with one entry per destination the package diff --git a/docs/site/src/content/docs/reference/bregctl-publicschema-wizard.mdx b/docs/site/src/content/docs/reference/bregctl-publicschema-wizard.mdx index 67bd3e77a1..cfdc7bc76b 100644 --- a/docs/site/src/content/docs/reference/bregctl-publicschema-wizard.mdx +++ b/docs/site/src/content/docs/reference/bregctl-publicschema-wizard.mdx @@ -1,6 +1,6 @@ --- title: PublicSchema wizard prompts -description: The nine questions bregctl init --from publicschema asks at a terminal, what each one lists and starts ticked, how a property becomes a field, what the derivation refuses, and how cancellation and a missing terminal are reported. +description: The questions bregctl init --from publicschema asks at a terminal, what each one lists and starts ticked, how a property becomes a field, what the derivation refuses, and how cancellation and a missing terminal are reported. status: current owner: registry-docs source_repos: @@ -11,7 +11,7 @@ locale: en standards_referenced: [] --- -`bregctl init --from publicschema`, given neither `--starter` nor `--selection`, asks nine +`bregctl init --from publicschema`, given neither `--starter` nor `--selection`, asks questions at a terminal. Your answers become the same `BRegModelSelection` document a starter ships or `--selection` reads, and the derivation treats all three alike. @@ -29,8 +29,9 @@ tooling text and can change. registry in its IRIs, scopes, and the catalogue`. There is no default. An answer must be 1 to 64 characters, start with a lowercase letter, and use only `a-z`, `0-9`, `-`, -and `_`. The project appends `-authority`, `-api`, `-service`, `-operator`, and `-reader` to name -what it derives, and each result must fit too, so the identifier can be at most 54 characters. +and `_`. The project appends `-authority`, `-api`, `-service`, and `-operator` to name what it derives. +The identifier must also leave room for `-reader`, which an optional reporting profile uses. Each +result must fit, so the identifier can be at most 54 characters. ## Registry title @@ -110,7 +111,7 @@ The wizard leaves every Record type `internal`. {/* Evidence: the mapping is a Rust match, not data. crates/registry-bregctl/src/init_from_model/resolve.rs, field_id(), reserved_field_id(), resolve_entity(), IDENTIFIER_MAX_LENGTH, field_kind(), scalar_kind(), bespoke_kind(), geometry_schema(), code_max_length(), list_of(), object_schema(), value_object_schema(), slot_classification(), LIST_MAX_ITEMS, LIST_MAX_BYTES, OBJECT_MAX_BYTES, GEOMETRY_MAX_BYTES, DECIMAL_PRECISION, and DECIMAL_SCALE; crates/registry-bregctl/src/init_from_model/wizard.rs, shape(), scalar_shape(), and assemble(); crates/registry-breg/src/logical_names.rs, reserved_logical_name(); - crates/registry-linkml/src/publicschema.rs, bespoke_type(), inline_only(), and sensitivity(). */} + crates/registry-linkml/src/publicschema.rs, bespoke_type(), inline_only(), and sensitivity_in_class(). */} ## Which entity does `.` point at? @@ -120,6 +121,14 @@ default identifiers of the chosen concepts that fit, in the order chosen. It is asked only where several chosen concepts fit a single-valued reference, after every concept's properties are settled, because a property may point at a concept chosen later. +`bregctl` follows each concept's primary parents (`is_a`) to match a reference target. It refuses an +explicit `Organization` target for `Enrollment.beneficiary`. PublicSchema connects `Organization` +to the `Party` range through a mixin. + +{/* Evidence: crates/registry-linkml/src/model.rs, is_subclass_of(); + crates/registry-bregctl/src/init_from_model/resolve.rs, fits_range() and field_kind(); + crates/registry-linkml/publicschema/schema/{identity,program}.yaml. */} + ## Keep the default identifiers and routes? A yes-or-no question defaulting to yes, with the help line `they name the collection routes, the @@ -148,14 +157,56 @@ An enumeration of at most 300 values starts ticked, the derivation's own default that differs is written into the selection's `vocabularies` list. Ticking one of more than 1024 values is refused. +## Add a read-only reporting profile? + +`Add a read-only reporting profile?`, defaulting to no, with the help line `the reader may list every +row of each Record type you choose`. No writes no `reporting` member into the selection. The +derivation creates only the `operator` access profile and its matching service role. The question is +skipped if the selection has no eligible field. + +Yes asks `Reporting purpose`, with the help line `the exact purpose the reader's token must carry`. +Enter the purpose exactly as the reader token will carry it. Use 1 to 128 printable ASCII characters +without spaces. + +It then asks `Which fields may the reporting profile read?`, with the help line `space to toggle, +type to filter, enter to confirm`. Each option uses the exact generated identifiers in the form +`.`, such as `person.given-name`. Choose at least one field. + +The wizard offers public and internal Record types and fields for this whole-collection profile. +The generated `reader` profile grants `get` and `list` for the chosen Record types, with only the named +fields in each record's data. The `reader` role in `service.yaml` binds that profile. `dev.yaml` adds +a development actor for the role. + +The generated identifier field is filterable only when you also choose it as a readable field. +No other field becomes filterable through this reporting selection. + +An authored selection uses the same optional shape: + +```yaml +reporting: + purpose: directory-statistics + records: + - recordType: person + readableFields: + - person-code + - given-name +``` + +`recordType` takes the derived Record type identifier. Each `readableFields` entry takes an +exact generated field identifier. Regenerating from a selection without `reporting` creates an +operator-only project. Add the reader's purpose and field list before regenerating if your +project uses the reporting grant. + ## Derive the project from this selection? The selection is printed as YAML, then one line naming any Record type no field connects to another, then a yes-or-no question defaulting to yes, with the help line `the document above is written into the project beside what it derives`. No writes nothing and reports `init.selection.cancelled`. -{/* Evidence: crates/registry-bregctl/src/init_from_model/wizard.rs, ask_target(), reference_questions(), ask_naming(), ask_entity_naming(), identifier_validator(), ask_vocabularies(), vocabulary_options(), vocabulary_overrides(), confirm_selection(), and unlinked_line(); - crates/registry-bregctl/src/init_from_model/resolve.rs, kebab_case(), pluralize(), INLINE_VOCABULARY_THRESHOLD, and resolve(); +{/* Evidence: crates/registry-bregctl/src/init_from_model/wizard.rs, ask_target(), reference_questions(), ask_naming(), ask_entity_naming(), identifier_validator(), ask_vocabularies(), vocabulary_options(), vocabulary_overrides(), ask_reporting(), confirm_selection(), and unlinked_line(); + crates/registry-bregctl/src/init_from_model/resolve.rs, kebab_case(), pluralize(), INLINE_VOCABULARY_THRESHOLD, reporting_fields(), resolve_reporting(), and resolve(); + crates/registry-bregctl/src/init_from_model/selection.rs, ReportingSelection and ReportingRecordSelection; + crates/registry-bregctl/src/init_from_model/render.rs, registry(), service_roles(), and development_plan(); crates/registry-manifest-core/src/lib.rs, MAX_CODELIST_CONCEPTS. */} ## What the derivation refuses diff --git a/docs/site/src/content/docs/reference/casework-configuration.mdx b/docs/site/src/content/docs/reference/casework-configuration.mdx index b698b272b5..8551724fbe 100644 --- a/docs/site/src/content/docs/reference/casework-configuration.mdx +++ b/docs/site/src/content/docs/reference/casework-configuration.mdx @@ -261,8 +261,13 @@ The removed runtime field `authentication.oidc.principalClaim` is refused with t You configure the trusted issuers under `authentication.oidc.issuers.`. Across that set, every access profile a person uses must name the same `principalClaim`. Casework refuses a project with mixed human principal claims with `casework.access-profile.mixed-principal-claims`. Profiles a trusted producer uses are services and share one claim among themselves, which may differ from the people's. A service requester profile must be named by a trusted producer's `profile` to be compared apart from people; no Casework route serves a service through any other requester profile. +A producer that sets `trustedInitiatorIssuer` also sets `trustedInitiatorPrincipalClaim`. The claim must match the one every human Casework profile reads. Casework refuses an initiator-excluding policy without both pins, and refuses a submitted initiator whose issuer or claim name differs. +Do not change that human claim while Casework retains reviews with named initiators. Package activation refuses the change until retention removes those reviews. A retained review admitted before its producer claim pin was recorded also blocks activation, because Casework cannot prove the stored value's identity meaning without rewriting history. {/* Evidence: crates/registry-casework/src/config.rs OidcConfig, TaskAuthorityConfig; + crates/registry-casework-core/src/config.rs ReviewProducerPolicy, trusted_producer_findings; + crates/registry-casework/src/review.rs create_review_request; + crates/registry-casework/src/pinned_work.rs compare_pinned_work; crates/registry-platform-config/src/caller_issuers.rs default_scope_claim; crates/registry-casework/src/task_grants/native_exchange_tests.rs unrestricted */} diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 0cf618e73d..90edb67127 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -5,7 +5,7 @@ status: current owner: registry-docs source_repos: - registry-stack -last_reviewed: "2026-11-28" +last_reviewed: "2026-12-02" doc_type: explanation locale: en standards_referenced: [] @@ -40,6 +40,7 @@ product can take back. | Host users who can write audit files | Nothing. | Rewriting or removing lines of a local audit file. Ship the stream to append-only storage (obligation 2). | | Package authors | Authoring the project under review. | A reviewed package that is wrong. Deployment-only values (environment, instance, database) are refused in a package, so the same bytes are promoted unchanged (`BREG-SEC-01`). | | BReg's in-process refresh worker | Running each configured refresh plan as that plan's service principal, inside the worker profile's root List boundary, its pinned row claims, and its `refreshExternalProjections` grant (`BREG-SEC-204`). | A plan that names a wider identity than intended. The worker presents no token from the issuer, so revoking that identity at the identity provider does not stop it. Removing the plan from the runtime file and restarting does. | +| BReg's Record hook worker | Applying a canonical proposal answer only under the hook's internal authored project profile and its bounded Action grant (`BREG-SEC-291`). | A reviewed package that deliberately grants the hook wider caller-independent Action authority than intended. The worker presents no caller token, the profile is unreachable from HTTP, and the worker cannot satisfy scope, purpose, actor, requester-client, task-grant or row-claim conditions. | {/* Evidence: products/breg/contracts/security-invariant-matrix.yaml, invariants; crates/registry-breg/tests/compiler_contract.rs, @@ -125,6 +126,28 @@ entry carries the same pseudonymous principal and record references as its attem breg.external-refresh.worker-not-admitted; crates/registry-breg/src/postgres/external_runtime/managed.rs, external-refresh-plan-step. */} +### Record hook proposal authority + +A Record hook is not an authenticated HTTP caller. When its receiver returns a canonical proposal +answer, BReg selects only the project access profile named by the hook's authored `principal` and +then applies the profile's Action grant. The required `principalClaim` remains profile metadata for +ordinary authenticated callers. BReg does not create a token claim from it. + +The compiler accepts a proposing hook profile only with unrestricted scopes and no required +purpose, actor kind, requester client or task grant. The Action grant must also have unrestricted +target row boundaries. Authentication removes that profile from every issuer's HTTP reach when an +issuer omits `accessProfiles`, while an issuer that lists it explicitly is refused. + +The loaded delivery inventory must retain the exact authored principal, and the worker rechecks the +compiled grant immediately before apply. A mismatch or caller-dependent grant is refused without a +Record mutation. A hook without `principal` remains a notification-only hook and cannot apply a +proposal. + +{/* Evidence: products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-291; + crates/registry-breg/tests/compiler_webhook.rs; + crates/registry-breg/tests/postgres_webhook_outbox.rs; + crates/registry-breg/tests/postgres_hook_changes.rs. */} + ### Supply chain Packages are verified by the SHA-256 of `SHA256SUMS`, with every listed file re-hashed before the diff --git a/docs/site/src/content/docs/security/casework.mdx b/docs/site/src/content/docs/security/casework.mdx index a2532fcea8..8e79697050 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -314,12 +314,15 @@ The residuals refer to these obligations by number. Revoke the key at the issuer and at every other relying party (`CASEWORK-RES-09`). {/* Evidence: crates/registry-casework/src/config.rs, revoked_key_ids, a_token_signed_by_a_revoked_key_id_is_refused_like_any_other_verification_failure. */} -10. Issue every person's tokens with the same principal claim. +10. Issue every person's tokens with the same principal claim, and pin that claim on each producer + trusted to name an initiator. Casework applies the same principal claim rule across the trusted issuer set. It refuses a `casework.yaml` whose reviewer, initiator and requester access profiles name different `principalClaim` values, because one person would then appear as two principals and separation-of-duties and one-seat checks would compare the wrong identities (`CASEWORK-SEC-16`). + Set `trustedInitiatorPrincipalClaim` beside `trustedInitiatorIssuer` to that same claim. Casework + refuses a producer's initiator when the submitted issuer or claim name differs. Producer profiles, which are services, share one claim among themselves. Secret files follow the [hardening checklist](../hardening-checklist/#secret-files). The diff --git a/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx b/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx index 3dcbce3163..0a29e91154 100644 --- a/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx +++ b/docs/site/src/content/docs/tutorials/derive-a-registry-from-publicschema.mdx @@ -17,12 +17,11 @@ tutorial_test: import QuickstartMeta from '../../../components/QuickstartMeta.astro'; -If you would rather start your registry from a published data model than type its fields yourself, -derive one from PublicSchema with Base Registry Engine (BReg). In about 30 to 45 minutes you will -have a registry of people, households, and household memberships running on your machine, with one -person in it that your operator client can read in full and your reader client can read without the -sensitive field. You will then edit the saved selection, compare the newly derived candidate with -the running package, and carry a local field and its access policy into the intended successor. +Derive a registry from PublicSchema with Base Registry Engine (BReg) when you want to start from a +published data model. In about 30 to 45 minutes you will run a registry of people, households, and +household memberships. Your operator client will create and read one person. You will then edit the +saved selection and compare the candidate with the running package. You will carry a local field and +its access policy into the intended successor. ready Created kept key /breg-audit-key Created kept key /breg-cursor-key Runtime config breg - Journey reader-lists-people passed + Journey operator-lists-people passed Logs rstack dev token --as operator - rstack dev token --as reader ``` The first start downloads PostgreSQL's image, so allow a few minutes. Before it reports `ready`, @@ -350,14 +349,13 @@ did not send are `null`, because the derivation makes no PublicSchema property r crates/registry-breg/src/api/mod.rs, router(); crates/registry-breg/src/logical_names.rs, default_api_name(). */} -## Read it as a reader +## Read it as the operator -List people under the `reader` access profile: +List people under the `operator` access profile: ```sh -READER_HEADERS="$(rstack dev token "$RUN" --as reader | awk '$2 == "headers" {sub(/^[[:blank:]]*[^[:blank:]]+ headers /, ""); print}')" -rstack breg api '/v1/records/persons?accessProfile=reader' \ - --url "$BREG_URL" --header @"$READER_HEADERS" +rstack breg api '/v1/records/persons?accessProfile=operator' \ + --url "$BREG_URL" --header @"$OPERATOR_HEADERS" ``` ```json test-excerpt @@ -366,9 +364,11 @@ rstack breg api '/v1/records/persons?accessProfile=reader' \ "dateOfBirth": "1990-04-12", "familyName": "Mensah", "givenName": "Ama", + "maritalStatus": "married", "personCode": "P-0001", "phoneNumber": null, "preferredLanguage": null, + "registrationNote": "local-ref-17", "sex": null }, "recordId": "", @@ -376,11 +376,11 @@ rstack breg api '/v1/records/persons?accessProfile=reader' \ } ``` -The same person comes back without `maritalStatus` or `registrationNote`. The derivation left the -sensitive PublicSchema field out of the reader grant, and your local policy did the same for the -institution-specific field. +The same person comes back with the restricted PublicSchema field and your local field. The starter +creates no general reporting profile. Add one only when you can name its purpose and exact readable +fields in the saved selection. -{/* Evidence: crates/registry-bregctl/src/init_from_model/render.rs, READER_PROFILE and readme(); +{/* Evidence: crates/registry-bregctl/src/init_from_model/render.rs, access_profiles() and readme(); crates/registry-breg/src/access.rs. */} ## Edit the saved selection and derive a candidate @@ -469,7 +469,7 @@ Reconcile those decisions manually. Add the field to the candidate: constraints: ``` -Restore only the operator grants, preserving the decision not to disclose the field to the reader: +Restore only the operator grants: ```diff lang="yaml" title="household-registry-2/registry.yaml" test-edit - readableFields: [person-code, given-name, family-name, date-of-birth, sex, preferred-language, phone-number] @@ -506,14 +506,9 @@ rstack breg explain access household-registry-2 writable fields ["date-of-birth","family-name","given-name","person-code","phone-number","preferred-language","registration-note","sex"] ``` -```text test-excerpt - readable fields ["date-of-birth","family-name","given-name","person-code","phone-number","preferred-language","sex"] - writable fields none -``` - -Confirm that `registration-note` remains `internal`, the operator can read and write it, and the -reader cannot read it. If any of those checks disagree with the policy you intended, edit the -candidate and repeat `check` and both explanations before comparing packages. +Confirm that `registration-note` remains `internal` and the operator can read and write it. If +either check disagrees with the policy you intended, edit the candidate and repeat `check` and both +explanations before comparing packages. {/* Evidence: crates/registry-bregctl/src/lib.rs, ExplainSubject::{Model, Access}; crates/registry-breg/src/access_preview.rs. */} diff --git a/docs/site/src/content/docs/tutorials/review-breg-changes-in-casework.mdx b/docs/site/src/content/docs/tutorials/review-breg-changes-in-casework.mdx index 29556a338b..b0778db3bf 100644 --- a/docs/site/src/content/docs/tutorials/review-breg-changes-in-casework.mdx +++ b/docs/site/src/content/docs/tutorials/review-breg-changes-in-casework.mdx @@ -276,11 +276,16 @@ trustedProducers: issuer: https://identity.example.test subject: facility-registry-review-producer trustedInitiatorIssuer: https://identity.example.test + trustedInitiatorPrincipalClaim: registry_principal sourceNamespaces: [facility-registry] reviewPolicies: [facility-address-review] retention: {receiptRetentionDays: 30} ``` +`trustedInitiatorPrincipalClaim` is the claim BReg uses to name the person who +submitted the Proposal. It must match every human Casework profile's +`principalClaim`; this tutorial uses `registry_principal` in both products. + Three values in the registry's binding must agree with that entry: - `producerId` equals the producer's key, `facility-registry`. Both products fold it into each diff --git a/external/README.md b/external/README.md index b640c46781..aefd815dcd 100644 --- a/external/README.md +++ b/external/README.md @@ -36,12 +36,12 @@ historical manifests that record earlier release inputs. `crates/registry-linkml/publicschema/` vendors a snapshot of the [PublicSchema](https://publicschema.org) reference model: repository `https://github.com/PublicSchema/publicschema.org`, commit -`e5cfbbc0161e4d2c802d1acd752ec193253f7820` from 2026-09-24, version 0.3.0, +`af10377ab57a416b07e93cc8277764895e974689` from 2026-12-03, version 0.3.0, licensed Creative Commons Attribution 4.0 International. It is a current vendored input, not a historical one. This commit, on upstream `main`, includes the draft government and agricultural holder concepts used by the -maintained BReg starters; the unchanged version string alone does not identify -those draft semantics. +maintained BReg starters. It also supplies class-specific sensitivity for the +subject links of service applications and administrative decisions. `crates/registry-linkml/publicschema/sync-snapshot.sh` refreshes the vendored files from a local checkout of the upstream repository and writes `PIN.yaml` diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 1e29c356ce..e311122419 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -30,6 +30,29 @@ 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`. + +- BREAKING: A Record hook that declares a proposal `principal` makes that + project access profile internal-only. It must use unrestricted scopes and + have no live caller requirements. BReg automatically excludes it from + issuer HTTP reach when `accessProfiles` is omitted and refuses a runtime + issuer that lists it explicitly. Keep ordinary HTTP access on another + profile, and omit `principal` for a notification-only hook. +- PublicSchema derivation classifies application and decision subject + references as restricted in their respective Record types. Review the + access profiles of existing derived projects before redeploying. +- BREAKING: PublicSchema reporting is opt-in. A selection without + `reporting` creates only `operator`. To generate `reader`, add a non-empty + `reporting.purpose` and list each derived `recordType` with its exact + `readableFields`. The generated profile grants only `get` and `list`, + excludes restricted Record types and fields, and receives its matching role + in `service.yaml`. If an existing project uses the reporting grant, add it + to the selection before regenerating. +- BREAKING: Before upgrading BReg, settle or cancel outstanding Proposal + reviews with a named initiator using the previous matching release. + Startup, plan and apply refuse retained work that lacks the initiator's + claim binding. Export any needed historical review status before upgrading + because older named-initiator status reads require the previous release. + - Record and read-path permissions can select stored fields with `readableFields.upToClassification`. Consent-gated permissions require explicit fields. diff --git a/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml b/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml index 646ba0c2fd..f0a3d97467 100644 --- a/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml +++ b/products/breg/acceptance/reviewed-evidence-journey/casework/casework.yaml @@ -5,22 +5,22 @@ project: version: '1' accessProfiles: staff: - principalClaim: sub + principalClaim: registry_principal requiredScopes: - casework:staff actsAs: staff administrator: - principalClaim: sub + principalClaim: registry_principal requiredScopes: - casework:admin actsAs: administrator requester: - principalClaim: sub + principalClaim: registry_principal requiredScopes: - casework:request actsAs: requester supervisor: - principalClaim: sub + principalClaim: registry_principal requiredScopes: - casework:supervisor actsAs: supervisor @@ -79,6 +79,7 @@ trustedProducers: issuer: https://issuer.example.test subject: producer trustedInitiatorIssuer: https://issuer.example.test + trustedInitiatorPrincipalClaim: registry_principal sourceNamespaces: - registry reviewPolicies: diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index 2073502dcb..c0ea4e25eb 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -307,3 +307,7 @@ invariants: - {"id": "BREG-SEC-288", "state": "enforced", "targetWave": "W5", "threat": "A message or mark-read by the party or the office, landing while the automatic worker applies an approved request, makes the Apply fail and hands the request back to the party.", "enforcementPoint": "The worker's Apply is fenced by its claimed lease, the submission version and the frozen effect digest inside the Apply transaction, not by a Proposal ETag read in an earlier one.", "refusal": "Apply the request; thread activity changes the revision but never what is applied.", "negativeId": "BREG-NEG-288", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "thread_activity_during_automatic_application_does_not_strand_the_request"}} - {"id": "BREG-SEC-289", "state": "enforced", "targetWave": "W5", "threat": "Office staff whose grant does not reach a Proposal confirm that it exists from how a thread route answers a malformed request.", "enforcementPoint": "Every thread route checks that the Proposal is visible to the admitted caller, under row boundaries and memberships, before it reads any header, query or body.", "refusal": "Conceal a hidden Proposal with 404 resource.not-found exactly as an unknown one.", "negativeId": "BREG-NEG-289", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_unknown_one"}} - {"id": "BREG-SEC-290", "state": "enforced", "targetWave": "W5", "threat": "A direct Record write names a referenced record the caller cannot read.", "enforcementPoint": "The write transaction reads each reference the item sets under the caller's own get or reference grant on the referenced Record type, using current transaction state. The probe requires an available row context and a validated reason when that grant requires one. Project compilation requires the grant. The reference-only policy applies only during the probe for that Record type.", "refusal": "An unauthorized, missing or tombstoned target yields 409 mutation.conflict for direct writes and 412 precondition.failed for ingestion. The same refusal applies when the attempted target grant requires a reason the request cannot supply. Refuse at compile with breg.access.reference-target-ungranted, breg.access-profile.reference-exclusive or breg.access.reference-grant-unused.", "negativeId": "BREG-NEG-290", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_direct_write_names_only_records_the_writer_can_read"}} + # Authoring and HTTP-boundary proofs: crates/registry-breg/tests/compiler_webhook.rs::proposal_hook_authority_requires_a_caller_independent_profile and proposal_hook_authority_must_bind_an_existing_profile; crates/registry-breg/tests/http_auth.rs::an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes and an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile + # Exact source binding: crates/registry-breg/tests/postgres_webhook_outbox.rs::real_postgres_webhook_outbox_capture_is_atomic_package_bound_and_deterministically_identified + # Action Invoke dispatch: crates/registry-breg/src/api/tests/immediate_action_tests.rs::internal_hook_profile_is_excluded_from_action_invoke_http_authority + - {id: BREG-SEC-291, state: enforced, targetWave: W5, threat: "An HTTP caller selects the Action profile reserved for a proposing Record hook, the hook borrows caller authority it does not hold, or a loaded delivery substitutes another profile binding.", enforcementPoint: "Authentication excludes every proposing-hook profile from issuer HTTP reach and refuses an issuer that explicitly lists one; the authoring compiler requires a handler for each hook declaring principal and binds it to an existing caller-independent project profile; mutation planning re-derives the principal from the governed hook; live proposal application rechecks the compiled Action grant.", refusal: "Refuse explicit issuer reach with breg.runtime.hook-profile-http-reachable and HTTP selection with profile.not-authorized. Refuse a missing handler for a proposing hook with breg.event.delivery-required. Refuse an unknown or caller-dependent profile with breg.event.hook-authority-unknown or breg.event.hook-authority-unsupported. Refuse a loaded incompatible grant as hook.proposal.unauthorized and apply no Record mutation. Notification-only hooks that omit principal remain valid.", negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index d4842ab4f3..564a501933 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -350,3 +350,4 @@ traceability: - {"id": "BREG-SEC-288", "state": "enforced", "negativeId": "BREG-NEG-288", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "thread_activity_during_automatic_application_does_not_strand_the_request"}} - {"id": "BREG-SEC-289", "state": "enforced", "negativeId": "BREG-NEG-289", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_unknown_one"}} - {"id": "BREG-SEC-290", "state": "enforced", "negativeId": "BREG-NEG-290", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_direct_write_names_only_records_the_writer_can_read"}} + - {id: BREG-SEC-291, state: enforced, negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} diff --git a/products/breg/evidence/organization-selection.yaml b/products/breg/evidence/organization-selection.yaml index 7ca68dda6c..05e99e1fea 100644 --- a/products/breg/evidence/organization-selection.yaml +++ b/products/breg/evidence/organization-selection.yaml @@ -2,7 +2,7 @@ apiVersion: id.registrystack.org/formats/breg/model-selection/v1alpha1 kind: BRegModelSelection model: publicschema modelVersion: "0.3.0" -modelRevision: "e5cfbbc0161e4d2c802d1acd752ec193253f7820" +modelRevision: "af10377ab57a416b07e93cc8277764895e974689" registry: id: organization-registry title: Synthetic organization registry diff --git a/products/breg/generated/tools/model-selection.v1alpha1.schema.json b/products/breg/generated/tools/model-selection.v1alpha1.schema.json index 524871a64a..9bfaa03820 100644 --- a/products/breg/generated/tools/model-selection.v1alpha1.schema.json +++ b/products/breg/generated/tools/model-selection.v1alpha1.schema.json @@ -87,6 +87,54 @@ ], "type": "object" }, + "ReportingRecordSelection": { + "additionalProperties": false, + "properties": { + "readableFields": { + "description": "Exact generated field ids to grant.", + "items": { + "$ref": "#/$defs/LocalId" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "recordType": { + "$ref": "#/$defs/LocalId", + "description": "The generated Record type id, including any selected id override." + } + }, + "required": [ + "recordType", + "readableFields" + ], + "type": "object" + }, + "ReportingSelection": { + "additionalProperties": false, + "description": "The exact grant for the optional, whole-collection reporting profile.", + "properties": { + "purpose": { + "description": "The purpose a verified reader token must carry.", + "maxLength": 128, + "minLength": 1, + "pattern": "^[\\x21-\\x7E]+$", + "type": "string" + }, + "records": { + "items": { + "$ref": "#/$defs/ReportingRecordSelection" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "purpose", + "records" + ], + "type": "object" + }, "VocabularyMode": { "oneOf": [ { @@ -155,6 +203,9 @@ "registry": { "$ref": "#/$defs/RegistrySelection" }, + "reporting": { + "$ref": "#/$defs/ReportingSelection" + }, "vocabularies": { "items": { "$ref": "#/$defs/VocabularySelection" diff --git a/products/breg/scripts/test_validate_product.py b/products/breg/scripts/test_validate_product.py index 800e298e9b..50eab11f19 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, 291) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 292) 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 f87af0b0da..a27e2d6dcd 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, 291) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 292) 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 09a78fb949..ec3b1bbe0d 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -7,6 +7,18 @@ `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep the configured plaintext transport. +- BREAKING: a trusted producer that names human initiators now sets + `trustedInitiatorPrincipalClaim` beside `trustedInitiatorIssuer`. The claim + must match every human Casework access profile. Review requests carry that + claim name in `initiator.principalClaim`; Casework refuses a missing or + different binding before it creates initiator-excluding work. Package + activation also refuses to change the human principal claim while an + initiator-bearing review is retained. A retained review admitted before the + claim pin was recorded blocks activation until Casework's configured + retention removes it. For a pre-1.0 deployment with such retained reviews, + keep the prior package until retention completes, or start 1.0 with a fresh + Casework database. + - 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/casework/README.md b/products/casework/README.md index d68c2d19ab..a293715c40 100644 --- a/products/casework/README.md +++ b/products/casework/README.md @@ -91,7 +91,10 @@ client, rather than inventing a digest. A request to `source`, `type`, `id`, `version`, and a real content `digest`, an opaque `requesterReference`, and `context: {"mode":"submitted","snapshot":{...}}` that validates against the pinned display schema. An optional qualified -`initiator` supports reviewer exclusion. Send `Idempotency-Key`; a retry with +`initiator` carries its issuer, principal claim name, and value. A producer +whose policy excludes its initiator pins the same issuer and claim name under +`trustedProducers`; that claim must also be the one every human Casework +profile reads. Send `Idempotency-Key`; a retry with the same key and original body recovers the accepted request before consulting current policy, even after policy updates. Acceptance, polling and results retain the concrete accepted policy; never fill that binding into the original selector diff --git a/products/casework/contracts/cli/report.schema.json b/products/casework/contracts/cli/report.schema.json index 97da6aee0b..1838928a05 100644 --- a/products/casework/contracts/cli/report.schema.json +++ b/products/casework/contracts/cli/report.schema.json @@ -1825,6 +1825,13 @@ }, "trustedInitiatorIssuer": { "$ref": "#/$defs/Url" + }, + "trustedInitiatorPrincipalClaim": { + "description": "The claim the trusted initiator issuer uses to name the person. It must\nmatch the one human Casework profiles read.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/products/casework/contracts/security-invariant-matrix.yaml b/products/casework/contracts/security-invariant-matrix.yaml index 1543dc04cd..b22337b189 100644 --- a/products/casework/contracts/security-invariant-matrix.yaml +++ b/products/casework/contracts/security-invariant-matrix.yaml @@ -19,7 +19,7 @@ invariants: - {id: CASEWORK-SEC-13, invariants: [14, 17], state: enforced, targetWave: beta, threat: "Credentials or refusal details escape through an unbounded HTTP response.", enforcementPoint: "Private listener policy and one bounded problem/trace/cache/security boundary.", refusal: "Normalize extraction/media/body/auth failures without CORS or private values.", negativeId: CASEWORK-NEG-13, negativeTest: {path: crates/registry-casework/src/http.rs, name: http_edge_returns_closed_problems_with_request_trace_and_security_headers}} - {id: CASEWORK-SEC-14, invariants: [2, 3, 17, 18], state: enforced, targetWave: beta, threat: "A caseload administrator loses current team or source authority after preview.", enforcementPoint: "Independent live Directory and source checks at apply plus exact move fencing.", refusal: "Refuse newly concealed or unauthorized movement without any partial effect.", negativeId: CASEWORK-NEG-14, negativeTest: {path: crates/registry-casework/tests/review_acceptance_postgres.rs, name: source_visibility_and_directory_authority_are_both_live_at_caseload_apply}} - {id: CASEWORK-SEC-15, invariants: [11, 18], state: enforced, targetWave: beta, threat: "Clock recompute upgrades policy or accepts newly published inputs after preview.", enforcementPoint: "Pinned closure, original anchor, explicit holiday revision and task/occurrence fences.", refusal: "Require a new preview when holiday inputs change and preserve pinned policy.", negativeId: CASEWORK-NEG-15, negativeTest: {path: crates/registry-casework/tests/review_acceptance_postgres.rs, name: clock_recompute_uses_pinned_calendar_and_fences_changed_holiday_inputs}} - - {id: CASEWORK-SEC-16, invariants: [1, 3, 17, 18], state: enforced, targetWave: beta, threat: "One reviewer satisfies independent stage decisions or invalid results settle a request.", enforcementPoint: "Pinned stage thresholds and negative-decision mode, issuer-qualified reviewer exclusions, one principal claim for every human access profile and schema validation.", refusal: "Refuse duplicate or prior-stage identity and invalid structured result without emitting work.", negativeId: CASEWORK-NEG-16, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: prior_stage_identity_and_invalid_structured_result_emit_nothing}} + - {id: CASEWORK-SEC-16, invariants: [1, 3, 17, 18], state: enforced, targetWave: beta, threat: "One reviewer satisfies independent stage decisions, an unqualified initiator value names the wrong person, or invalid results settle a request.", enforcementPoint: "Pinned stage thresholds and negative-decision mode, issuer-and-claim-qualified initiator exclusion, one principal claim for every human access profile, retained-identity activation compatibility and schema validation.", refusal: "Refuse duplicate, initiator or prior-stage identity, an incompatible retained identity binding and invalid structured result without emitting work or changing the active package.", negativeId: CASEWORK-NEG-16, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: an_initiator_is_refused_by_name_and_is_only_recorded_from_a_trusted_issuer}} - {id: CASEWORK-SEC-17, invariants: [9, 17], state: enforced, targetWave: beta, threat: "A retention job leaves private context, decisions or recovery payloads indefinitely.", enforcementPoint: "Bounded review retention and exact request-owned erasure.", refusal: "Scrub private work and expire owned idempotency without changing terminal meaning.", negativeId: CASEWORK-NEG-17, negativeTest: {path: crates/registry-casework/tests/review_postgres.rs, name: terminal_retention_scrubs_private_work_and_expires_owned_idempotency}} - {id: CASEWORK-SEC-18, invariants: [3, 5, 18], state: enforced, targetWave: beta, threat: "A task grant survives responsibility changes or is revived after reassignment.", enforcementPoint: "Current holder/profile/Directory/template/subject checks and durable assignment generation.", refusal: "Invalidate authority monotonically while draft-only edits preserve deferred responsibility.", negativeId: CASEWORK-NEG-18, negativeTest: {path: crates/registry-casework/src/task_grants/http_tests.rs, name: deferred_review_grants_ignore_drafts_but_never_revive_after_responsibility_changes}} - {id: CASEWORK-SEC-19, invariants: [4, 5, 9, 17], state: enforced, targetWave: beta, threat: "A provider returns unrequested routing fields or silently reroutes existing tasks.", enforcementPoint: "Exact request/task/policy/contract purpose binding and compiled field set at task creation.", refusal: "Reject extra fields and retain only the derived queue.", negativeId: CASEWORK-NEG-19, negativeTest: {path: crates/registry-casework/tests/review_acceptance_postgres.rs, name: current_source_routing_is_purpose_bound_once_and_never_persists_fields}} diff --git a/products/casework/contracts/security-test-traceability.yaml b/products/casework/contracts/security-test-traceability.yaml index 9b4bae2d7b..fec3c85886 100644 --- a/products/casework/contracts/security-test-traceability.yaml +++ b/products/casework/contracts/security-test-traceability.yaml @@ -17,7 +17,7 @@ entries: - {id: CASEWORK-SEC-13, tests: [{file: crates/registry-casework/src/http.rs, name: http_edge_returns_closed_problems_with_request_trace_and_security_headers}]} - {id: CASEWORK-SEC-14, tests: [{file: crates/registry-casework/tests/review_acceptance_postgres.rs, name: source_visibility_and_directory_authority_are_both_live_at_caseload_apply}]} - {id: CASEWORK-SEC-15, tests: [{file: crates/registry-casework/tests/review_acceptance_postgres.rs, name: clock_recompute_uses_pinned_calendar_and_fences_changed_holiday_inputs}]} - - {id: CASEWORK-SEC-16, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: prior_stage_identity_and_invalid_structured_result_emit_nothing}, {file: crates/registry-casework-core/src/review.rs, name: advisory_thresholds_count_mixed_decisions_and_still_require_distinct_reviewers}, {file: crates/registry-casework-core/tests/principal_claims.rs, name: every_human_profile_kind_must_share_the_claim_of_the_others}, {file: crates/registry-casework/tests/human_identity_auth.rs, name: human_profiles_naming_different_principal_claims_are_refused_at_load}]} + - {id: CASEWORK-SEC-16, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: an_initiator_is_refused_by_name_and_is_only_recorded_from_a_trusted_issuer}, {file: crates/registry-casework/tests/review_postgres.rs, name: activation_preserves_the_claim_binding_of_retained_initiators}, {file: crates/registry-casework/tests/review_postgres.rs, name: prior_stage_identity_and_invalid_structured_result_emit_nothing}, {file: crates/registry-casework-core/src/review.rs, name: advisory_thresholds_count_mixed_decisions_and_still_require_distinct_reviewers}, {file: crates/registry-casework-core/tests/principal_claims.rs, name: an_initiator_excluding_producer_pins_the_human_principal_claim}, {file: crates/registry-casework-core/tests/principal_claims.rs, name: every_human_profile_kind_must_share_the_claim_of_the_others}, {file: crates/registry-casework/tests/human_identity_auth.rs, name: human_profiles_naming_different_principal_claims_are_refused_at_load}]} - {id: CASEWORK-SEC-17, tests: [{file: crates/registry-casework/tests/review_postgres.rs, name: terminal_retention_scrubs_private_work_and_expires_owned_idempotency}]} - {id: CASEWORK-SEC-18, tests: [{file: crates/registry-casework/src/task_grants/http_tests.rs, name: deferred_review_grants_ignore_drafts_but_never_revive_after_responsibility_changes}]} - {id: CASEWORK-SEC-19, tests: [{file: crates/registry-casework/tests/review_acceptance_postgres.rs, name: current_source_routing_is_purpose_bound_once_and_never_persists_fields}]} diff --git a/products/casework/examples/canonical-review/casework.yaml b/products/casework/examples/canonical-review/casework.yaml index e830bf5d67..74f00cd50d 100644 --- a/products/casework/examples/canonical-review/casework.yaml +++ b/products/casework/examples/canonical-review/casework.yaml @@ -6,15 +6,15 @@ project: version: "1" accessProfiles: staff: - principalClaim: sub + principalClaim: registry_principal requiredScopes: [casework:staff] actsAs: staff supervisor: - principalClaim: sub + principalClaim: registry_principal requiredScopes: [casework:supervisor] actsAs: supervisor administrator: - principalClaim: sub + principalClaim: registry_principal requiredScopes: [casework:admin] actsAs: administrator requester: @@ -110,6 +110,7 @@ trustedProducers: issuer: https://identity.example.test subject: facility-registry-review-producer trustedInitiatorIssuer: https://identity.example.test + trustedInitiatorPrincipalClaim: registry_principal sourceNamespaces: [facility-registry] reviewPolicies: [facility-address-review] retention: {receiptRetentionDays: 30} diff --git a/products/casework/generated/project/project.schema.json b/products/casework/generated/project/project.schema.json index c04711adc2..882c993ead 100644 --- a/products/casework/generated/project/project.schema.json +++ b/products/casework/generated/project/project.schema.json @@ -1403,6 +1403,10 @@ }, "trustedInitiatorIssuer": { "$ref": "#/$defs/Url" + }, + "trustedInitiatorPrincipalClaim": { + "description": "The claim the trusted initiator issuer uses to name the person. It must\nmatch the one human Casework profiles read.", + "type": "string" } }, "required": [ diff --git a/products/casework/generated/registry-casework.openapi.json b/products/casework/generated/registry-casework.openapi.json index 11e95fec1d..74942170ac 100644 --- a/products/casework/generated/registry-casework.openapi.json +++ b/products/casework/generated/registry-casework.openapi.json @@ -1203,12 +1203,16 @@ "issuer": { "type": "string" }, + "principalClaim": { + "type": "string" + }, "subject": { "type": "string" } }, "required": [ "issuer", + "principalClaim", "subject" ], "type": "object" @@ -4462,6 +4466,13 @@ }, "trustedInitiatorIssuer": { "$ref": "#/components/schemas/Url" + }, + "trustedInitiatorPrincipalClaim": { + "description": "The claim the trusted initiator issuer uses to name the person. It must\nmatch the one human Casework profiles read.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index af246eea8d..b2b80d0fde 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -7,6 +7,13 @@ `database.transport` to `verified-tls` to use TLS, or remove `sslmode` from the URL to keep the configured plaintext transport. +- BREAKING: Workflows that submit Casework reviews use a new retained + execution binding for `casework.submit-review-request/v1`. Requests with + an initiator now carry `initiator.principalClaim`. Let runs using the + previous binding finish, or cancel them using the previous matching + release. Recheck, package and apply the workflows with the new release. + Coordinator holds older runs at definition restore before they can dispatch. + - 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. diff --git a/products/coordinator/generated/operations/README.md b/products/coordinator/generated/operations/README.md index d958a37aa5..72eafba388 100644 --- a/products/coordinator/generated/operations/README.md +++ b/products/coordinator/generated/operations/README.md @@ -19,7 +19,7 @@ Each catalog operation has an input contract, the type its adapter decodes, and | [`breg.invoke-action/v1`](#breg.invoke-action/v1) | 1 | `breg` | mutation | required | required | same-command | none | [`onDeclaredRefusal`](breg.invoke-action.v1.declared-refusal.schema.json) | | [`external.get/v1`](#external.get/v1) | 1 | `external-http` | read | none | none | read-again | none | none | | [`evaluation.evaluate/v1`](#evaluation.evaluate/v1) | 1 | `evaluation` | evaluation | none | required | hold-after-dispatch | none | none | -| [`casework.submit-review-request/v1`](#casework.submit-review-request/v1) | 1 | `casework` | mutation | required | none | same-command | none | none | +| [`casework.submit-review-request/v1`](#casework.submit-review-request/v1) | 2 | `casework` | mutation | required | none | same-command | none | none | | [`casework.cancel-review-request/v1`](#casework.cancel-review-request/v1) | 1 | `casework` | mutation | required | none | same-command | none | none | | [`scheduling.preview-availability/v1`](#scheduling.preview-availability/v1) | 1 | `scheduling` | read | none | none | read-again | none | none | | [`external.command/v1`](#external.command/v1) | 1 | `external-http` | mutation | required | none | same-command | none | [`onDeclaredRefusal`](external.command.v1.declared-refusal.schema.json) | @@ -1074,7 +1074,7 @@ Host execution and completion contract: "readReceipt": false, "recovery": "same-command", "requiresPreparation": false, - "version": 1 + "version": 2 }, "limits": { "attemptTimeoutSeconds": 10, diff --git a/products/coordinator/generated/operations/casework.submit-review-request.v1.input.schema.json b/products/coordinator/generated/operations/casework.submit-review-request.v1.input.schema.json index a814112d51..6f13e652a0 100644 --- a/products/coordinator/generated/operations/casework.submit-review-request.v1.input.schema.json +++ b/products/coordinator/generated/operations/casework.submit-review-request.v1.input.schema.json @@ -12,12 +12,16 @@ "issuer": { "type": "string" }, + "principalClaim": { + "type": "string" + }, "subject": { "type": "string" } }, "required": [ "issuer", + "principalClaim", "subject" ], "type": "object" diff --git a/products/coordinator/generated/operations/catalog.json b/products/coordinator/generated/operations/catalog.json index 78079b1767..f332475469 100644 --- a/products/coordinator/generated/operations/catalog.json +++ b/products/coordinator/generated/operations/catalog.json @@ -1619,7 +1619,7 @@ "readReceipt": false, "recovery": "same-command", "requiresPreparation": false, - "version": 1 + "version": 2 }, "limits": { "attemptTimeoutSeconds": 10, @@ -1658,12 +1658,16 @@ "issuer": { "type": "string" }, + "principalClaim": { + "type": "string" + }, "subject": { "type": "string" } }, "required": [ "issuer", + "principalClaim", "subject" ], "type": "object" diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 5a02ffbbcd..ae6e81e053 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6040,7 +6040,7 @@ }, "artifact": { "path": "products/breg/generated/tools/model-selection.v1alpha1.schema.json", - "sha256": "975478df7cdc216115fcf370f1478ffc3309c6ac6ae47f79be1c8b358c90dd7e", + "sha256": "d01c4852709b392ba92df20525e79d8917e77a7f75ccc02d9a3b8879fb508988", "mediaType": "application/schema+json" } }, @@ -6238,7 +6238,7 @@ }, "artifact": { "path": "products/casework/generated/project/project.schema.json", - "sha256": "046d67a79c31a867499c61e681913002dcd1ac50c3e1cad2585feb5f1f1619af", + "sha256": "aab7b69e1dafb5eb660177e7e6c2a6aa2401e50754355c4c934e2dbbde1eb007", "mediaType": "application/schema+json" } }, @@ -6256,7 +6256,7 @@ }, "artifact": { "path": "products/casework/contracts/cli/report.schema.json", - "sha256": "10a09de6b586e2b9797e693799104927c6aba199acc2ed5bc26fcc0c46c2a43a", + "sha256": "b7584fcd639262718e7236d3d5d2969969ba7d726df89501eeb93fff7aeac890", "mediaType": "application/schema+json" } }, diff --git a/products/platform/examples/licensing/casework/casework.yaml b/products/platform/examples/licensing/casework/casework.yaml index ac1417315c..e73dcc02de 100644 --- a/products/platform/examples/licensing/casework/casework.yaml +++ b/products/platform/examples/licensing/casework/casework.yaml @@ -3,15 +3,15 @@ kind: CaseworkProject project: {id: licensing-review, version: "1"} accessProfiles: administrator: - principalClaim: sub + principalClaim: registry_principal requiredScopes: ["casework:admin"] actsAs: administrator reviewer: - principalClaim: sub + principalClaim: registry_principal requiredScopes: ["casework:review"] actsAs: staff supervisor: - principalClaim: sub + principalClaim: registry_principal requiredScopes: ["casework:supervise"] actsAs: supervisor intake: @@ -54,6 +54,7 @@ trustedProducers: issuer: https://identity.licensing.example.test subject: intake trustedInitiatorIssuer: https://identity.licensing.example.test + trustedInitiatorPrincipalClaim: registry_principal sourceNamespaces: [licensing] reviewPolicies: [licensing-approval] retention: {receiptRetentionDays: 7} diff --git a/products/platform/examples/licensing/dev-journeys.yaml b/products/platform/examples/licensing/dev-journeys.yaml index c4e4cfdc97..e6bf695ebe 100644 --- a/products/platform/examples/licensing/dev-journeys.yaml +++ b/products/platform/examples/licensing/dev-journeys.yaml @@ -41,7 +41,7 @@ journeys: # SHA-256 of the synthetic submitted snapshot's canonical JSON. digest: "sha256:847c1042e1013e5b80dc8bdb7c021b584be3a7b778a4f242e42777b07539b9e5" requesterReference: application-001 - initiator: {issuer: https://identity.licensing.example.test, subject: applicant} + initiator: {issuer: https://identity.licensing.example.test, principalClaim: registry_principal, subject: applicant} context: mode: submitted snapshot: {reference: application-001, profession: Surveyor} diff --git a/release/scripts/check-gates-inventory.py b/release/scripts/check-gates-inventory.py index 1ef809b717..99fdb4b354 100644 --- a/release/scripts/check-gates-inventory.py +++ b/release/scripts/check-gates-inventory.py @@ -748,7 +748,7 @@ ), ( "Release manifest validation", - "uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-current", + "uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-current-ci", ), ( "Release docset validation", diff --git a/release/scripts/registry-release b/release/scripts/registry-release index 4565d23fcd..7d35207e17 100755 --- a/release/scripts/registry-release +++ b/release/scripts/registry-release @@ -529,7 +529,10 @@ def external_pin_errors(external: Any, repo_root: Path, version: str) -> list[st return errors -def validate(manifest_path: Path) -> int: +def validate( + manifest_path: Path, + inherited_source_ref: str | None = None, +) -> int: manifest = load_yaml(manifest_path) errors: list[str] = [] stack = manifest.get("stack", {}) if isinstance(manifest, dict) else {} @@ -580,6 +583,8 @@ def validate(manifest_path: Path) -> int: catalog_source_ref = source_ref if has_source_ref else None if catalog_source_ref is None: catalog_source_ref = local_tag_target(repo_root, source_tag) + if catalog_source_ref is None: + catalog_source_ref = inherited_source_ref errors.extend( identifier_catalog_errors( version, @@ -620,7 +625,7 @@ def validate(manifest_path: Path) -> int: return 0 -def validate_current(manifest_dir: Path) -> int: +def current_manifest_path(manifest_dir: Path) -> Path: candidates: list[tuple[tuple[int, int, int], Path]] = [] for path in sorted(manifest_dir.glob("registry-stack-*.yaml")): try: @@ -643,30 +648,133 @@ def validate_current(manifest_dir: Path) -> int: YamlDependencyError, ReleasePlanError, ) as exc: - print( - f"error: cannot select current release manifest from {path}: {exc}", - file=sys.stderr, - ) - return 1 + raise ReleasePlanError( + f"cannot select current release manifest from {path}: {exc}" + ) from exc if not candidates: - print( - f"error: no Registry Stack release manifests found in {manifest_dir}", - file=sys.stderr, + raise ReleasePlanError( + f"no Registry Stack release manifests found in {manifest_dir}" ) - return 1 current_version = max(version for version, _path in candidates) current_paths = [path for version, path in candidates if version == current_version] if len(current_paths) != 1: rendered = ", ".join(str(path) for path in current_paths) - print( - f"error: version {'.'.join(str(part) for part in current_version)} " - f"has multiple release manifests: {rendered}", - file=sys.stderr, + raise ReleasePlanError( + f"version {'.'.join(str(part) for part in current_version)} " + f"has multiple release manifests: {rendered}" ) + return current_paths[0] + + +def validate_current(manifest_dir: Path) -> int: + try: + manifest_path = current_manifest_path(manifest_dir) + except ReleasePlanError as exc: + print(f"error: {exc}", file=sys.stderr) return 1 - return validate(current_paths[0]) + return validate(manifest_path) + + +def validate_manifest_ci(manifest_path: Path, base_ref: str | None) -> int: + """Validate one manifest under the ordinary CI comparison policy. + + A manifest changed from the event base belongs to the proposed checkout and + uses strict validation. An inherited manifest uses its own last-changing + commit from the trusted base history, after an exact byte comparison. + """ + try: + history_ref = "HEAD" + repo_root = Path( + git_plan_output( + manifest_path.parent, + "rev-parse", + "--show-toplevel", + ) + ) + try: + relative_manifest = manifest_path.resolve().relative_to(repo_root.resolve()) + except ValueError as exc: + raise ReleasePlanError( + f"current release manifest is outside its repository: {manifest_path}" + ) from exc + + if base_ref is not None: + history_ref = resolve_commit( + repo_root, + base_ref, + "release manifest comparison base", + ) + comparison = subprocess.run( + ["git", "diff", "--quiet", history_ref, "--", relative_manifest], + cwd=repo_root, + check=False, + ) + if comparison.returncode == 1: + return validate(manifest_path) + if comparison.returncode != 0: + raise ReleasePlanError( + f"cannot compare {relative_manifest} with {base_ref}" + ) + + worktree_comparison = subprocess.run( + ["git", "diff", "--quiet", "HEAD", "--", relative_manifest], + cwd=repo_root, + check=False, + ) + if worktree_comparison.returncode == 1: + return validate(manifest_path) + if worktree_comparison.returncode != 0: + raise ReleasePlanError( + f"cannot compare {relative_manifest} with the checked-out source" + ) + + source_ref = git_plan_output( + repo_root, + "log", + "-1", + "--format=%H", + history_ref, + "--", + relative_manifest.as_posix(), + ) + if HEX40.fullmatch(source_ref) is None: + raise ReleasePlanError( + f"cannot resolve the committed source of {relative_manifest}" + ) + committed = subprocess.run( + ["git", "show", f"{source_ref}:{relative_manifest.as_posix()}"], + cwd=repo_root, + capture_output=True, + check=False, + ) + if committed.returncode != 0: + raise ReleasePlanError( + f"{relative_manifest} is missing from its committed source {source_ref}" + ) + if committed.stdout != manifest_path.read_bytes(): + raise ReleasePlanError( + f"{relative_manifest} does not match its committed source {source_ref}" + ) + except (OSError, UnicodeError, ReleasePlanError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + return validate( + manifest_path, + inherited_source_ref=source_ref, + ) + + +def validate_current_ci(manifest_dir: Path, base_ref: str | None) -> int: + """Select the maintained manifest and apply ordinary CI validation.""" + try: + manifest_path = current_manifest_path(manifest_dir) + except ReleasePlanError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + return validate_manifest_ci(manifest_path, base_ref) def published_release_tags(metadata: Any) -> set[str]: @@ -4647,6 +4755,17 @@ def main() -> int: validate_current_parser.add_argument( "--manifest-dir", type=Path, default=RELEASE_MANIFEST_DIR ) + validate_current_ci_parser = subparsers.add_parser( + "validate-current-ci", + help=( + "validate a changed current manifest against the checkout or an " + "inherited current manifest against its committed source" + ), + ) + validate_current_ci_parser.add_argument( + "--manifest-dir", type=Path, default=RELEASE_MANIFEST_DIR + ) + validate_current_ci_parser.add_argument("--base-ref") docsets_parser = subparsers.add_parser("validate-docsets") docsets_parser.add_argument( "--manifest-dir", type=Path, default=RELEASE_MANIFEST_DIR @@ -4813,6 +4932,8 @@ def main() -> int: return validate(args.manifest) if args.command == "validate-current": return validate_current(args.manifest_dir) + if args.command == "validate-current-ci": + return validate_current_ci(args.manifest_dir, args.base_ref) if args.command == "validate-docsets": return validate_docsets( args.manifest_dir, diff --git a/release/scripts/test_check_gates_inventory.py b/release/scripts/test_check_gates_inventory.py index f533f5c3a9..c897914dfd 100644 --- a/release/scripts/test_check_gates_inventory.py +++ b/release/scripts/test_check_gates_inventory.py @@ -2006,7 +2006,7 @@ def test_missing_release_docset_validation_is_reported(self) -> None: def test_release_manifest_validation_uses_only_the_maintained_manifest( self, ) -> None: - command = "uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-current" + command = "uv run --no-project --with PyYAML==6.0.2 python3 release/scripts/registry-release validate-current-ci" self.assertIn(command, self.workflow) self.assertNotIn( "for manifest in release/manifests/registry-stack-*.yaml", diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 618f0b891c..707c6de140 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -5471,13 +5471,129 @@ def test_validate_does_not_require_thunderid_pin_through_beta_57(self) -> None: self.assertNotIn("external.thunderid", result.stderr) def test_validate_accepts_every_historical_manifest(self) -> None: + registry_release = load_registry_release() for manifest in sorted((ROOT / "release/manifests").glob("registry-stack-*.yaml")): - version = yaml.safe_load(manifest.read_text(encoding="utf-8"))["stack"]["version"] + data = yaml.safe_load(manifest.read_text(encoding="utf-8")) + version = data["stack"]["version"] if tuple(int(part) for part in str(version).split(".")) < (0, 19, 0): continue # validate refuses pre-v0.19 manifests by design with self.subTest(manifest=manifest.name): - result = run_tool("validate", str(manifest)) - self.assertEqual(0, result.returncode, result.stderr) + source_tag = data["stack"]["source_tag"] + tag_target = subprocess.run( + [ + "git", + "rev-parse", + "--verify", + f"refs/tags/{source_tag}^{{}}", + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if "source_ref" in data["stack"] or tag_target.returncode == 0: + result = run_tool("validate", str(manifest)) + self.assertEqual(0, result.returncode, result.stderr) + else: + errors = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(errors): + result = registry_release.validate_manifest_ci(manifest, None) + self.assertEqual(0, result, errors.getvalue()) + + def test_validate_current_ci_uses_inherited_source_and_refuses_proposed_drift( + self, + ) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = init_repo(Path(tmp)) + catalog_path = root / "products/identifiers/generated/catalog.v1.json" + catalog_path.parent.mkdir(parents=True) + catalog_path.write_text( + json.dumps({"version": 1, "entries": [{"status": "active"}]}) + + "\n", + encoding="utf-8", + ) + git(root, "add", str(catalog_path.relative_to(root))) + git(root, "commit", "-m", "record release catalog") + catalog_ref = git(root, "rev-parse", "HEAD") + manifest = write_manifest( + root, + version="0.19.1", + source_ref=catalog_ref, + ) + data = yaml.safe_load(manifest.read_text(encoding="utf-8")) + del data["stack"]["source_ref"] + del data["stack"]["status"] + manifest_dir = root / "release/manifests" + manifest_dir.mkdir(parents=True) + manifest = manifest_dir / "registry-stack-beta-6.yaml" + manifest.write_text( + yaml.safe_dump(data, sort_keys=False), encoding="utf-8" + ) + prepared_manifest = manifest.read_bytes() + git(root, "add", str(manifest.relative_to(root))) + git(root, "commit", "-m", "prepare release manifest") + baseline_ref = git(root, "rev-parse", "HEAD") + + catalog_path.write_text( + json.dumps( + { + "version": 1, + "entries": [ + {"status": "active"}, + {"status": "active"}, + ], + } + ) + + "\n", + encoding="utf-8", + ) + git(root, "add", str(catalog_path.relative_to(root))) + git(root, "commit", "-m", "advance current catalog") + manifest.write_bytes(prepared_manifest + b"# transient manifest touch\n") + git(root, "add", str(manifest.relative_to(root))) + git(root, "commit", "-m", "touch inherited manifest") + manifest.write_bytes(prepared_manifest) + git(root, "add", str(manifest.relative_to(root))) + git(root, "commit", "-m", "restore inherited manifest") + + inherited = run_tool( + "validate-current-ci", + "--manifest-dir", + str(manifest_dir), + "--base-ref", + baseline_ref, + ) + strict = run_tool( + "validate-current", + "--manifest-dir", + str(manifest_dir), + ) + + manifest.write_text( + manifest.read_text(encoding="utf-8") + "# proposed manifest update\n", + encoding="utf-8", + ) + git(root, "add", str(manifest.relative_to(root))) + git(root, "commit", "-m", "change proposed release manifest") + proposed = run_tool( + "validate-current-ci", + "--manifest-dir", + str(manifest_dir), + "--base-ref", + baseline_ref, + ) + + self.assertEqual(0, inherited.returncode, inherited.stderr) + self.assertNotEqual(0, strict.returncode) + self.assertIn( + "identifier_catalog.sha256 does not match the committed catalog bytes", + strict.stderr, + ) + self.assertNotEqual(0, proposed.returncode) + self.assertIn( + "identifier_catalog.sha256 does not match the committed catalog bytes", + proposed.stderr, + ) def test_validate_docsets_skips_external_pins(self) -> None: with tempfile.TemporaryDirectory() as tmp: @@ -5722,6 +5838,39 @@ def test_validate_uses_identifier_catalog_from_recorded_source_ref(self) -> None self.assertNotEqual(0, mismatched.returncode) self.assertIn("does not match the committed catalog bytes", mismatched.stderr) + def test_validate_refuses_missing_recorded_catalog_source(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = init_repo(Path(tmp)) + catalog_path = root / "products/identifiers/generated/catalog.v1.json" + catalog_path.parent.mkdir(parents=True) + catalog_path.write_text( + json.dumps({"version": 1, "entries": [{"status": "active"}]}) + + "\n", + encoding="utf-8", + ) + git(root, "add", str(catalog_path.relative_to(root))) + git(root, "commit", "-m", "record release catalog") + source_ref = git(root, "rev-parse", "HEAD") + manifest = write_manifest( + root, + version="0.19.1", + source_ref=source_ref, + status="released", + ) + data = yaml.safe_load(manifest.read_text(encoding="utf-8")) + data["stack"]["source_ref"] = "f" * 40 + manifest.write_text( + yaml.safe_dump(data, sort_keys=False), encoding="utf-8" + ) + + result = run_tool("validate", str(manifest)) + + self.assertNotEqual(0, result.returncode) + self.assertIn( + "the identifier catalog is missing from the recorded stack.source_ref", + result.stderr, + ) + def test_validate_uses_identifier_catalog_from_existing_source_tag(self) -> None: with tempfile.TemporaryDirectory() as tmp: root = init_repo(Path(tmp)) diff --git a/release/scripts/test_release_workflow_structure.py b/release/scripts/test_release_workflow_structure.py index 645a647c58..bb3991e46b 100644 --- a/release/scripts/test_release_workflow_structure.py +++ b/release/scripts/test_release_workflow_structure.py @@ -2908,6 +2908,26 @@ def test_mirrors_one_digest_preserving_copy_behind_input_validation(self) -> Non class SupportingWorkflowStructureTest(unittest.TestCase): + def test_release_manifest_ci_uses_the_event_comparison_source(self) -> None: + _, document = workflow("ci.yml") + step = next( + item + for item in document["jobs"]["release-tool"]["steps"] + if item.get("name") == "Validate release manifest" + ) + self.assertEqual( + step["env"]["RELEASE_MANIFEST_BASE_REF"], + "${{ needs.changes.outputs.archive_base_ref }}", + ) + self.assertEqual( + step["env"]["RELEASE_MANIFEST_COMPARISON_REQUIRED"], + "${{ needs.changes.outputs.archive_comparison_required }}", + ) + run = step["run"] + self.assertIn("registry-release validate-current-ci", run) + self.assertIn('--base-ref "${RELEASE_MANIFEST_BASE_REF}"', run) + self.assertNotIn("registry-release validate-current\n", run) + def test_render_golden_pins_go_and_scopes_its_native_cache(self) -> None: _, document = workflow("render-golden.yml") assert_pinned_go(self, document, "golden") From e57dd408b4fdd37fc6c173d5d12238c9af1eabe0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 3 Dec 2026 11:56:39 +0000 Subject: [PATCH 02/33] docs(casework): clarify recovery for retained pinned reviews Signed-off-by: Jeremi Joslin --- .../src/content/docs/operate/casework.mdx | 47 ++++++++++++++----- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/docs/site/src/content/docs/operate/casework.mdx b/docs/site/src/content/docs/operate/casework.mdx index 4baea187c8..e2433c3d31 100644 --- a/docs/site/src/content/docs/operate/casework.mdx +++ b/docs/site/src/content/docs/operate/casework.mdx @@ -166,6 +166,16 @@ source headers on release. A Casework approval never applies a BReg Proposal. products/casework/generated/registry-casework.openapi.json, releaseReviewTask; crates/registry-casework/src/runtime.rs, build_context_providers(). */} +`caseworkctl provider add` uses the selected BReg human review profile's `principalClaim` when available. +Its fallback requires a single principal claim across the BReg access profiles. +The generated Casework human profiles and the producer's `trustedInitiatorPrincipalClaim` use that claim. +For `casework.provider-add.human-principal-claim-ambiguous`, set `principalClaim` on the human BReg profile that grants `get-review-context`. +You can also configure a single principal claim across the BReg access profiles. +Then rerun [`caseworkctl provider add`](../../configure/casework/#generate-the-policy-from-a-breg-action). + +{/* Evidence: crates/registry-caseworkctl/src/provider_add.rs, human-principal-claim-ambiguous, + trustedInitiatorPrincipalClaim, ambiguous_human_claim_refuses_before_writing_a_project. */} + ### Check the runtime file offline Check the authored project against the runtime file before anything touches a database: @@ -297,14 +307,26 @@ says the runtime credential can activate packages. ## Refuse a package that strands pinned work -An accepted review keeps the policy closure it was admitted under. A candidate that removes a -policy, producer, profile, team, queue, provider, or context contract an open review still needs is -refused with `casework.activation.stranded-work`, and so is a change to pinned policy content under -the same policy version. There is no override. Let the affected reviews finish, have their producer -cancel them, or prepare a successor that keeps what they need. +An accepted review keeps the policy closure it was admitted under. +`caseworkctl plan` and `caseworkctl apply` report `casework.activation.stranded-work` when a candidate strands pinned reviews. +Active reviews can still need their queues, reviewer profiles, bound producer, and current-source provider and contract. +Casework checks the pinned principal claim of a retained initiator even after the review settles. +Casework refuses activation if that claim changes or cannot be established. +If the candidate can preserve the required dependencies and claim, revise it and run `caseworkctl plan` again. + +Keep the previous compatible Casework release and package running on the existing database. +Let the affected active reviews finish there or have each review's bound producer cancel it. +For settled reviews, [keep the erasure worker running](../casework-retention/#keep-erasure-running) so it can remove the retained requests at accountability expiry. +Rerun `caseworkctl plan` and confirm the refusal has cleared before applying the candidate. + +If you need to start the candidate sooner, [provision a separate fresh database](#provision-postgresql) and apply the candidate there. +Earlier reviews stay with the compatible deployment for completion and retention. {/* Evidence: crates/registry-casework/src/pinned_work.rs, compare_pinned_work() and stranded_work_refusal(); - crates/registry-casework/src/activation.rs, stranded-work. */} + crates/registry-casework/src/activation.rs, stranded-work; + crates/registry-casework/src/store.rs, pinned_work_inventory_in(); + crates/registry-casework/src/review/maintenance.rs, erase_expired_reviews_at(); + crates/registry-casework/tests/review_postgres.rs, activation_preserves_the_claim_binding_of_retained_initiators. */} ## Plan, apply, and serve @@ -486,8 +508,10 @@ Run the operator preflight as the runtime user: caseworkctl doctor --runtime-config /etc/registry-casework/runtime.yaml ``` -Doctor checks the configuration, the package, the database activation, open reviews against the -configured package, and that the audit path is writable. It accepts the package already active. +Doctor checks the configuration, the package, and the database activation. +It also checks that the audit path is writable. +It checks the configured package against active reviews and retained initiator bindings. +It accepts the package already active. It warns when the serving teams cannot supply the distinct reviewers a stage requires; add eligible members and rerun it to confirm the warning clears. It opens no listener and proves no issuer or provider access; use `/ready` and an authenticated task read for those. @@ -500,9 +524,10 @@ provider access; use `/ready` and an authenticated task read for those. A running process keeps the package it started with and does not recheck the activation ledger, so a predecessor left serving after apply goes on admitting work under the old package. Take it out of your proxy's routing, stop every process serving it, then plan, apply, and start the successor -at once. The successor repeats the pinned-work check before it opens its listener. If it refuses -with `casework.activation.stranded-work`, plan and apply the predecessor again, serve it until the -named reviews finish or are cancelled, and retry the change. +at once. The successor repeats the pinned-work check before it opens its listener. +If startup reports stranded pinned reviews after apply, use the previous compatible release to plan and reapply its package. +Then restart its runtime. +Follow the [pinned-work recovery steps](#refuse-a-package-that-strands-pinned-work) before retrying the change. [Change an active package](../change-a-casework-package/) walks the plan and apply against a local session. From 133eb461aaddad242c3c1fb6c4ccdb11bdee80c9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 3 Dec 2026 11:58:45 +0000 Subject: [PATCH 03/33] docs(casework): clarify the retained initiator check Signed-off-by: Jeremi Joslin --- .../src/content/docs/reference/casework-configuration.mdx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/site/src/content/docs/reference/casework-configuration.mdx b/docs/site/src/content/docs/reference/casework-configuration.mdx index 8551724fbe..1014247a09 100644 --- a/docs/site/src/content/docs/reference/casework-configuration.mdx +++ b/docs/site/src/content/docs/reference/casework-configuration.mdx @@ -104,9 +104,11 @@ Set it to the digest that `caseworkctl package` printed for the package you revi ### Pinned work -Before activation, `caseworkctl plan` compares the candidate package with the in-flight reviews retained in the database. -`caseworkctl apply` refuses a package that removes a policy, profile, team, producer, provider or contract those reviews still need, or that changes pinned policy content under the same version. -Let the affected reviews finish under the active package before you apply the candidate. +Before activation, `caseworkctl plan` checks the candidate package against work retained in the database. +`caseworkctl apply` refuses a package that removes a policy, profile, team, producer, provider or contract that an active review needs. +It also refuses a change to pinned policy content under the same version. +Casework also checks the pinned principal claim of a retained initiator after the review settles. +If Casework refuses the candidate, follow the [pinned-work recovery steps](../../operate/casework/#refuse-a-package-that-strands-pinned-work) before retrying. `caseworkctl doctor` repeats the check for the active package. There is no override for orphaned work. From 447f5114b49fbae49f7dcfc901cb3ddc5876c618 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 3 Dec 2026 11:54:05 +0000 Subject: [PATCH 04/33] test(release): verify historical manifests with available source Signed-off-by: Jeremi Joslin --- release/scripts/test_registry_release.py | 61 ++++++++++++++++++++---- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/release/scripts/test_registry_release.py b/release/scripts/test_registry_release.py index 707c6de140..1326503ff8 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -5470,7 +5470,7 @@ def test_validate_does_not_require_thunderid_pin_through_beta_57(self) -> None: result = run_tool("validate", str(manifest)) self.assertNotIn("external.thunderid", result.stderr) - def test_validate_accepts_every_historical_manifest(self) -> None: + def test_validate_historical_manifests_against_available_source(self) -> None: registry_release = load_registry_release() for manifest in sorted((ROOT / "release/manifests").glob("registry-stack-*.yaml")): data = yaml.safe_load(manifest.read_text(encoding="utf-8")) @@ -5498,7 +5498,17 @@ def test_validate_accepts_every_historical_manifest(self) -> None: errors = io.StringIO() with redirect_stdout(io.StringIO()), redirect_stderr(errors): result = registry_release.validate_manifest_ci(manifest, None) - self.assertEqual(0, result, errors.getvalue()) + if manifest.name == "registry-stack-beta-32.yaml": + # The manifest was restored after the catalog changed. + # Only v0.21.0 binds it to the shipped catalog bytes. + self.assertEqual(1, result, errors.getvalue()) + self.assertEqual( + "error: identifier_catalog.sha256 does not match the " + "committed catalog bytes\n", + errors.getvalue(), + ) + else: + self.assertEqual(0, result, errors.getvalue()) def test_validate_current_ci_uses_inherited_source_and_refuses_proposed_drift( self, @@ -5929,14 +5939,49 @@ def test_validate_uses_identifier_catalog_from_existing_source_tag(self) -> None self.assertIn("does not match the committed catalog bytes", mismatched.stderr) def test_validate_copied_manifest_uses_tool_repository_source_tag(self) -> None: - source = ROOT / "release/manifests/registry-stack-beta-32.yaml" + registry_release = load_registry_release() with tempfile.TemporaryDirectory() as tmp: - copied = Path(tmp) / source.name - copied.write_bytes(source.read_bytes()) - result = run_tool("validate", str(copied)) + repo = Path(tmp) / "tool-repo" + repo.mkdir() + init_repo(repo) + catalog_path = registry_release.IDENTIFIER_CATALOG_RELATIVE_PATH + (repo / catalog_path).parent.mkdir(parents=True) + catalog_ref = commit_file( + repo, catalog_path, '{"entries": [{"id": "first", "status": "active"}]}\n' + ) + manifest = write_manifest(repo, version="0.19.1", source_ref=catalog_ref) + data = yaml.safe_load(manifest.read_text(encoding="utf-8")) + del data["stack"]["source_ref"] + del data["stack"]["status"] + prepared = yaml.safe_dump(data, sort_keys=False) + release_ref = commit_file(repo, manifest.name, prepared) + commit_file( + repo, catalog_path, '{"entries": [{"id": "second", "status": "active"}]}\n' + ) + commit_file(repo, manifest.name, prepared + "# restored release manifest\n") - self.assertEqual(0, result.returncode, result.stderr) - self.assertIn("validated", result.stdout) + errors = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(errors): + tagless = registry_release.validate_manifest_ci(manifest, None) + self.assertEqual(1, tagless, errors.getvalue()) + self.assertEqual( + "error: identifier_catalog.sha256 does not match the committed catalog bytes\n", + errors.getvalue(), + ) + + git(repo, "tag", "v0.19.1", release_ref) + copied = Path(tmp) / manifest.name + copied.write_bytes(manifest.read_bytes()) + output, errors = io.StringIO(), io.StringIO() + with ( + mock.patch.object(registry_release, "ROOT", repo), + redirect_stdout(output), + redirect_stderr(errors), + ): + tagged = registry_release.validate(copied) + + self.assertEqual(0, tagged, errors.getvalue()) + self.assertIn("validated", output.getvalue()) def test_relay_installer_joins_the_exact_inventory_after_v0_19_0(self) -> None: with tempfile.TemporaryDirectory() as tmp: From 38ba1bf82b2f0018fbe9e5c746c18a742f7f5d41 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 06:26:27 +0000 Subject: [PATCH 05/33] test(breg): cover rehearsal of a historical proposing hook Signed-off-by: Jeremi Joslin --- .../src/package/tests/predecessor_sources.rs | 122 +++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/crates/registry-breg/src/package/tests/predecessor_sources.rs b/crates/registry-breg/src/package/tests/predecessor_sources.rs index fe7d2f890e..f0ba7f0573 100644 --- a/crates/registry-breg/src/package/tests/predecessor_sources.rs +++ b/crates/registry-breg/src/package/tests/predecessor_sources.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -//! Predecessor packages whose stored sources this release cannot read. +//! Source compatibility for verified predecessor packages. #![cfg(feature = "tooling")] @@ -35,6 +35,126 @@ fn historical_member_grant(source: &mut Value) { }]); } +#[test] +fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { + let mut source = json!({ + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": {"id":"hook-rehearsal","version":"1","defaultLanguage":"en", + "canonicalBaseIri":"https://hook-rehearsal.example.test"}, + "package": {"sourceRevision":"hook-rehearsal-fixture"}, + "datasets": {"test-dataset": {}}, + "recordTypes": { + "entry": {"primaryDataset":"test-dataset","route":"entries","mutationMode":"create-only", + "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}], + "hooks":[{"id":"entry-created","phase":"after","trigger":"created","projection":["label"], + "handler":{"type":"url","destinationId":"observer"},"principal":"hook-worker"}]}, + "followup": {"primaryDataset":"test-dataset","route":"followups","mutationMode":"create-only", + "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}]} + }, + "actions": {"open-followup": {"execution":{"mode":"immediate"}, + "inputs":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}], + "plan":{"type":"fixed","effects":[{"id":"followup","target":{"recordType":"followup"}, + "operation":"create","set":{"label":{"fromInput":"label"}}}]}}}, + "accessProfiles": {"hook-worker": {"principalClaim":"principal","requiredScopes":"unrestricted", + "permissions":{"actions":[{"action":"open-followup","operations":["invoke"], + "targets":[{"recordType":"followup","rowBoundaries":"unrestricted"}],"results":["followup"]}]}}} + }); + source["accessProfiles"]["operator"] = source["accessProfiles"]["hook-worker"].clone(); + source["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); + let mut prepared = prepare_package(PackageBuildRequest { + from_package_digest: None, + compiler_source_revision: "hook-rehearsal-fixture".to_owned(), + schema_fingerprint: + "sha256:1111111111111111111111111111111111111111111111111111111111111111".to_owned(), + project: PackageSourceFile { + path: "source/project.yaml".to_owned(), + bytes: serde_json::to_vec(&source).unwrap(), + }, + modules: Vec::new(), + fixture_journeys: PackageSourceFile { + path: FIXTURE_JOURNEYS_PATH.to_owned(), + bytes: b"journeys: []".to_vec(), + }, + migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, + }) + .expect("the candidate compiles with a dedicated hook profile"); + + // Archive the earlier binding in the source and both generated inventories. + source["recordTypes"]["entry"]["hooks"][0]["principal"] = json!("operator"); + let source_bytes = serde_json::to_vec(&source).unwrap(); + let project = parse_project_yaml(&source_bytes).expect("the archived source parses"); + for profile in [CompileProfile::Authoring, CompileProfile::Production] { + let failure = compile_project_with_assets(&project, &[], &[], profile) + .expect_err("current compilation requires separate hook authority"); + let errors = failure + .diagnostics() + .iter() + .filter(|diagnostic| { + diagnostic.severity == crate::diagnostics::DiagnosticSeverity::Error + }) + .map(|diagnostic| diagnostic.code.as_str()) + .collect::>(); + assert_eq!(errors, ["breg.event.hook-authority-unsupported"]); + } + prepared + .files + .insert(prepared.manifest.sources.project.clone(), source_bytes); + edit_governed_model(&mut prepared, |model| { + model["recordTypes"]["entry"]["hooks"]["entry-created"]["principal"] = json!("operator"); + model["eventDeliveryInventory"]["deliveries"][0]["principal"] = json!("operator"); + }); + let events_path = unique_manifest_file(&prepared.manifest, PackageFileRole::EventInventory) + .unwrap() + .path + .clone(); + let mut events: Value = serde_json::from_slice(&prepared.files[&events_path]).unwrap(); + events["deliveries"][0]["principal"] = json!("operator"); + prepared + .files + .insert(events_path, canonicalize_json(&events).unwrap()); + for entry in &mut prepared.manifest.files { + *entry = file_entry(&entry.path, entry.role, &prepared.files[&entry.path]).unwrap(); + } + + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("package"); + let envelope = prepared + .publish_to_directory(&root) + .expect("the archived package seals"); + let context = PackageLoadContext { + posture: registry_platform_config::Posture::Production, + }; + assert_eq!( + load_package(&root, &context).err(), + Some(PackageError::Derivation) + ); + let (predecessor, reconstructed) = load_predecessor_rehearsal_baseline(&root, &context) + .expect("the verified predecessor still reconstructs for rehearsal"); + assert_eq!(predecessor.package_digest(), envelope.digest()); + assert_eq!( + predecessor.schema_fingerprint(), + prepared.manifest.schema_fingerprint + ); + assert_eq!(reconstructed.ddl(), prepared.registry.ddl()); + assert_eq!( + reconstructed.event_deliveries().deliveries[0] + .principal + .as_deref(), + Some("operator") + ); + + let diff = crate::tooling::classify_registry_diff( + &reconstructed.with_migration_baseline_schema(predecessor.migration_baseline()), + &prepared.registry, + predecessor.package_digest(), + ); + assert!(diff.changes.iter().any(|change| { + change.change.code == CompiledRegistryChangeCode::EventChanged + && change.change.target.member_id.as_deref() == Some("entry-created") + })); +} + #[test] fn predecessor_sources_refuse_current_membership_elsewhere_in_a_historical_file() { let mut previous = membership_source(); From 1d7566cf78479215ca9eb0a066adfbe21a6633f4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 06:27:59 +0000 Subject: [PATCH 06/33] test(breg): keep predecessor hook coverage in the tooling lane Signed-off-by: Jeremi Joslin --- .../registry-breg/src/package/tests/predecessor_sources.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/registry-breg/src/package/tests/predecessor_sources.rs b/crates/registry-breg/src/package/tests/predecessor_sources.rs index f0ba7f0573..efd30b7c89 100644 --- a/crates/registry-breg/src/package/tests/predecessor_sources.rs +++ b/crates/registry-breg/src/package/tests/predecessor_sources.rs @@ -136,6 +136,10 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { predecessor.schema_fingerprint(), prepared.manifest.schema_fingerprint ); + assert_eq!( + reconstructed.entities(), + &predecessor.migration_baseline().entities + ); assert_eq!(reconstructed.ddl(), prepared.registry.ddl()); assert_eq!( reconstructed.event_deliveries().deliveries[0] @@ -145,7 +149,7 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { ); let diff = crate::tooling::classify_registry_diff( - &reconstructed.with_migration_baseline_schema(predecessor.migration_baseline()), + &reconstructed, &prepared.registry, predecessor.package_digest(), ); From de4b9695f4b9fe6e1f30965656886d9542c9fa01 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 07:32:42 +0000 Subject: [PATCH 07/33] fix(breg): restore rehearsal of predecessor hook bindings Keep caller-dependent historical profile bindings available for schema reconstruction through the existing verified predecessor rules. Retain the current compiler refusal and the requirement that a binding names an existing profile. Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/compiler.rs | 17 +++++++++++------ .../src/package/tests/predecessor_sources.rs | 9 ++++++++- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 69ed40dff8..f93797eb0c 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -250,6 +250,7 @@ pub fn compile_project_with_assets( /// Reconstruct the schema of a verified predecessor for migration rehearsal. /// A v0.51.0 package can declare writable references without target grants. +/// It can also bind a proposing hook to a caller-dependent project profile. #[cfg(feature = "tooling")] pub(crate) fn compile_verified_predecessor_for_rehearsal( project: &RegistryProject, @@ -362,6 +363,7 @@ fn compile_with_source_rules( &sources, &project.access_profiles, &origins.hook_paths, + source_rules, &mut diagnostics, ); validate_module_access_profile_task_grants(&sources, &mut diagnostics); @@ -4071,11 +4073,13 @@ fn validate_project_entity_access_profiles( /// explicit binding to one project access profile, but the worker has no /// verified token scopes, purpose, actor, OAuth client, or task grant to /// satisfy caller-dependent conditions on that profile. Refuse such a -/// binding during authoring instead of manufacturing claims at delivery. +/// binding when compiling current sources. Rehearsal retains historical +/// bindings to existing profiles for schema reconstruction and comparison. fn validate_hook_proposal_authorities( entities: &BTreeMap, profiles: &[ProjectAccessProfileSource], hook_paths: &HookPathMap, + source_rules: SourceRules, errors: &mut Vec, ) { let profiles = profiles @@ -4099,11 +4103,12 @@ fn validate_hook_proposal_authorities( )); continue; }; - if !profile.required_scopes.is_empty() - || !profile.required_purposes.is_empty() - || profile.actor_kind.is_some() - || !profile.requester_clients.is_empty() - || profile.task_grant.is_some() + if source_rules == SourceRules::Current + && (!profile.required_scopes.is_empty() + || !profile.required_purposes.is_empty() + || profile.actor_kind.is_some() + || !profile.requester_clients.is_empty() + || profile.task_grant.is_some()) { errors.push(Diagnostic::error( "breg.event.hook-authority-unsupported", diff --git a/crates/registry-breg/src/package/tests/predecessor_sources.rs b/crates/registry-breg/src/package/tests/predecessor_sources.rs index efd30b7c89..5e0afd5044 100644 --- a/crates/registry-breg/src/package/tests/predecessor_sources.rs +++ b/crates/registry-breg/src/package/tests/predecessor_sources.rs @@ -125,6 +125,9 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { let context = PackageLoadContext { posture: registry_platform_config::Posture::Production, }; + let verified = load_predecessor_package(&root, &context) + .expect("the archive is eligible for ordinary predecessor planning"); + assert_eq!(verified.package_digest(), envelope.digest()); assert_eq!( load_package(&root, &context).err(), Some(PackageError::Derivation) @@ -138,7 +141,11 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { ); assert_eq!( reconstructed.entities(), - &predecessor.migration_baseline().entities + &verified.migration_baseline().entities + ); + assert_eq!( + reconstructed.actions(), + &verified.migration_baseline().actions ); assert_eq!(reconstructed.ddl(), prepared.registry.ddl()); assert_eq!( From 717d38e01d97729dd358cdb4741d4dc0b62ad7de Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 07:33:42 +0000 Subject: [PATCH 08/33] test(breg): admit hook HTTP boundary fixtures under current profiles Signed-off-by: Jeremi Joslin --- .../src/api/tests/immediate_action_tests.rs | 12 +++++++++--- crates/registry-breg/tests/http_auth.rs | 15 +++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index caa1ca1dc6..9ed056d54b 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -103,6 +103,9 @@ fn compiled() -> Arc { #[tokio::test] async fn internal_hook_profile_is_excluded_from_action_invoke_http_authority() { let mut project = parse_project_yaml(PROJECT.as_bytes()).expect("action fixture parses"); + project.package = Some(crate::contract::PackageIdentitySource { + source_revision: "action-admission-hook-fixture".to_owned(), + }); project.entities[0].hooks.push( serde_json::from_value(json!({ "id": "case-created", @@ -122,7 +125,10 @@ async fn internal_hook_profile_is_excluded_from_action_invoke_http_authority() { "permissions": {"actions": [{ "action": "rename-case", "operations": ["invoke"], - "targets": [{"recordType": "case", "rowBoundaries": "unrestricted"}], + "targets": [{ + "recordType": "case", + "rowBoundaries": [{"field": "id", "claim": "registry_principal", "operator": "equals"}] + }], "results": ["renamed"] }]} })) @@ -170,7 +176,7 @@ async fn internal_hook_profile_is_excluded_from_action_invoke_http_authority() { "aud": audience, "sub": "ordinary-registrar", "azp": "agent-client", - "registry_principal": "ordinary-registrar", + "registry_principal": "00000000-0000-4000-8000-000000000001", "registry_purpose": "case-management", "regions": ["north"], "scope": "case.rename" @@ -183,7 +189,7 @@ async fn internal_hook_profile_is_excluded_from_action_invoke_http_authority() { "aud": audience, "sub": "hook-caller", "azp": "agent-client", - "registry_principal": "hook-caller", + "registry_principal": "00000000-0000-4000-8000-000000000002", "scope": "hook.invoke" })); let denied = send(hook, "hook-worker").await.expect("router responds"); diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index aaf54426e7..f14889bee8 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -189,6 +189,8 @@ project: version: 0.1.0 defaultLanguage: en canonicalBaseIri: https://authoring.example.test +package: + sourceRevision: proposing-hook-profile-fixture datasets: cases: {} recordTypes: @@ -243,12 +245,15 @@ accessProfiles: - recordType: case operations: [get] readableFields: [label] - rowBoundaries: unrestricted + rowBoundaries: + - {field: id, claim: registry_principal, operator: equals} actions: - action: open-followup operations: [invoke] targets: - - {recordType: followup, rowBoundaries: unrestricted} + - recordType: followup + rowBoundaries: + - {field: id, claim: registry_principal, operator: equals} results: [followup] "#; @@ -4649,7 +4654,9 @@ async fn authenticator_construction_refuses_an_explicit_proposing_hook_profile() #[tokio::test] async fn an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes() { let harness = Harness::with_source(PROPOSING_HOOK_PROFILE_PROJECT).await; - let ordinary = harness.valid_token(); + let mut ordinary_claims = valid_claims(); + ordinary_claims["registry_principal"] = json!(RECORD_ID); + let ordinary = harness.idp.mint_token(ordinary_claims); let response = harness .send( &format!("/v1/records/cases/{RECORD_ID}"), @@ -4664,7 +4671,7 @@ async fn an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes() { json!({ "aud": AUDIENCE, "registry_actor_kind": "service", - "registry_principal": PRINCIPAL, + "registry_principal": RECORD_ID, "scope": "hook.invoke", "purpose": "hook-response" }), From 85992cd60062feb3ce6bcb53f134013329a00bce Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 07:42:13 +0000 Subject: [PATCH 09/33] fix(breg): bind the observer fixture to an independent hook profile Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/postgres_proposal_hooks.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/registry-breg/tests/postgres_proposal_hooks.rs b/crates/registry-breg/tests/postgres_proposal_hooks.rs index cd19054442..d45d890876 100644 --- a/crates/registry-breg/tests/postgres_proposal_hooks.rs +++ b/crates/registry-breg/tests/postgres_proposal_hooks.rs @@ -497,7 +497,11 @@ async fn native_observers_refuse_callback_candidates_before_action_grant_lookup( #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn native_observer_candidates_have_no_application_authority_even_under_a_forged_owner() { let mut source = model::source(json!([model::local_hook("candidate", json!(["started"]))])); - source["recordTypes"]["target"]["hooks"] = json!([{"id":"record-candidate","phase":"after","trigger":"created","projection":["name"],"principal":"clerk","handler":{"type":"rhai","script":"hooks/candidate.rhai","abi":"registry.hook-handler/v1"}}]); + source["accessProfiles"]["record-hook"] = json!({ + "principalClaim": "sub", + "requiredScopes": "unrestricted" + }); + source["recordTypes"]["target"]["hooks"] = json!([{"id":"record-candidate","phase":"after","trigger":"created","projection":["name"],"principal":"record-hook","handler":{"type":"rhai","script":"hooks/candidate.rhai","abi":"registry.hook-handler/v1"}}]); let registry = compile(source, &[("candidate", CANDIDATE)]); let (_root, destinations) = runtime(®istry, None); let fixture = client_http::ClientFixture::start(registry, claims()).await; @@ -505,7 +509,7 @@ async fn native_observer_candidates_have_no_application_authority_even_under_a_f let native_id = "events.proposals.correct-name.candidate.webhook"; let forged_id = "events.target.record-candidate.webhook"; // The migrated outbox contract remains native even if an adversarial row - // substitutes a compiled Record owner with a proposing principal. + // substitutes a compiled Record owner with an authored hook principal. fixture.database.admin.execute("INSERT INTO registry_internal.registry_webhook_deliveries SELECT (jsonb_populate_record(NULL::registry_internal.registry_webhook_deliveries,to_jsonb(d)||jsonb_build_object('compiled_delivery_id',$2::text))).* FROM registry_internal.registry_webhook_deliveries d WHERE compiled_delivery_id=$1",&[&native_id,&forged_id]).await.unwrap(); fixture.database.admin.execute("INSERT INTO registry_internal.registry_webhook_delivery_state SELECT (jsonb_populate_record(NULL::registry_internal.registry_webhook_delivery_state,to_jsonb(s)||jsonb_build_object('compiled_delivery_id',$2::text))).* FROM registry_internal.registry_webhook_delivery_state s WHERE compiled_delivery_id=$1",&[&native_id,&forged_id]).await.unwrap(); fixture.database.admin.execute("DELETE FROM registry_internal.registry_webhook_delivery_state WHERE compiled_delivery_id=$1",&[&native_id]).await.unwrap(); From a0c112e228f257a4686c63b4906b7d2953421944 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:17:09 +0000 Subject: [PATCH 10/33] test(breg): cover proposing hook authority with plain Action grants Signed-off-by: Jeremi Joslin --- .../src/api/tests/immediate_action_tests.rs | 2 +- .../src/package/tests/predecessor_sources.rs | 88 ++++-------- .../registry-breg/tests/compiler_webhook.rs | 35 ++++- crates/registry-breg/tests/http_auth.rs | 3 +- .../tests/membership_authoring.rs | 2 + .../tests/postgres_hook_changes.rs | 131 +++++++++--------- 6 files changed, 132 insertions(+), 129 deletions(-) diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index 9ed056d54b..6bbf08f763 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -127,7 +127,7 @@ async fn internal_hook_profile_is_excluded_from_action_invoke_http_authority() { "operations": ["invoke"], "targets": [{ "recordType": "case", - "rowBoundaries": [{"field": "id", "claim": "registry_principal", "operator": "equals"}] + "rowBoundaries": "unrestricted" }], "results": ["renamed"] }]} diff --git a/crates/registry-breg/src/package/tests/predecessor_sources.rs b/crates/registry-breg/src/package/tests/predecessor_sources.rs index 5e0afd5044..3548d78310 100644 --- a/crates/registry-breg/src/package/tests/predecessor_sources.rs +++ b/crates/registry-breg/src/package/tests/predecessor_sources.rs @@ -62,64 +62,34 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { }); source["accessProfiles"]["operator"] = source["accessProfiles"]["hook-worker"].clone(); source["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); - let mut prepared = prepare_package(PackageBuildRequest { - from_package_digest: None, - compiler_source_revision: "hook-rehearsal-fixture".to_owned(), - schema_fingerprint: - "sha256:1111111111111111111111111111111111111111111111111111111111111111".to_owned(), - project: PackageSourceFile { - path: "source/project.yaml".to_owned(), - bytes: serde_json::to_vec(&source).unwrap(), - }, - modules: Vec::new(), - fixture_journeys: PackageSourceFile { - path: FIXTURE_JOURNEYS_PATH.to_owned(), - bytes: b"journeys: []".to_vec(), - }, - migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, - }) - .expect("the candidate compiles with a dedicated hook profile"); + let prepare = |source: &Value| { + prepare_package(PackageBuildRequest { + from_package_digest: None, + compiler_source_revision: "hook-rehearsal-fixture".to_owned(), + schema_fingerprint: + "sha256:1111111111111111111111111111111111111111111111111111111111111111".to_owned(), + project: PackageSourceFile { + path: "source/project.yaml".to_owned(), + bytes: serde_json::to_vec(source).unwrap(), + }, + modules: Vec::new(), + fixture_journeys: PackageSourceFile { + path: FIXTURE_JOURNEYS_PATH.to_owned(), + bytes: b"journeys: []".to_vec(), + }, + migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, + }) + }; + let candidate = prepare(&source).expect("the candidate compiles with a plain hook grant"); - // Archive the earlier binding in the source and both generated inventories. + // Archive a historical binding that carries a scope on its Action grant. source["recordTypes"]["entry"]["hooks"][0]["principal"] = json!("operator"); - let source_bytes = serde_json::to_vec(&source).unwrap(); - let project = parse_project_yaml(&source_bytes).expect("the archived source parses"); - for profile in [CompileProfile::Authoring, CompileProfile::Production] { - let failure = compile_project_with_assets(&project, &[], &[], profile) - .expect_err("current compilation requires separate hook authority"); - let errors = failure - .diagnostics() - .iter() - .filter(|diagnostic| { - diagnostic.severity == crate::diagnostics::DiagnosticSeverity::Error - }) - .map(|diagnostic| diagnostic.code.as_str()) - .collect::>(); - assert_eq!(errors, ["breg.event.hook-authority-unsupported"]); - } - prepared - .files - .insert(prepared.manifest.sources.project.clone(), source_bytes); - edit_governed_model(&mut prepared, |model| { - model["recordTypes"]["entry"]["hooks"]["entry-created"]["principal"] = json!("operator"); - model["eventDeliveryInventory"]["deliveries"][0]["principal"] = json!("operator"); - }); - let events_path = unique_manifest_file(&prepared.manifest, PackageFileRole::EventInventory) - .unwrap() - .path - .clone(); - let mut events: Value = serde_json::from_slice(&prepared.files[&events_path]).unwrap(); - events["deliveries"][0]["principal"] = json!("operator"); - prepared - .files - .insert(events_path, canonicalize_json(&events).unwrap()); - for entry in &mut prepared.manifest.files { - *entry = file_entry(&entry.path, entry.role, &prepared.files[&entry.path]).unwrap(); - } + source["accessProfiles"]["hook-worker"]["requiredScopes"] = json!(["hooks:invoke"]); + let archived = prepare(&source).expect("the archived configuration compiles"); let directory = tempfile::tempdir().unwrap(); let root = directory.path().join("package"); - let envelope = prepared + let envelope = archived .publish_to_directory(&root) .expect("the archived package seals"); let context = PackageLoadContext { @@ -128,16 +98,18 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { let verified = load_predecessor_package(&root, &context) .expect("the archive is eligible for ordinary predecessor planning"); assert_eq!(verified.package_digest(), envelope.digest()); + let active = load_package(&root, &context).expect("current derivation accepts the binding"); + assert_eq!(active.package_digest(), envelope.digest()); assert_eq!( - load_package(&root, &context).err(), - Some(PackageError::Derivation) + active.registry().event_deliveries(), + archived.registry.event_deliveries() ); let (predecessor, reconstructed) = load_predecessor_rehearsal_baseline(&root, &context) .expect("the verified predecessor still reconstructs for rehearsal"); assert_eq!(predecessor.package_digest(), envelope.digest()); assert_eq!( predecessor.schema_fingerprint(), - prepared.manifest.schema_fingerprint + archived.manifest.schema_fingerprint ); assert_eq!( reconstructed.entities(), @@ -147,7 +119,7 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { reconstructed.actions(), &verified.migration_baseline().actions ); - assert_eq!(reconstructed.ddl(), prepared.registry.ddl()); + assert_eq!(reconstructed.ddl(), archived.registry.ddl()); assert_eq!( reconstructed.event_deliveries().deliveries[0] .principal @@ -157,7 +129,7 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { let diff = crate::tooling::classify_registry_diff( &reconstructed, - &prepared.registry, + &candidate.registry, predecessor.package_digest(), ); assert!(diff.changes.iter().any(|change| { diff --git a/crates/registry-breg/tests/compiler_webhook.rs b/crates/registry-breg/tests/compiler_webhook.rs index 94a110f3c4..9c7ebf3be9 100644 --- a/crates/registry-breg/tests/compiler_webhook.rs +++ b/crates/registry-breg/tests/compiler_webhook.rs @@ -80,6 +80,7 @@ fn webhook_mut(value: &mut Value) -> &mut serde_json::Map { fn proposal_hook_project_value() -> Value { let mut source = project_value(); + source["package"] = json!({"sourceRevision": "proposing-hook-contract-fixture"}); source["recordTypes"]["case"]["hooks"][0]["principal"] = json!("case-hook"); source["recordTypes"]["followup"] = json!({ "primaryDataset": "test-dataset", @@ -134,7 +135,7 @@ fn proposal_hook_project_value() -> Value { } #[test] -fn proposal_hook_authority_requires_a_caller_independent_profile() { +fn proposing_hook_profile_binding_preserves_authored_caller_requirements() { for (member, value) in [ ("requiredScopes", json!(["registry.write"])), ("requiredPurposes", json!(["case-management"])), @@ -142,17 +143,26 @@ fn proposal_hook_authority_requires_a_caller_independent_profile() { ("requesterClients", json!(["case-worker"])), ] { let mut source = proposal_hook_project_value(); - source["accessProfiles"]["case-hook"][member] = value; - assert_compile_code(&source, "breg.event.hook-authority-unsupported"); + source["accessProfiles"]["case-hook"][member] = value.clone(); + let compiled = compile(&source).expect("profile binding compiles with caller requirements"); + assert_eq!( + compiled.event_deliveries().deliveries[0] + .principal + .as_deref(), + Some("case-hook") + ); + let grant = &compiled.actions().actions[0].permissions[0]; + let authored = serde_json::to_value(grant).expect("compiled grant serializes"); + assert_eq!(authored[member], value); } } #[test] -fn proposal_hook_authority_refuses_task_grant_approval() { +fn proposing_hook_profiles_still_require_valid_task_grant_bindings() { let mut source = proposal_hook_project_value(); source["accessProfiles"]["case-hook"]["taskGrant"] = json!({"sourceIssuer": "https://task-authority.example.test"}); - assert_compile_code(&source, "breg.event.hook-authority-unsupported"); + assert_compile_code(&source, "breg.access-profile.task-grant-binding-required"); } #[test] @@ -175,7 +185,7 @@ fn proposal_hook_authority_must_bind_an_existing_profile() { #[test] fn proposal_hook_accepts_a_bounded_profile_and_keeps_its_authored_binding() { let compiled = compile(&proposal_hook_project_value()) - .expect("a caller-independent hook action grant compiles"); + .expect("a hook profile with a plain Action grant compiles"); let delivery = &compiled.event_deliveries().deliveries[0]; assert_eq!(delivery.principal.as_deref(), Some("case-hook")); let action = compiled @@ -195,6 +205,19 @@ fn proposal_hook_accepts_a_bounded_profile_and_keeps_its_authored_binding() { assert!(grant.actor_kind.is_none()); assert!(grant.requester_clients.is_empty()); assert!(grant.task_grant.is_none()); + assert_eq!(grant.targets.len(), 1); + assert!(grant.targets[0].row_boundaries.is_empty()); + assert!(grant.targets[0].membership_boundaries.is_empty()); +} + +#[test] +fn an_open_http_action_grant_still_requires_a_principal_boundary() { + let mut source = proposal_hook_project_value(); + source["recordTypes"]["case"]["hooks"][0] + .as_object_mut() + .expect("hook object") + .remove("principal"); + assert_compile_code(&source, "breg.access.open-write-without-principal-boundary"); } #[test] diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index f14889bee8..a2d7922e23 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -252,8 +252,7 @@ accessProfiles: operations: [invoke] targets: - recordType: followup - rowBoundaries: - - {field: id, claim: registry_principal, operator: equals} + rowBoundaries: unrestricted results: [followup] "#; diff --git a/crates/registry-breg/tests/membership_authoring.rs b/crates/registry-breg/tests/membership_authoring.rs index 43dc642aad..bdeaacd869 100644 --- a/crates/registry-breg/tests/membership_authoring.rs +++ b/crates/registry-breg/tests/membership_authoring.rs @@ -330,6 +330,8 @@ fn production_admits_a_membership_bound_immediate_action_target() { fn a_hook_cannot_use_an_action_grant_with_membership() { let mut project = action_project(); project["recordTypes"]["child"]["hooks"][0]["principal"] = json!("registrar"); + project["recordTypes"]["child"]["hooks"][0]["handler"] = + json!({"type":"url","destinationId":"record-events"}); project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); assert_refusal(&project, "breg.access.membership-hook-unsupported", diff --git a/crates/registry-breg/tests/postgres_hook_changes.rs b/crates/registry-breg/tests/postgres_hook_changes.rs index 58a84bd0a4..ac7b36f3e2 100644 --- a/crates/registry-breg/tests/postgres_hook_changes.rs +++ b/crates/registry-breg/tests/postgres_hook_changes.rs @@ -35,7 +35,7 @@ use registry_breg::field_encryption::{FieldEncryptionProvider, FieldEncryptionSe use registry_breg::hooks::{ HookDeliveryError, HookDeliveryService, HookRetainedBindingError, HookWorkOutcome, }; -use registry_breg::model::{CompiledActionPermission, CompiledRegistry}; +use registry_breg::model::CompiledRegistry; use registry_breg::mutation::{MutationBody, MutationPlan, MutationRequest, MutationTransaction}; use registry_breg::postgres::{ initialize_compiled_registry_state_with_posture_for_test, install_compiled_schema, @@ -146,6 +146,7 @@ fn hook_project_json( "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", "kind":"BRegProject", "project":{{"id":"hook-proposal-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://authoring.example.test"}}, + "package":{{"sourceRevision":"hook-proposal-fixture"}}, "datasets":{{"test-dataset": {{}}}}, "recordTypes":{{"case":{{"primaryDataset":"test-dataset","route":"cases","mutationMode":"create-only","classification":"restricted", "fields":[ @@ -184,7 +185,7 @@ fn hook_project_json( "rowBoundaries":[{{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}}] }}]}} }},"case-hook":{{ - "principalClaim":"registry_principal","requiredScopes":["records:write"], + "principalClaim":"registry_principal","requiredScopes":"unrestricted", "permissions":{{"actions":[{{ "action":"open-followup","operations":["invoke"], "targets":[{{"recordType":"followup","rowBoundaries":"unrestricted"}}], @@ -240,12 +241,19 @@ fn compile_proposal_registry_with_grant( hook_project_json(case_hooks, followup_hooks, case_hook_results, extra_writes).as_bytes(), ) .expect("hook proposal fixture parses"); + compile_hook_registry(&project, hook_assets) +} + +fn compile_hook_registry( + project: ®istry_breg::contract::RegistryProject, + hook_assets: &[ModuleAssetSource], +) -> CompiledRegistry { let mut assets = vec![rhai_asset( "scripts/open-followup.rhai", ACTION_HANDLER_SCRIPT, )]; assets.extend(hook_assets.iter().cloned()); - compile_project_with_assets(&project, &[], &assets, CompileProfile::Authoring) + compile_project_with_assets(project, &[], &assets, CompileProfile::Authoring) .expect("hook proposal fixture compiles") } @@ -263,21 +271,6 @@ fn proposal_registry() -> CompiledRegistry { ) } -/// Models a loaded compiled package whose action grant no longer matches the -/// caller-independent hook authority the authoring compiler accepted. The -/// live apply path must independently refuse it before any Record mutation. -fn proposal_registry_with_substituted_grant( - constrain: fn(&mut CompiledActionPermission), -) -> CompiledRegistry { - let mut compiled = proposal_registry(); - constrain( - compiled - .action_grant_mut_for_test("open-followup", "case-hook") - .expect("the compiled hook grant exists"), - ); - compiled -} - /// The standard proposal registry with the action's `origin` target sealed /// at rest. The proposal still carries plaintext process-local input; only /// the committed field changes storage shape. @@ -359,13 +352,9 @@ fn dispositions_registry() -> CompiledRegistry { } fn principal_less_registry() -> CompiledRegistry { - compile_proposal_registry( - &format!( - "[{}]", - hook_json("principal-less-proposer", false, PROPOSING_RHAI_HANDLER) - ), - "[]", - &[rhai_asset("hooks/propose.rhai", PROPOSAL_HOOK_SCRIPT)], + compile_notification_registry( + &hook_json("principal-less-proposer", false, PROPOSING_RHAI_HANDLER), + rhai_asset("hooks/propose.rhai", PROPOSAL_HOOK_SCRIPT), ) } @@ -388,20 +377,31 @@ fn invalid_proposal_registry() -> CompiledRegistry { } fn silent_registry() -> CompiledRegistry { - compile_proposal_registry( - &format!( - "[{}]", - hook_json( - "silent-observer", - false, - r#"{"type":"rhai","script":"hooks/silent.rhai","abi":"registry.hook-handler/v1"}"# - ) + compile_notification_registry( + &hook_json( + "silent-observer", + false, + r#"{"type":"rhai","script":"hooks/silent.rhai","abi":"registry.hook-handler/v1"}"#, ), - "[]", - &[rhai_asset("hooks/silent.rhai", SILENT_HOOK_SCRIPT)], + rhai_asset("hooks/silent.rhai", SILENT_HOOK_SCRIPT), ) } +fn compile_notification_registry(hook: &str, asset: ModuleAssetSource) -> CompiledRegistry { + let mut source: Value = serde_json::from_str(&hook_project_json( + &format!("[{hook}]"), + "[]", + r#""results":["followup"]"#, + "", + )) + .expect("notification fixture is JSON"); + // Without a bound hook this is an ordinary profile. Keep Invoke scoped. + source["accessProfiles"]["case-hook"]["requiredScopes"] = json!(["records:write"]); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect("notification fixture parses"); + compile_hook_registry(&project, &[asset]) +} + /// The hidden-result journey registry: the action declares a second write slot /// the proposal never applies, and the `case-hook` grant's result set names /// only that slot. The grant is legal and nonempty, but its disclosure @@ -2625,26 +2625,33 @@ async fn real_postgres_a_proposal_without_a_declared_principal_is_dead_lettered_ #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_a_loaded_hook_grant_requiring_caller_context_is_refused_without_mutation() { - type Constraint = fn(&mut CompiledActionPermission); - let constraints: [(&str, Constraint); 4] = [ - ("scope", |grant| { - assert!(grant.required_scopes.insert("registry.write".to_owned())); - }), - ("actor kind", |grant| { - assert!(grant.actor_kind.is_none()); - grant.actor_kind = Some(registry_breg::contract::ActorKindSource::Service); - }), - ("purpose", |grant| { - assert!(grant.required_purposes.insert("case-management".to_owned())); - }), - ("requester client", |grant| { - assert!(grant.requester_clients.insert("hook-client".to_owned())); - }), - ]; - for (case, constrain) in constraints { + let hooks = format!( + "[{}]", + hook_json("case-created", true, PROPOSING_RHAI_HANDLER) + ); + let source: Value = serde_json::from_str(&hook_project_json( + &hooks, + "[]", + r#""results":["followup"]"#, + "", + )) + .expect("hook proposal fixture is JSON"); + for (member, value) in [ + ("requiredScopes", json!(["registry.write"])), + ("actorKind", json!("service")), + ("requiredPurposes", json!(["case-management"])), + ("requesterClients", json!(["hook-client"])), + ] { + let mut source = source.clone(); + source["accessProfiles"]["case-hook"][member] = value; + let project = + parse_project_json(&serde_json::to_vec(&source).unwrap()).expect("hook fixture parses"); let receiver = HttpsReceiver::start().await; let setup = setup( - proposal_registry_with_substituted_grant(constrain), + compile_hook_registry( + &project, + &[rhai_asset("hooks/propose.rhai", PROPOSAL_HOOK_SCRIPT)], + ), &receiver, false, ) @@ -2654,35 +2661,35 @@ async fn real_postgres_a_loaded_hook_grant_requiring_caller_context_is_refused_w .get_for_test() .await .expect("runtime mutation connection is available"); - let event = create_case(&setup, &mut mutation_client, case).await; + let event = create_case(&setup, &mut mutation_client, member).await; let delivery_id = single_delivery(&event).to_owned(); drop(mutation_client); assert_eq!( setup.service.deliver_once().await, Ok(HookWorkOutcome::Delivered), - "{case}: the incompatible proposal settles as a refusal" + "{member}: the incompatible proposal settles as a refusal" ); let row = delivery_row(&setup, event.event_id, &delivery_id).await; - assert_eq!(row.state, "delivered", "{case}"); - assert_eq!(row.disposition.as_deref(), Some("refused"), "{case}"); - assert_eq!(row.resulting_revision, None, "{case}"); + assert_eq!(row.state, "delivered", "{member}"); + assert_eq!(row.disposition.as_deref(), Some("refused"), "{member}"); + assert_eq!(row.resulting_revision, None, "{member}"); assert_eq!( row.code.as_deref(), Some("hook.proposal.unauthorized"), - "{case}" + "{member}" ); assert_eq!( row.summary.as_deref(), Some("The declared principal's grant requires caller context a hook does not carry."), - "{case}: the live hook-authority guard produced the refusal" + "{member}: the live hook-authority guard produced the refusal" ); assert_eq!( record_count(&setup, "followup").await, 0, - "{case}: a caller-dependent hook grant applies no Record mutation" + "{member}: a caller-dependent hook grant applies no Record mutation" ); - assert_eq!(record_count(&setup, "case").await, 1, "{case}"); + assert_eq!(record_count(&setup, "case").await, 1, "{member}"); setup.teardown().await; receiver.stop().await; From e9a64eeadf90842e1f1b2b89ab93923b87c7e148 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:21:42 +0000 Subject: [PATCH 11/33] fix(breg): admit open write grants for reserved hook profiles Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/compiler.rs | 61 +++++++++---------- crates/registry-breg/src/immediate_actions.rs | 22 ++++++- crates/registry-breg/src/membership.rs | 22 +++---- crates/registry-breg/src/model.rs | 19 ------ .../content/docs/configure/breg-access.mdx | 4 +- .../content/docs/operate/breg-webhooks.mdx | 33 +++++----- docs/site/src/content/docs/security/breg.mdx | 26 ++++---- .../contracts/security-invariant-matrix.yaml | 7 ++- .../contracts/security-test-traceability.yaml | 4 ++ 9 files changed, 101 insertions(+), 97 deletions(-) diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index f93797eb0c..42c5723f92 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -250,7 +250,6 @@ pub fn compile_project_with_assets( /// Reconstruct the schema of a verified predecessor for migration rehearsal. /// A v0.51.0 package can declare writable references without target grants. -/// It can also bind a proposing hook to a caller-dependent project profile. #[cfg(feature = "tooling")] pub(crate) fn compile_verified_predecessor_for_rehearsal( project: &RegistryProject, @@ -359,11 +358,10 @@ fn compile_with_source_rules( &mut diagnostics, ); validate_project_entity_access_profiles(project, &mut diagnostics); - validate_hook_proposal_authorities( + let hook_profiles = validate_hook_proposal_authorities( &sources, &project.access_profiles, &origins.hook_paths, - source_rules, &mut diagnostics, ); validate_module_access_profile_task_grants(&sources, &mut diagnostics); @@ -387,7 +385,13 @@ fn compile_with_source_rules( source_rules == SourceRules::Current, &mut diagnostics, ); - crate::membership::validate(project, &action_sources, &sources, &mut diagnostics); + crate::membership::validate( + project, + &action_sources, + &sources, + &hook_profiles, + &mut diagnostics, + ); crate::proposal_subject::validate_field_writes( project, &action_sources, @@ -481,6 +485,7 @@ fn compile_with_source_rules( &project.review_authorities, project, &timer_actions, + &hook_profiles, ) .map_err(|errors| { stopped_compile_failure( @@ -4069,33 +4074,32 @@ fn validate_project_entity_access_profiles( } } -/// A Record hook is not an HTTP caller. Its authored `principal` is an -/// explicit binding to one project access profile, but the worker has no -/// verified token scopes, purpose, actor, OAuth client, or task grant to -/// satisfy caller-dependent conditions on that profile. Refuse such a -/// binding when compiling current sources. Rehearsal retains historical -/// bindings to existing profiles for schema reconstruction and comparison. -fn validate_hook_proposal_authorities( +/// A proposing Record hook binds an existing project access profile. Only +/// hooks with handlers enter the delivery inventory, whose principal bindings +/// authentication excludes from every HTTP issuer. +fn validate_hook_proposal_authorities<'a>( entities: &BTreeMap, - profiles: &[ProjectAccessProfileSource], + profiles: &'a [ProjectAccessProfileSource], hook_paths: &HookPathMap, - source_rules: SourceRules, errors: &mut Vec, -) { +) -> BTreeSet<&'a str> { let profiles = profiles .iter() - .map(|profile| (profile.id.as_str(), profile)) - .collect::>(); + .map(|profile| profile.id.as_str()) + .collect::>(); + let mut hook_profiles = BTreeSet::new(); for entity in entities.values() { for hook in &entity.hooks { let Some(principal) = hook.principal.as_deref() else { continue; }; - let hook_path = hook_paths - .get(&(entity.id.clone(), hook.id.clone())) - .cloned() - .unwrap_or_else(|| format!("recordTypes[id={}].hooks[id={}]", entity.id, hook.id)); - let Some(profile) = profiles.get(principal) else { + let Some(&profile_id) = profiles.get(principal) else { + let hook_path = hook_paths + .get(&(entity.id.clone(), hook.id.clone())) + .cloned() + .unwrap_or_else(|| { + format!("recordTypes[id={}].hooks[id={}]", entity.id, hook.id) + }); errors.push(Diagnostic::error( "breg.event.hook-authority-unknown", format!("{hook_path}.principal"), @@ -4103,21 +4107,12 @@ fn validate_hook_proposal_authorities( )); continue; }; - if source_rules == SourceRules::Current - && (!profile.required_scopes.is_empty() - || !profile.required_purposes.is_empty() - || profile.actor_kind.is_some() - || !profile.requester_clients.is_empty() - || profile.task_grant.is_some()) - { - errors.push(Diagnostic::error( - "breg.event.hook-authority-unsupported", - format!("{hook_path}.principal"), - "a proposing hook must bind a profile with unrestricted scopes and no purpose, actor, requester-client, or task-grant requirement", - )); + if hook.handler.is_some() { + hook_profiles.insert(profile_id); } } } + hook_profiles } /// A task grant is authored only in project `accessProfiles`, where diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index 2255a589d9..11b8dec8fb 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -58,6 +58,7 @@ pub(crate) fn compile_immediate_actions( review_authorities: &[crate::contract::ReviewAuthoritySource], project: &crate::contract::RegistryProject, timer_actions: &BTreeSet, + hook_profiles: &BTreeSet<&str>, ) -> Result> { let mut errors = Vec::new(); validate_action_permission_sources(actions, profiles, &mut errors); @@ -76,6 +77,7 @@ pub(crate) fn compile_immediate_actions( review_authorities, project, timer_actions, + hook_profiles, &mut wasm_module_count, &mut errors, ) { @@ -128,6 +130,7 @@ fn compile_action( review_authorities: &[crate::contract::ReviewAuthoritySource], project: &crate::contract::RegistryProject, timer_actions: &BTreeSet, + hook_profiles: &BTreeSet<&str>, wasm_module_count: &mut usize, errors: &mut Vec, ) -> Option { @@ -370,6 +373,7 @@ fn compile_action( profiles, &target_uses, &result_effects, + hook_profiles, errors, ); if permissions.is_empty() && !timer_actions.contains(&action.id) { @@ -388,6 +392,7 @@ fn compile_action( profiles, review_authorities, &target_uses, + hook_profiles, errors, ); if let crate::model::CompiledActionExecution::Proposal { proposal } = &mut execution { @@ -2499,6 +2504,7 @@ fn compile_permissions( profiles: &[ProjectAccessProfileSource], target_uses: &[CompiledActionTargetUse], result_effects: &BTreeSet, + hook_profiles: &BTreeSet<&str>, errors: &mut Vec, ) -> Vec { let mut grants = Vec::new(); @@ -2531,8 +2537,14 @@ fn compile_permissions( "Action permissions support only the invoke operation", )); } - let target_locks = - compile_permission_targets(entities, profile, grant, target_uses, errors); + let target_locks = compile_permission_targets( + entities, + profile, + grant, + target_uses, + !hook_profiles.contains(profile.id.as_str()), + errors, + ); validate_permission_covers_uses(&target_locks, target_uses, errors); let targets = discriminate_permission_targets(&target_locks, target_uses, errors); for result in grant.results.iter() { @@ -2594,6 +2606,7 @@ fn compile_permission_targets( profile: &ProjectAccessProfileSource, grant: &crate::contract::ActionPermissionSource, target_uses: &[CompiledActionTargetUse], + http_reachable: bool, errors: &mut Vec, ) -> Vec { let mut seen = BTreeSet::new(); @@ -2632,6 +2645,7 @@ fn compile_permission_targets( }); let membership_boundaries = compile_target_memberships( entities, profile, entity, &target.row_boundaries, &target.membership_row_boundaries, + http_reachable, true, writes, &format!("accessProfiles[id={}].permissions.actions[action={}].targets[recordType={}].rowBoundaries", profile.id, grant.action, target.entity), @@ -2654,6 +2668,7 @@ fn compile_target_memberships( entity: &CompiledEntity, row_boundaries: &[RowBoundarySource], entries: &[crate::contract::MembershipRowBoundarySource], + http_reachable: bool, write_grant: bool, writes_record: bool, location: &str, @@ -2662,6 +2677,7 @@ fn compile_target_memberships( crate::membership::validate_write_admission( profile.required_scopes.is_empty(), profile.requester_clients.is_empty(), + http_reachable, &profile.principal_claim, write_grant, writes_record && entity.membership.is_some(), @@ -3355,6 +3371,7 @@ fn compile_execution( profiles: &[ProjectAccessProfileSource], authorities: &[crate::contract::ReviewAuthoritySource], target_uses: &[CompiledActionTargetUse], + hook_profiles: &BTreeSet<&str>, errors: &mut Vec, ) -> crate::model::CompiledActionExecution { use crate::contract::*; @@ -3655,6 +3672,7 @@ fn compile_execution( }); let membership_boundaries = compile_target_memberships( entities, profile, entity, &target.row_boundaries, &target.membership_row_boundaries, + !hook_profiles.contains(profile.id.as_str()), write_grant, writes, &format!("accessProfiles[id={}].permissions.proposals[action={}].targets[recordType={}].rowBoundaries", profile.id, grant.action, target.record_type), diff --git a/crates/registry-breg/src/membership.rs b/crates/registry-breg/src/membership.rs index ea76478a21..de16a278e3 100644 --- a/crates/registry-breg/src/membership.rs +++ b/crates/registry-breg/src/membership.rs @@ -24,6 +24,7 @@ pub(crate) fn validate( project: &RegistryProject, actions: &BTreeMap, entities: &BTreeMap, + hook_profiles: &BTreeSet<&str>, errors: &mut Vec, ) { for entity in entities.values() { @@ -42,6 +43,7 @@ pub(crate) fn validate( validate_write_admission( profile.required_scopes.is_empty(), profile.requester_clients.is_empty(), + !hook_profiles.contains(profile.id.as_str()), &profile.principal_claim, writes, writes_membership, @@ -126,7 +128,7 @@ pub(crate) fn validate( } } } - validate_target_entries(project, actions, entities, errors); + validate_target_entries(project, actions, entities, hook_profiles, errors); validate_source_writes(project, actions, entities, errors); validate_source_key_writes(project, actions, entities, errors); } @@ -786,22 +788,15 @@ fn validate_target_entries( project: &RegistryProject, actions: &BTreeMap, entities: &BTreeMap, + hook_profiles: &BTreeSet<&str>, errors: &mut Vec, ) { - let hook_principals = entities - .values() - .flat_map(|entity| { - entity - .hooks - .iter() - .filter_map(|hook| hook.principal.as_deref()) - }) - .collect::>(); let timer_actions = entities .values() .flat_map(|entity| entity.timers.iter().map(|timer| timer.invoke.as_str())) .collect::>(); for profile in &project.access_profiles { + let hook_profile = hook_profiles.contains(profile.id.as_str()); let targets = profile .permissions .actions @@ -849,6 +844,7 @@ fn validate_target_entries( validate_write_admission( profile.required_scopes.is_empty(), profile.requester_clients.is_empty(), + !hook_profile, &profile.principal_claim, write_grant, writes_membership, @@ -867,7 +863,7 @@ fn validate_target_entries( { refuse_recursive(&format!("recordTypes[id={id}].membership"), errors); } - if surface == "actions" && hook_principals.contains(profile.id.as_str()) { + if surface == "actions" && hook_profile { errors.push(Diagnostic::error( "breg.access.membership-hook-unsupported", &location, @@ -980,6 +976,7 @@ fn refuse_open_membership_principal(location: &str, errors: &mut Vec pub(crate) fn validate_write_admission( scopeless: bool, unrestricted_clients: bool, + http_reachable: bool, principal_claim: &str, writes: bool, writes_membership: bool, @@ -992,7 +989,10 @@ pub(crate) fn validate_write_admission( if open && has_membership && principal_claim != "sub" { refuse_open_membership_principal(location, errors); } + // Only the principal-boundary requirement depends on HTTP admission. + // The membership source and principal rules govern these grants as well. if open + && http_reachable && writes && !has_membership && !row_boundaries diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index 263d386090..58e0f20e96 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -2200,25 +2200,6 @@ pub struct CompiledRegistry { } impl CompiledRegistry { - /// Access a compiled Action grant in a disposable PostgreSQL test fixture. - #[cfg(feature = "postgres-test")] - pub fn action_grant_mut_for_test( - &mut self, - action_id: &str, - profile_id: &str, - ) -> Option<&mut CompiledActionPermission> { - self.action_inventory - .actions - .iter_mut() - .find(|action| action.id == action_id) - .and_then(|action| { - action - .permissions - .iter_mut() - .find(|grant| grant.profile_id == profile_id) - }) - } - #[allow(clippy::too_many_arguments)] pub(crate) fn new( registry_id: String, diff --git a/docs/site/src/content/docs/configure/breg-access.mdx b/docs/site/src/content/docs/configure/breg-access.mdx index 4aea995352..ba160063f3 100644 --- a/docs/site/src/content/docs/configure/breg-access.mdx +++ b/docs/site/src/content/docs/configure/breg-access.mdx @@ -485,8 +485,8 @@ An active-lifecycle membership Record must match the key and the verified princi with `active: true`. A missing match or a null key grants no access. Set `principalClaim` to a stable identity claim from a trusted issuer. If the profile requires neither scopes nor requester clients, it must use `sub` for membership. A profile that admits tokens without -scopes cannot write to a Record type that declares membership. An open profile's write target -needs a membership boundary or a claim boundary on its `principalClaim`. +scopes cannot write to a Record type that declares membership. An open profile reachable over HTTP +needs a membership boundary or a claim boundary on its `principalClaim` for each write target. The grant's profile must satisfy the membership Record type's mandatory scopes and purposes. Membership inputs remain private unless a separate field grant exposes them. diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index e7f898806b..0c6aaea65d 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -210,34 +210,39 @@ input. ### Authorize a proposing hook A receiver can return a canonical proposal answer only when the Record hook declares `principal`. -That value names the project access profile whose Action grant limits the proposal. It is an -authored authority binding, not a token subject or a claim value supplied by the receiver. +Set `principal` to an existing project access profile. Its Action grant limits what the proposal +can apply. -Every access profile still declares `principalClaim`, because the same profile contract describes -authenticated HTTP callers. A hook does not manufacture that claim, a token, or other caller -context. Its profile must therefore use `requiredScopes: unrestricted` and omit -`requiredPurposes`, `actorKind`, `requesterClients` and `taskGrant`. The Action grant must allow -`invoke`, name the permitted results and use unrestricted target row boundaries. The compiler -refuses an unknown or caller-dependent hook profile. The delivery worker checks the compiled grant -again before applying an answer. +Declare `principalClaim` as required by the access profile format. For a hook that applies changes, +use `requiredScopes: unrestricted` and omit `requiredPurposes`, `actorKind`, `requesterClients` and +`taskGrant`. Give the profile an Action grant for `invoke`, name the permitted results and set each +target's `rowBoundaries` to `unrestricted`. At application, the worker checks the compiled grant +and refuses caller-dependent grants and targets with claim or membership boundaries. -A profile selected by a proposing hook is also internal-only. BReg removes it from every issuer's -HTTP reach when `accessProfiles` is omitted, and a runtime file that lists it explicitly is refused -with `breg.runtime.hook-profile-http-reachable`. Use a separate profile for ordinary HTTP access. +BReg reserves the bound profile for the hook and exempts it from the principal-boundary requirement +for open writes. When an issuer omits `accessProfiles`, BReg excludes the reserved profile from +HTTP access. An issuer that lists the profile explicitly is refused with +`breg.runtime.hook-profile-http-reachable`. Use a separate profile for HTTP writes, where the open +write rule still applies. Omit `principal` for a notification-only webhook. It can still deliver and acknowledge events, but any proposal answer is dead-lettered rather than applied. {/* Evidence: crates/registry-breg/tests/compiler_webhook.rs, - proposal_hook_authority_requires_a_caller_independent_profile, + proposing_hook_profile_binding_preserves_authored_caller_requirements, proposal_hook_accepts_a_bounded_profile_and_keeps_its_authored_binding, + an_open_http_action_grant_still_requires_a_principal_boundary, notification_only_hook_does_not_constrain_unrelated_caller_profiles; crates/registry-breg/tests/http_auth.rs, an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes, an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile; crates/registry-breg/tests/postgres_hook_changes.rs, + real_postgres_the_same_proposal_applies_identically_across_handler_kinds, + real_postgres_hook_proposal_refuses_a_claim_bounded_action_target, real_postgres_a_loaded_hook_grant_requiring_caller_context_is_refused_without_mutation, - real_postgres_a_hook_without_a_principal_compiles_and_delivers. */} + real_postgres_a_hook_without_a_principal_compiles_and_delivers; + crates/registry-breg/tests/membership_authoring.rs, + a_hook_cannot_use_an_action_grant_with_membership. */} ## Bind each destination diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 90edb67127..56e2a901f6 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -40,7 +40,7 @@ product can take back. | Host users who can write audit files | Nothing. | Rewriting or removing lines of a local audit file. Ship the stream to append-only storage (obligation 2). | | Package authors | Authoring the project under review. | A reviewed package that is wrong. Deployment-only values (environment, instance, database) are refused in a package, so the same bytes are promoted unchanged (`BREG-SEC-01`). | | BReg's in-process refresh worker | Running each configured refresh plan as that plan's service principal, inside the worker profile's root List boundary, its pinned row claims, and its `refreshExternalProjections` grant (`BREG-SEC-204`). | A plan that names a wider identity than intended. The worker presents no token from the issuer, so revoking that identity at the identity provider does not stop it. Removing the plan from the runtime file and restarting does. | -| BReg's Record hook worker | Applying a canonical proposal answer only under the hook's internal authored project profile and its bounded Action grant (`BREG-SEC-291`). | A reviewed package that deliberately grants the hook wider caller-independent Action authority than intended. The worker presents no caller token, the profile is unreachable from HTTP, and the worker cannot satisfy scope, purpose, actor, requester-client, task-grant or row-claim conditions. | +| BReg's Record hook worker | Applying a canonical proposal answer only under the hook's authored project profile and its compiled Action grant (`BREG-SEC-291`). | A reviewed package grants the hook an Action with wider effects than intended. | {/* Evidence: products/breg/contracts/security-invariant-matrix.yaml, invariants; crates/registry-breg/tests/compiler_contract.rs, @@ -128,23 +128,23 @@ entry carries the same pseudonymous principal and record references as its attem ### Record hook proposal authority -A Record hook is not an authenticated HTTP caller. When its receiver returns a canonical proposal -answer, BReg selects only the project access profile named by the hook's authored `principal` and -then applies the profile's Action grant. The required `principalClaim` remains profile metadata for -ordinary authenticated callers. BReg does not create a token claim from it. +When a Record hook's receiver returns a canonical proposal answer, BReg uses the Action grant on +the project access profile named by the hook's authored `principal`. The required `principalClaim` +remains profile metadata. The hook worker carries no caller claims. -The compiler accepts a proposing hook profile only with unrestricted scopes and no required -purpose, actor kind, requester client or task grant. The Action grant must also have unrestricted -target row boundaries. Authentication removes that profile from every issuer's HTTP reach when an -issuer omits `accessProfiles`, while an issuer that lists it explicitly is refused. +The compiler requires the profile to exist and the hook to declare a handler. The compiler exempts +the bound profile from the open-write principal-boundary check. Every HTTP-reachable open profile +still requires a principal boundary for writes. Authentication excludes the reserved profile when +an issuer omits `accessProfiles` and refuses any issuer that lists it explicitly. -The loaded delivery inventory must retain the exact authored principal, and the worker rechecks the -compiled grant immediately before apply. A mismatch or caller-dependent grant is refused without a -Record mutation. A hook without `principal` remains a notification-only hook and cannot apply a -proposal. +The loaded delivery inventory must retain the exact authored principal. Before applying an answer, +the worker checks the compiled Action grant and refuses any caller-dependent grant or target grant +with claim or membership boundaries. A refusal leaves Records unchanged. A hook without +`principal` can only deliver notifications. {/* Evidence: products/breg/contracts/security-invariant-matrix.yaml, BREG-SEC-291; crates/registry-breg/tests/compiler_webhook.rs; + crates/registry-breg/tests/http_auth.rs; crates/registry-breg/tests/postgres_webhook_outbox.rs; crates/registry-breg/tests/postgres_hook_changes.rs. */} diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index c0ea4e25eb..bca2772b9d 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -271,7 +271,7 @@ invariants: - {"id": "BREG-SEC-252", "state": "enforced", "targetWave": "W5", "threat": "An approved Proposal moves a Record to a key outside the applying caller's membership.", "enforcementPoint": "Caller Apply locks memberships for current and frozen proposed keys and checks the selected caller's target grant before effect settlement.", "refusal": "Refuse the key move if only the old key is admitted.", "negativeId": "BREG-NEG-252", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted"}} - {"id": "BREG-SEC-253", "state": "enforced", "targetWave": "W5", "threat": "An immediate Action acquires external Evidence without a satisfiable membership-bound effect.", "enforcementPoint": "Evidence preflight checks membership feasibility under the selected Action grant before acquisition; the mutation transaction checks current authority independently.", "refusal": "Refuse an unsatisfiable Action before Evidence acquisition.", "negativeId": "BREG-NEG-253", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "evidence_admission_refuses_unsatisfiable_membership_and_replays_without_acquisition"}} - {"id": "BREG-SEC-254", "state": "enforced", "targetWave": "W5", "threat": "A denied membership-bound Action stages file bytes or creates a Record attachment reference.", "enforcementPoint": "Immediate Action admission and transaction membership checks precede its S3 staging and primary attachment write.", "refusal": "A membership denial leaves staging, references and external storage calls unchanged.", "negativeId": "BREG-NEG-254", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_membership_refusal_leaves_s3_staging_unchanged"}} - - {"id": "BREG-SEC-255", "state": "enforced", "targetWave": "W5", "threat": "A Proposal hook callback uses a target grant for which it cannot supply a claim or membership boundary.", "enforcementPoint": "Hook target authority requires the reviewed profile's target grants to have neither boundary kind.", "refusal": "Refuse the bounded target grant through the existing hook authority rejection.", "negativeId": "BREG-NEG-255", "negativeTest": {"path": "crates/registry-breg/src/mutation/action.rs", "name": "hooks_refuse_claim_and_membership_boundaries_on_the_same_path"}} + - {"id": "BREG-SEC-255", "state": "enforced", "targetWave": "W5", "threat": "A proposing Record hook uses a target grant whose claim or membership boundary the worker cannot satisfy.", "enforcementPoint": "Authoring refuses membership boundaries on Action grants for a proposing hook profile. Live hook target authority checks the compiled targets for both boundary kinds.", "refusal": "Refuse a membership-bound Action target at compilation with breg.access.membership-hook-unsupported. Refuse a claim-bound or membership-bound target at application with hook.proposal.boundaries-unsatisfiable before any Record mutation.", "negativeId": "BREG-NEG-255", "negativeTest": {"path": "crates/registry-breg/src/mutation/action.rs", "name": "hooks_refuse_claim_and_membership_boundaries_on_the_same_path"}} - {"id": "BREG-SEC-256", "state": "planned", "targetWave": "W5", "threat": "An immediate Action and Proposal Apply wait on each other when storing shared attachment content.", "enforcementPoint": "Planned common order for immediate Action staging and attachment writes and Proposal Apply promotion before history allocation, with durable staging before external upload.", "refusal": "Require the shared-content order and bounded failure recovery to preserve transaction effects and replay before treating this invariant as enforced.", "negativeId": "BREG-NEG-256"} - {"id": "BREG-SEC-257", "state": "enforced", "targetWave": "W5", "threat": "A membership source's own authority depends on another membership source that is itself bounded, or on itself, so a probe chain reaches past one level or loops.", "enforcementPoint": "Project compilation of membership declarations and of Record, Action and Proposal target entries.", "refusal": "Refuse with breg.access.membership-source-recursive unless the source is bounded only over a different leaf that has no membership entries and no incoming read paths.", "negativeId": "BREG-NEG-257", "negativeTest": {"path": "crates/registry-breg/tests/steward_authoring.rs", "name": "a_two_level_chain_through_an_action_target_is_refused"}} - {"id": "BREG-SEC-258", "state": "enforced", "targetWave": "W5", "threat": "A membership boundary on the protected Record's own identifier authorizes a write whose key cannot be checked, or a key of another Record type.", "enforcementPoint": "Project compilation of membership entries decides the identifier field by type and by whether the grant writes the protected Record type.", "refusal": "Refuse with breg.access.membership-key-type unless the key references the protected Record type and the grant only reads it or references it as an Action or Proposal target.", "negativeId": "BREG-NEG-258", "negativeTest": {"path": "crates/registry-breg/tests/steward_authoring.rs", "name": "the_identifier_field_bounds_reads_and_referenced_targets_only"}} @@ -307,7 +307,8 @@ invariants: - {"id": "BREG-SEC-288", "state": "enforced", "targetWave": "W5", "threat": "A message or mark-read by the party or the office, landing while the automatic worker applies an approved request, makes the Apply fail and hands the request back to the party.", "enforcementPoint": "The worker's Apply is fenced by its claimed lease, the submission version and the frozen effect digest inside the Apply transaction, not by a Proposal ETag read in an earlier one.", "refusal": "Apply the request; thread activity changes the revision but never what is applied.", "negativeId": "BREG-NEG-288", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "thread_activity_during_automatic_application_does_not_strand_the_request"}} - {"id": "BREG-SEC-289", "state": "enforced", "targetWave": "W5", "threat": "Office staff whose grant does not reach a Proposal confirm that it exists from how a thread route answers a malformed request.", "enforcementPoint": "Every thread route checks that the Proposal is visible to the admitted caller, under row boundaries and memberships, before it reads any header, query or body.", "refusal": "Conceal a hidden Proposal with 404 resource.not-found exactly as an unknown one.", "negativeId": "BREG-NEG-289", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_unknown_one"}} - {"id": "BREG-SEC-290", "state": "enforced", "targetWave": "W5", "threat": "A direct Record write names a referenced record the caller cannot read.", "enforcementPoint": "The write transaction reads each reference the item sets under the caller's own get or reference grant on the referenced Record type, using current transaction state. The probe requires an available row context and a validated reason when that grant requires one. Project compilation requires the grant. The reference-only policy applies only during the probe for that Record type.", "refusal": "An unauthorized, missing or tombstoned target yields 409 mutation.conflict for direct writes and 412 precondition.failed for ingestion. The same refusal applies when the attempted target grant requires a reason the request cannot supply. Refuse at compile with breg.access.reference-target-ungranted, breg.access-profile.reference-exclusive or breg.access.reference-grant-unused.", "negativeId": "BREG-NEG-290", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_direct_write_names_only_records_the_writer_can_read"}} - # Authoring and HTTP-boundary proofs: crates/registry-breg/tests/compiler_webhook.rs::proposal_hook_authority_requires_a_caller_independent_profile and proposal_hook_authority_must_bind_an_existing_profile; crates/registry-breg/tests/http_auth.rs::an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes and an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile + # Authoring: crates/registry-breg/tests/compiler_webhook.rs::proposal_hook_authority_must_bind_an_existing_profile and an_open_http_action_grant_still_requires_a_principal_boundary + # Explicit issuer reach: crates/registry-breg/tests/http_auth.rs::an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile and authenticator_construction_refuses_an_explicit_proposing_hook_profile # Exact source binding: crates/registry-breg/tests/postgres_webhook_outbox.rs::real_postgres_webhook_outbox_capture_is_atomic_package_bound_and_deterministically_identified # Action Invoke dispatch: crates/registry-breg/src/api/tests/immediate_action_tests.rs::internal_hook_profile_is_excluded_from_action_invoke_http_authority - - {id: BREG-SEC-291, state: enforced, targetWave: W5, threat: "An HTTP caller selects the Action profile reserved for a proposing Record hook, the hook borrows caller authority it does not hold, or a loaded delivery substitutes another profile binding.", enforcementPoint: "Authentication excludes every proposing-hook profile from issuer HTTP reach and refuses an issuer that explicitly lists one; the authoring compiler requires a handler for each hook declaring principal and binds it to an existing caller-independent project profile; mutation planning re-derives the principal from the governed hook; live proposal application rechecks the compiled Action grant.", refusal: "Refuse explicit issuer reach with breg.runtime.hook-profile-http-reachable and HTTP selection with profile.not-authorized. Refuse a missing handler for a proposing hook with breg.event.delivery-required. Refuse an unknown or caller-dependent profile with breg.event.hook-authority-unknown or breg.event.hook-authority-unsupported. Refuse a loaded incompatible grant as hook.proposal.unauthorized and apply no Record mutation. Notification-only hooks that omit principal remain valid.", negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} + - {id: BREG-SEC-291, state: enforced, targetWave: W5, threat: "An HTTP caller selects the Action profile reserved for a proposing Record hook, the hook borrows caller authority it does not hold, or a loaded delivery substitutes another profile binding.", enforcementPoint: "Authentication excludes every proposing Record hook profile from issuer HTTP reach and refuses an issuer that explicitly lists one. The compiler requires a handler and an existing project access profile for a hook declaring principal. Only these bound profiles are exempt from the open-write principal-boundary check. Mutation planning re-derives the principal from the governed hook and live proposal application rechecks the compiled Action grant.", refusal: "Refuse explicit issuer reach with breg.runtime.hook-profile-http-reachable and HTTP selection with profile.not-authorized. Refuse a missing handler with breg.event.delivery-required and an unknown profile with breg.event.hook-authority-unknown. Refuse a principal-unbounded open HTTP write with breg.access.open-write-without-principal-boundary. Refuse a caller-dependent compiled Action grant at application with hook.proposal.unauthorized and apply no Record mutation. Notification-only hooks that omit principal remain valid.", negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index 564a501933..220440ae23 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -313,6 +313,8 @@ traceability: - {"id": "BREG-SEC-252", "state": "enforced", "negativeId": "BREG-NEG-252", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted"}} - {"id": "BREG-SEC-253", "state": "enforced", "negativeId": "BREG-NEG-253", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "evidence_admission_refuses_unsatisfiable_membership_and_replays_without_acquisition"}} - {"id": "BREG-SEC-254", "state": "enforced", "negativeId": "BREG-NEG-254", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_membership_refusal_leaves_s3_staging_unchanged"}} + # Authored membership refusal: crates/registry-breg/tests/membership_authoring.rs::a_hook_cannot_use_an_action_grant_with_membership + # Claim refusal and plain grant control: crates/registry-breg/tests/postgres_hook_changes.rs::real_postgres_hook_proposal_refuses_a_claim_bounded_action_target - {"id": "BREG-SEC-255", "state": "enforced", "negativeId": "BREG-NEG-255", "negativeTest": {"path": "crates/registry-breg/src/mutation/action.rs", "name": "hooks_refuse_claim_and_membership_boundaries_on_the_same_path"}} - {"id": "BREG-SEC-256", "state": "planned", "negativeId": "BREG-NEG-256"} - {"id": "BREG-SEC-257", "state": "enforced", "negativeId": "BREG-NEG-257", "negativeTest": {"path": "crates/registry-breg/tests/steward_authoring.rs", "name": "a_two_level_chain_through_an_action_target_is_refused"}} @@ -350,4 +352,6 @@ traceability: - {"id": "BREG-SEC-288", "state": "enforced", "negativeId": "BREG-NEG-288", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "thread_activity_during_automatic_application_does_not_strand_the_request"}} - {"id": "BREG-SEC-289", "state": "enforced", "negativeId": "BREG-NEG-289", "negativeTest": {"path": "crates/registry-breg/tests/postgres_proposal_messages.rs", "name": "bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_unknown_one"}} - {"id": "BREG-SEC-290", "state": "enforced", "negativeId": "BREG-NEG-290", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_direct_write_names_only_records_the_writer_can_read"}} + # Open HTTP write refusal: crates/registry-breg/tests/compiler_webhook.rs::an_open_http_action_grant_still_requires_a_principal_boundary + # Plain grant application and live grant refusal: crates/registry-breg/tests/postgres_hook_changes.rs::real_postgres_the_same_proposal_applies_identically_across_handler_kinds and real_postgres_a_loaded_hook_grant_requiring_caller_context_is_refused_without_mutation - {id: BREG-SEC-291, state: enforced, negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} From e1d9a9c8f55987d7742040475f21fa1f5a9158ed Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:41:39 +0000 Subject: [PATCH 12/33] test(breg): cover an undeclared notification binding in a numbered predecessor Signed-off-by: Jeremi Joslin --- .../src/package/tests/predecessor_sources.rs | 51 ++++++++++++++ .../package/SHA256SUMS | 14 ++++ .../package/database/ddl.sql | 22 ++++++ .../package/database/migration-plan.json | 1 + .../package/effective-model.json | 1 + .../package/inventories/access.json | 1 + .../package/inventories/events.json | 1 + .../package/inventories/physical-names.json | 1 + .../package/inventories/queries.json | 1 + .../package/inventories/routes.json | 1 + .../package/metadata/registry.json | 1 + .../package/openapi/openapi.json | 1 + .../package/package.json | 1 + .../package/schemas/entry.schema.json | 1 + .../package/source/registry.yaml | 68 +++++++++++++++++++ .../package/tests/journeys.yaml | 14 ++++ 16 files changed, 180 insertions(+) create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/SHA256SUMS create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/ddl.sql create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/migration-plan.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/effective-model.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/access.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/events.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/physical-names.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/queries.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/routes.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/metadata/registry.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/openapi/openapi.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/package.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/schemas/entry.schema.json create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/source/registry.yaml create mode 100644 crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/tests/journeys.yaml diff --git a/crates/registry-breg/src/package/tests/predecessor_sources.rs b/crates/registry-breg/src/package/tests/predecessor_sources.rs index 3548d78310..12b1aac217 100644 --- a/crates/registry-breg/src/package/tests/predecessor_sources.rs +++ b/crates/registry-breg/src/package/tests/predecessor_sources.rs @@ -5,6 +5,8 @@ #![cfg(feature = "tooling")] use super::*; +use crate::diagnostics::DiagnosticSeverity; +use crate::model::{CompiledAccessInventory, CompiledEventDeliveryInventory}; use serde_json::json; use std::fs; use std::path::Path; @@ -138,6 +140,55 @@ fn predecessor_sources_rehearse_a_historical_proposing_hook_profile() { })); } +#[test] +fn predecessor_sources_rehearse_a_v052_notification_with_an_undeclared_hook_profile() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/v0.52.0-notification-predecessor/package"); + let context = PackageLoadContext { + posture: registry_platform_config::Posture::Production, + }; + let archived_source = fs::read(root.join("source/registry.yaml")).unwrap(); + let project = parse_project_yaml(&archived_source).expect("archived source parses"); + for profile in [CompileProfile::Authoring, CompileProfile::Production] { + let failure = crate::compiler::compile_project(&project, &[], profile) + .expect_err("current compilation requires a declared hook profile"); + let errors = failure + .diagnostics() + .iter() + .filter(|diagnostic| diagnostic.severity == DiagnosticSeverity::Error) + .map(|diagnostic| diagnostic.code.as_str()) + .collect::>(); + assert_eq!(errors, ["breg.event.hook-authority-unknown"]); + } + assert_eq!( + load_package(&root, &context).err(), + Some(PackageError::Derivation) + ); + + let verified = load_predecessor_package(&root, &context) + .expect("the v0.52.0 notification package is eligible for predecessor planning"); + let (predecessor, reconstructed) = load_predecessor_rehearsal_baseline(&root, &context) + .expect("the verified v0.52.0 notification package reconstructs for rehearsal"); + assert_eq!(predecessor.package_digest(), verified.package_digest()); + assert_eq!( + predecessor.schema_fingerprint(), + verified.schema_fingerprint() + ); + + let events: CompiledEventDeliveryInventory = + parse_canonical(&fs::read(root.join("inventories/events.json")).unwrap()).unwrap(); + assert_eq!(events.deliveries.len(), 1); + assert_eq!( + events.deliveries[0].principal.as_deref(), + Some("retired-observer") + ); + assert_eq!(reconstructed.event_deliveries(), &events); + let access: CompiledAccessInventory = + parse_canonical(&fs::read(root.join("inventories/access.json")).unwrap()).unwrap(); + assert_eq!(reconstructed.access(), &access); + assert!(reconstructed.actions().actions.is_empty()); +} + #[test] fn predecessor_sources_refuse_current_membership_elsewhere_in_a_historical_file() { let mut previous = membership_source(); diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/SHA256SUMS b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/SHA256SUMS new file mode 100644 index 0000000000..29b38ef1ca --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/SHA256SUMS @@ -0,0 +1,14 @@ +414ef28b272a8cb0476bd52c0a370b2f39dd1b4bc8165cffaa9e2814213dc0ce database/ddl.sql +b5a2d4932de5f05d2c360302ac03035c935e840fa276228e6ae6b4f0bfa3d625 database/migration-plan.json +60f6c8991db2662f3d2020e617f62961e4904ade9d7ac026cef3627dd88e5bfa effective-model.json +227548585b40c39d043bf2893a34d733d834df30b307b13688d3c99a82e8ca63 inventories/access.json +f2774f4ebe41246dfcc4625eae4516fc8ab2b69c1d43995f482b9cac4a054787 inventories/events.json +3326f7a0849b731a0448c753b583add1012c4f5c46fdc1039897932af2b44ee8 inventories/physical-names.json +ede4e9f3f991500b3e38fa652047cbdf3eabcc5168373f65acb8f1770c1c262b inventories/queries.json +5e63e972cbe44c1884579046b51999998a0632fe2f65dd9d959c42197e691e1d inventories/routes.json +889a86bc86cf8812bea91f958f76f3d9db60d4cc2716d536639c2db25e5731a0 metadata/registry.json +3f74358d17d754f01fd21119aa3152db243c2a0c9a5c1d0c43d1dd9000924336 openapi/openapi.json +bc02dba5665b5b3eea31fabc3b4c7c3c901a74d7b29bf50ee72b27f5cb7c4254 package.json +d5635af1dc5eca2818e5111c97d690e76fa8fb8104c725203af75edad45a6549 schemas/entry.schema.json +f933b261e44cd70544e582e0cf6c56dbf12223f637ea570c351353522c1060ae source/registry.yaml +253493af5c5fd85d65bc3fa645ba4f0b0f56c4b154c7a77525b677e0213d4f5b tests/journeys.yaml diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/ddl.sql b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/ddl.sql new file mode 100644 index 0000000000..a4da83234a --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/ddl.sql @@ -0,0 +1,22 @@ +CREATE SCHEMA IF NOT EXISTS registry_data; +CREATE SCHEMA IF NOT EXISTS registry_source; +CREATE SCHEMA IF NOT EXISTS registry_derived; +CREATE SCHEMA IF NOT EXISTS registry_context; +CREATE OR REPLACE FUNCTION registry_context.evaluation_date() + RETURNS date + LANGUAGE sql + STABLE + SECURITY INVOKER + AS $breg_function$ + SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date + $breg_function$; +CREATE TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), "breg_f_entry_name_b223a4d2b68b84ee" varchar(64) COLLATE pg_catalog.pg_c_utf8); +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" ENABLE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" FORCE ROW LEVEL SECURITY; +CREATE POLICY "registry_rls_select_a949aa044b11815c56813b65" ON registry_data."breg_e_entry_c691cfb82ab6e25e" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'reader' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')); +COMMENT ON POLICY "registry_rls_select_a949aa044b11815c56813b65" ON registry_data."breg_e_entry_c691cfb82ab6e25e" IS 'breg/policy/v1/db3a8229a6ca7c86cba13bd0889ac61c2bb486fd1fcb5bc88dfce541bf639627'; +CREATE VIEW registry_source."entry" + WITH (security_invoker=true) + AS SELECT record_id AS "id", "breg_f_entry_name_b223a4d2b68b84ee" AS "name" + FROM registry_data."breg_e_entry_c691cfb82ab6e25e" + WHERE record_lifecycle = 'active'; diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/migration-plan.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/migration-plan.json new file mode 100644 index 0000000000..52d0f3ed4a --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/database/migration-plan.json @@ -0,0 +1 @@ +{"statements":[{"id":"schema.registry_data","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_data"},{"id":"schema.registry_source","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_source"},{"id":"schema.registry_derived","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_derived"},{"id":"schema.registry_context","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_context"},{"id":"function.registry_context.evaluation_date","kind":"function","sql":"CREATE OR REPLACE FUNCTION registry_context.evaluation_date()\n RETURNS date\n LANGUAGE sql\n STABLE\n SECURITY INVOKER\n AS $breg_function$\n SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date\n $breg_function$"},{"id":"entity.entry.table","kind":"table","sql":"CREATE TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_entry_name_b223a4d2b68b84ee\" varchar(64) COLLATE pg_catalog.pg_c_utf8)"},{"id":"entity.entry.rls.enable","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ENABLE ROW LEVEL SECURITY"},{"id":"entity.entry.rls.force","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.policy.registry_rls_select_a949aa044b11815c56813b65","kind":"policy","sql":"CREATE POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'reader' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/db3a8229a6ca7c86cba13bd0889ac61c2bb486fd1fcb5bc88dfce541bf639627'"},{"id":"entity.entry.source-view","kind":"view","sql":"CREATE VIEW registry_source.\"entry\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_entry_name_b223a4d2b68b84ee\" AS \"name\"\n FROM registry_data.\"breg_e_entry_c691cfb82ab6e25e\"\n WHERE record_lifecycle = 'active'"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/effective-model.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/effective-model.json new file mode 100644 index 0000000000..3aba57816f --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/effective-model.json @@ -0,0 +1 @@ +{"accessProfiles":[{"display":{},"id":"reader"}],"datasets":[{"display":{},"id":"records"}],"defaultLanguage":"en","eventDeliveryInventory":{"deliveries":[{"attemptTimeoutMs":5000,"authenticationProfile":"hmac-sha256-v1","classificationCeiling":"internal","dataSchema":"urn:breg:event-schema:notification-rehearsal:entry:entry-created:sha256:56249ea133bc85e38983614fbdd74b5756280e6f4e21c138cd5a77e86da01a4b","dataSchemaArtifactPath":"generated/event-schemas/entry.entry-created.schema.json","dataSchemaFingerprint":"sha256:56249ea133bc85e38983614fbdd74b5756280e6f4e21c138cd5a77e86da01a4b","deadLetter":"required","deliveryMode":"after-commit","destinationId":"observer","eventId":"entry-created","exponentialBackoffMultiplier":2,"id":"events.entry.entry-created.webhook","initialBackoffMs":1000,"maximumAttempts":5,"maximumBackoffMs":8000,"maximumPayloadBytes":2747,"operatorReplay":true,"owner":{"recordType":"entry","trigger":"created","type":"record-type"},"principal":"retired-observer","projectionFields":["name"],"retryDelaysMs":[1000,2000,4000,8000],"retryProfile":"registry-v1"}]},"metadataInventory":{"recordTypes":[{"entries":[{"accessProfile":"reader","operation":"list","readableFields":["name"],"responseRecordType":"entry","routeId":"records.entry.list"}],"id":"entry","route":"entries","schemaPath":"/v1/schemas/entry"}],"registryId":"notification-rehearsal","version":"1"},"moduleClosure":[],"moduleOrder":[],"physicalNames":{"entities":{"entry":{"constraints":{},"fields":{"name":"breg_f_entry_name_b223a4d2b68b84ee"},"indexes":{},"policies":{"reader":"breg_p_entry_reader_9153097a6905bab0"},"table":"breg_e_entry_c691cfb82ab6e25e"}}},"queryInventory":{"operations":[{"allowCount":false,"filterFields":[],"id":"records.entry.reader.list","kind":"list","maxPageSize":100,"processingFields":["name"],"profileId":"reader","projectionFields":["name"],"recordType":"entry","routeId":"records.entry.list","sortFields":[],"stableTieBreaker":"record_id"}]},"recordTypes":{"entry":{"accessProfiles":{"reader":{"allowDataExport":false,"default":false,"filterableFields":[],"id":"reader","operations":["list"],"principalClaim":"principal","readableFields":["name"],"requiredPurposes":[],"requiredScopes":["records:read"],"revisionAccess":false,"rowBoundaries":[],"sortableFields":[],"writableFields":[]}},"apiName":"Entry","canonicalId":{"apiName":"id","classification":"internal","fieldType":{"type":"uuid"},"id":"id","sqlName":"id"},"classification":"internal","constraints":{},"definitionRevision":"sha256:7e2a9ef3eb2034a024c1a5a813ae37c6aaeeb7adef94c467e18d8ea04312ad79","derivedFields":{},"derivedRelations":{},"display":{},"fields":{"name":{"classification":"internal","display":{},"fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"name","physicalName":"breg_f_entry_name_b223a4d2b68b84ee","relationship":null,"required":false}},"hooks":{"entry-created":{"handler":{"destinationId":"observer","type":"url"},"id":"entry-created","phase":"after","principal":"retired-observer","projection":["name"],"trigger":"created"}},"id":"entry","indexes":{},"lookups":{},"mutationMode":"create-only","physicalTable":"breg_e_entry_c691cfb82ab6e25e","primaryDataset":"records","readPaths":{},"route":"entries","sourceRelation":{"recordType":"entry","sqlName":"entry","storedFields":["name"]},"storedFields":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"name","physicalName":"breg_f_entry_name_b223a4d2b68b84ee","required":false,"sqlName":"name"}],"tombstone":false}},"registryId":"notification-rehearsal","version":"1"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/access.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/access.json new file mode 100644 index 0000000000..c9fbcec4e5 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/access.json @@ -0,0 +1 @@ +{"entries":[{"defaultProfileId":"reader","operation":"list","profileIds":["reader"],"recordType":"entry","routeId":"records.entry.list"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/events.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/events.json new file mode 100644 index 0000000000..e9f6b6210a --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/events.json @@ -0,0 +1 @@ +{"deliveries":[{"attemptTimeoutMs":5000,"authenticationProfile":"hmac-sha256-v1","classificationCeiling":"internal","dataSchema":"urn:breg:event-schema:notification-rehearsal:entry:entry-created:sha256:56249ea133bc85e38983614fbdd74b5756280e6f4e21c138cd5a77e86da01a4b","dataSchemaArtifactPath":"generated/event-schemas/entry.entry-created.schema.json","dataSchemaFingerprint":"sha256:56249ea133bc85e38983614fbdd74b5756280e6f4e21c138cd5a77e86da01a4b","deadLetter":"required","deliveryMode":"after-commit","destinationId":"observer","eventId":"entry-created","exponentialBackoffMultiplier":2,"id":"events.entry.entry-created.webhook","initialBackoffMs":1000,"maximumAttempts":5,"maximumBackoffMs":8000,"maximumPayloadBytes":2747,"operatorReplay":true,"owner":{"recordType":"entry","trigger":"created","type":"record-type"},"principal":"retired-observer","projectionFields":["name"],"retryDelaysMs":[1000,2000,4000,8000],"retryProfile":"registry-v1"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/physical-names.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/physical-names.json new file mode 100644 index 0000000000..3321bab91d --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/physical-names.json @@ -0,0 +1 @@ +{"entities":{"entry":{"constraints":{},"fields":{"name":"breg_f_entry_name_b223a4d2b68b84ee"},"indexes":{},"policies":{"reader":"breg_p_entry_reader_9153097a6905bab0"},"table":"breg_e_entry_c691cfb82ab6e25e"}}} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/queries.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/queries.json new file mode 100644 index 0000000000..57a8c61f31 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/queries.json @@ -0,0 +1 @@ +{"operations":[{"allowCount":false,"filterFields":[],"id":"records.entry.reader.list","kind":"list","maxPageSize":100,"processingFields":["name"],"profileId":"reader","projectionFields":["name"],"recordType":"entry","routeId":"records.entry.list","sortFields":[],"stableTieBreaker":"record_id"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/routes.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/routes.json new file mode 100644 index 0000000000..ea4112f61a --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/inventories/routes.json @@ -0,0 +1 @@ +{"routes":[{"accessProfiles":["reader"],"defaultAccessProfile":"reader","id":"records.entry.list","method":"GET","operation":"list","path":"/v1/records/entries","queryKind":"list","recordType":"entry"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/metadata/registry.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/metadata/registry.json new file mode 100644 index 0000000000..4ab25734c9 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/metadata/registry.json @@ -0,0 +1 @@ +{"recordTypes":[{"entries":[{"accessProfile":"reader","operation":"list","readableFields":["name"],"responseRecordType":"entry","routeId":"records.entry.list"}],"id":"entry","route":"entries","schemaPath":"/v1/schemas/entry"}],"registryId":"notification-rehearsal","version":"1"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/openapi/openapi.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/openapi/openapi.json new file mode 100644 index 0000000000..b4efd04ee3 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/openapi/openapi.json @@ -0,0 +1 @@ +{"components":{"schemas":{"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.form-limit-reached"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/form-limit-reached"}}},{"properties":{"code":{"const":"proposal.form-undeclared"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/form-undeclared"}}},{"properties":{"code":{"const":"proposal.message-limit-reached"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/message-limit-reached"}}},{"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.subject-changed"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/subject-changed"}}},{"properties":{"code":{"const":"proposal.subject-not-caller"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/subject-not-caller"}}},{"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.form-limit-reached","proposal.form-undeclared","proposal.message-limit-reached","proposal.rejected","proposal.review-result-mismatch","proposal.subject-changed","proposal.subject-not-caller","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"},"entry":{"$id":"urn:breg:record-type:entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"}},"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":"notification-rehearsal","version":"1"},"openapi":"3.1.0","paths":{"/v1/records/entries":{"get":{"operationId":"records.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":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"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":"records"},"recordTypeId":{"const":"entry"},"registryId":{"const":"notification-rehearsal"}},"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":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"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":"records"},"recordTypeId":{"const":"entry"},"registryId":{"const":"notification-rehearsal"}},"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":["reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"reader","requiredFilters":[],"selectableProperties":["name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"entry","x-registry-responseShape":"RegistryRecordCollectionV1"}},"/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/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/package.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/package.json new file mode 100644 index 0000000000..521e5b4f56 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/package.json @@ -0,0 +1 @@ +{"apiVersion":"id.registrystack.org/formats/breg/package/v2","kind":"BRegPackage","manifest":{"compiler":{"id":"breg","profile":"production","sourceRevision":"v0.52.0-notification-rehearsal-fixture"},"engineFeatures":["statistical_release_store","caller_scoped_idempotency","record_timer_store"],"files":[{"path":"database/ddl.sql","role":"generated_ddl","sha256":"sha256:414ef28b272a8cb0476bd52c0a370b2f39dd1b4bc8165cffaa9e2814213dc0ce","size":2382},{"path":"database/migration-plan.json","role":"migration_plan","sha256":"sha256:b5a2d4932de5f05d2c360302ac03035c935e840fa276228e6ae6b4f0bfa3d625","size":3057},{"path":"effective-model.json","role":"governed_model","sha256":"sha256:60f6c8991db2662f3d2020e617f62961e4904ade9d7ac026cef3627dd88e5bfa","size":3613},{"path":"inventories/access.json","role":"access_inventory","sha256":"sha256:227548585b40c39d043bf2893a34d733d834df30b307b13688d3c99a82e8ca63","size":138},{"path":"inventories/events.json","role":"event_inventory","sha256":"sha256:f2774f4ebe41246dfcc4625eae4516fc8ab2b69c1d43995f482b9cac4a054787","size":948},{"path":"inventories/physical-names.json","role":"physical_name_inventory","sha256":"sha256:3326f7a0849b731a0448c753b583add1012c4f5c46fdc1039897932af2b44ee8","size":210},{"path":"inventories/queries.json","role":"query_inventory","sha256":"sha256:ede4e9f3f991500b3e38fa652047cbdf3eabcc5168373f65acb8f1770c1c262b","size":296},{"path":"inventories/routes.json","role":"route_inventory","sha256":"sha256:5e63e972cbe44c1884579046b51999998a0632fe2f65dd9d959c42197e691e1d","size":203},{"path":"metadata/registry.json","role":"caller_safe_metadata","sha256":"sha256:889a86bc86cf8812bea91f958f76f3d9db60d4cc2716d536639c2db25e5731a0","size":279},{"path":"openapi/openapi.json","role":"generated_openapi","sha256":"sha256:3f74358d17d754f01fd21119aa3152db243c2a0c9a5c1d0c43d1dd9000924336","size":29735},{"path":"schemas/entry.schema.json","role":"entity_json_schema","sha256":"sha256:d5635af1dc5eca2818e5111c97d690e76fa8fb8104c725203af75edad45a6549","size":289},{"path":"source/registry.yaml","role":"source_project","sha256":"sha256:f933b261e44cd70544e582e0cf6c56dbf12223f637ea570c351353522c1060ae","size":1479},{"path":"tests/journeys.yaml","role":"fixture_journeys","sha256":"sha256:253493af5c5fd85d65bc3fa645ba4f0b0f56c4b154c7a77525b677e0213d4f5b","size":398}],"migrationPlan":{"statements":[{"id":"schema.registry_data","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_data"},{"id":"schema.registry_source","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_source"},{"id":"schema.registry_derived","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_derived"},{"id":"schema.registry_context","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_context"},{"id":"function.registry_context.evaluation_date","kind":"function","sql":"CREATE OR REPLACE FUNCTION registry_context.evaluation_date()\n RETURNS date\n LANGUAGE sql\n STABLE\n SECURITY INVOKER\n AS $breg_function$\n SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date\n $breg_function$"},{"id":"entity.entry.table","kind":"table","sql":"CREATE TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_entry_name_b223a4d2b68b84ee\" varchar(64) COLLATE pg_catalog.pg_c_utf8)"},{"id":"entity.entry.rls.enable","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ENABLE ROW LEVEL SECURITY"},{"id":"entity.entry.rls.force","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.policy.registry_rls_select_a949aa044b11815c56813b65","kind":"policy","sql":"CREATE POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'reader' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/db3a8229a6ca7c86cba13bd0889ac61c2bb486fd1fcb5bc88dfce541bf639627'"},{"id":"entity.entry.source-view","kind":"view","sql":"CREATE VIEW registry_source.\"entry\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_entry_name_b223a4d2b68b84ee\" AS \"name\"\n FROM registry_data.\"breg_e_entry_c691cfb82ab6e25e\"\n WHERE record_lifecycle = 'active'"}]},"packageId":"notification-rehearsal","schemaFingerprint":"sha256:1feb833c4da8cbbfa60a45bbd9fa3dd24781eeebdd94cb4f8bc12d183e85322a","sources":{"fixtureJourneys":"tests/journeys.yaml","modules":[],"project":"source/registry.yaml"}}} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/schemas/entry.schema.json b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/schemas/entry.schema.json new file mode 100644 index 0000000000..0598045297 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/schemas/entry.schema.json @@ -0,0 +1 @@ +{"$id":"urn:breg:record-type:entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/source/registry.yaml b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/source/registry.yaml new file mode 100644 index 0000000000..0d5c077dc9 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/source/registry.yaml @@ -0,0 +1,68 @@ +{ + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": { + "id": "notification-rehearsal", + "version": "1", + "defaultLanguage": "en", + "canonicalBaseIri": "https://notification.example.test" + }, + "package": { + "sourceRevision": "v0.52.0-notification-rehearsal-fixture" + }, + "datasets": { + "records": {} + }, + "recordTypes": { + "entry": { + "primaryDataset": "records", + "route": "entries", + "mutationMode": "create-only", + "fields": [ + { + "id": "name", + "type": "string", + "maximumLength": 64, + "classification": "internal" + } + ], + "hooks": [ + { + "id": "entry-created", + "phase": "after", + "trigger": "created", + "projection": [ + "name" + ], + "handler": { + "type": "url", + "destinationId": "observer" + }, + "principal": "retired-observer" + } + ] + } + }, + "accessProfiles": { + "reader": { + "principalClaim": "principal", + "requiredScopes": [ + "records:read" + ], + "permissions": { + "records": [ + { + "recordType": "entry", + "operations": [ + "list" + ], + "readableFields": [ + "name" + ], + "rowBoundaries": "unrestricted" + } + ] + } + } + } +} diff --git a/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/tests/journeys.yaml b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/tests/journeys.yaml new file mode 100644 index 0000000000..2200486f35 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.52.0-notification-predecessor/package/tests/journeys.yaml @@ -0,0 +1,14 @@ +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: empty-entries + steps: + - id: list-entries + actor: reader + recordType: entry + accessProfile: reader + claims: + principal: synthetic-reader + scopes: [records:read] + request: {type: list} + expect: {outcome: success, status: 200, count: 0} From 493cb5bc968f05fd9000d47aa60932c1c7ad7f40 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:42:30 +0000 Subject: [PATCH 13/33] fix(breg): retain undeclared hook bindings in predecessor rehearsal Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/compiler.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 42c5723f92..9809403475 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -250,6 +250,7 @@ pub fn compile_project_with_assets( /// Reconstruct the schema of a verified predecessor for migration rehearsal. /// A v0.51.0 package can declare writable references without target grants. +/// A v0.52.0 package can carry an undeclared notification hook profile name. #[cfg(feature = "tooling")] pub(crate) fn compile_verified_predecessor_for_rehearsal( project: &RegistryProject, @@ -362,6 +363,7 @@ fn compile_with_source_rules( &sources, &project.access_profiles, &origins.hook_paths, + source_rules, &mut diagnostics, ); validate_module_access_profile_task_grants(&sources, &mut diagnostics); @@ -4077,10 +4079,12 @@ fn validate_project_entity_access_profiles( /// A proposing Record hook binds an existing project access profile. Only /// hooks with handlers enter the delivery inventory, whose principal bindings /// authentication excludes from every HTTP issuer. +/// An undeclared predecessor binding stays in the delivery inventory as metadata. fn validate_hook_proposal_authorities<'a>( entities: &BTreeMap, profiles: &'a [ProjectAccessProfileSource], hook_paths: &HookPathMap, + source_rules: SourceRules, errors: &mut Vec, ) -> BTreeSet<&'a str> { let profiles = profiles @@ -4094,17 +4098,19 @@ fn validate_hook_proposal_authorities<'a>( continue; }; let Some(&profile_id) = profiles.get(principal) else { - let hook_path = hook_paths - .get(&(entity.id.clone(), hook.id.clone())) - .cloned() - .unwrap_or_else(|| { - format!("recordTypes[id={}].hooks[id={}]", entity.id, hook.id) - }); - errors.push(Diagnostic::error( - "breg.event.hook-authority-unknown", - format!("{hook_path}.principal"), - "a proposing hook must bind an existing project access profile", - )); + if source_rules == SourceRules::Current { + let hook_path = hook_paths + .get(&(entity.id.clone(), hook.id.clone())) + .cloned() + .unwrap_or_else(|| { + format!("recordTypes[id={}].hooks[id={}]", entity.id, hook.id) + }); + errors.push(Diagnostic::error( + "breg.event.hook-authority-unknown", + format!("{hook_path}.principal"), + "a proposing hook must bind an existing project access profile", + )); + } continue; }; if hook.handler.is_some() { From 025a50a16c0627b167ecb3da4f1a5e31eb29aba3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:43:33 +0000 Subject: [PATCH 14/33] test(breg): cover retained review recovery during upgrade Signed-off-by: Jeremi Joslin --- .../tests/support/review_go_live.rs | 225 ++++++++++++++++++ crates/registry-bregctl/src/lib.rs | 21 ++ 2 files changed, 246 insertions(+) diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index 8ce679df66..b3596aa109 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -1105,6 +1105,231 @@ async fn activation_blocked_resubmit_names_package_change_instead_of_resending() fixture.finish().await; } +#[tokio::test] +async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { + use registry_breg::{ + migration::MigrationError, + review_store::{ + check_review_initiator_upgrade, verify_retained_bindings, RetainedReviewBindingError, + }, + }; + + let authority = Authority::start(false, true).await; + let (fixture, _) = reviewed_fixture(&authority, false).await; + let id = submitted(&fixture, "upgrade-failed-review").await; + let db = &fixture.database.admin; + let snapshot = || async { + db.query_one( + "SELECT to_jsonb(s), to_jsonb(w) + FROM registry_internal.registry_proposal_review_submissions s + JOIN registry_internal.registry_proposal_state w USING (action_id, proposal_id) + WHERE s.proposal_id=$1", + &[&id], + ) + .await + .unwrap() + }; + let current = snapshot().await.get::<_, Value>(0)["create_request"].clone(); + let mut previous = current.clone(); + previous["initiator"] = + json!({"issuer":"https://previous.example.test","subject":"older-human"}); + let operator = recovery(&fixture, &fixture.registry, &fixture.identity); + for code in [ + "result-poll-attempts-exhausted", + "submission-recovery-expired", + "operator-closed", + ] { + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET state='failed',last_error_code=$2,create_request=$3,attempt_count=3, + result_poll_attempts=2 + WHERE proposal_id=$1", + &[&id, &code, &previous], + ) + .await + .unwrap(); + let before = snapshot().await; + assert_eq!( + check_review_initiator_upgrade(&fixture.pool).await, + Err(MigrationError::ReviewInitiatorUpgrade), + "{code}" + ); + assert_eq!( + verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) + .await, + Err(RetainedReviewBindingError::ReviewInitiatorUpgrade), + "{code}" + ); + let audit_start = fixture.database.activation_audit_entries().len(); + let ReviewRecoveryError::Ineligible { + reason, + state, + code: stored_code, + } = operator + .resubmit(scope(id)) + .await + .expect_err("the older request cannot be resent") + else { + panic!("resubmit must name why recovery is refused"); + }; + assert_eq!(reason.as_str(), "initiator-upgrade"); + assert_eq!(state, "failed"); + assert_eq!(stored_code.as_deref(), Some(code)); + let after = snapshot().await; + for column in 0..2 { + assert_eq!( + after.get::<_, Value>(column), + before.get::<_, Value>(column) + ); + } + let audit = fixture.database.activation_audit_entries(); + let entries = &audit[audit_start..]; + assert_eq!(entries.len(), 2); + assert_eq!(entries[0]["phase"], "request"); + assert_eq!(entries[1]["phase"], "response"); + assert_eq!(entries[1]["record"]["outcome"], "refused"); + assert_eq!(entries[0]["correlation"], entries[1]["correlation"]); + } + + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET create_request=$2 WHERE proposal_id=$1", + &[&id, ¤t], + ) + .await + .unwrap(); + check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + assert_eq!(operator.resubmit(scope(id)).await.unwrap().state, "pending"); + let after: Value = snapshot().await.get(0); + assert_eq!(after["create_request"], current); + assert_eq!(after["attempt_count"], 0); + assert_eq!(after["result_poll_attempts"], 0); + assert!(authority.state.creates.lock().unwrap().is_empty()); + fixture.finish().await; +} + +#[tokio::test] +async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { + use registry_breg::review_store::{check_review_initiator_upgrade, verify_retained_bindings}; + + let authority = Authority::start(false, true).await; + let (fixture, _) = reviewed_fixture(&authority, false).await; + let proposal = submitted_proposal(&fixture, "upgrade-terminal-review").await; + let id = Uuid::parse_str(proposal.id()).unwrap(); + let db = &fixture.database.admin; + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET state='failed',create_request=create_request || $2::jsonb, + producer_id='previous-producer' + WHERE proposal_id=$1", + &[&id, &json!({"initiator":{"issuer":"https://previous.example.test","subject":"older-human"}})], + ) + .await + .unwrap(); + let operator = recovery(&fixture, &fixture.registry, &fixture.identity); + for (state, version, withdrawn, blocked, code, reason) in [ + ( + "submitted", + 1_i64, + false, + None, + "remote-refused", + "submission-state", + ), + ("submitted", 1, true, None, "operator-closed", "withdrawn"), + ( + "submitted", + 1, + false, + Some("package-changed"), + "operator-closed", + "package-changed", + ), + ( + "submitted", + 2, + false, + None, + "operator-closed", + "proposal-not-submitted", + ), + ( + "cancelled", + 1, + false, + None, + "operator-closed", + "proposal-not-submitted", + ), + ] { + db.execute( + "UPDATE registry_internal.registry_proposal_state + SET state=$2,submission_version=$3,blocked_reason=$4 WHERE proposal_id=$1", + &[&id, &state, &version, &blocked], + ) + .await + .unwrap(); + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET withdrawn=$2,last_error_code=$3 WHERE proposal_id=$1", + &[&id, &withdrawn, &code], + ) + .await + .unwrap(); + check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) + .await + .unwrap(); + let ReviewRecoveryError::Ineligible { reason: actual, .. } = operator + .resubmit(scope(id)) + .await + .expect_err("this review is not eligible") + else { + panic!("resubmit must preserve the existing refusal"); + }; + assert_eq!(actual.as_str(), reason); + } + let terminal = fixture + .http + .client + .read_proposal(&proposal) + .await + .unwrap() + .value; + assert_eq!( + terminal.state(), + registry_breg_client::BRegProposalState::Cancelled + ); + + db.execute( + "UPDATE registry_internal.registry_proposal_state SET state='submitted' WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap(); + db.execute( + "INSERT INTO registry_internal.registry_proposal_review_results + (action_id, proposal_id, submission_version, authority, result_id, result, status, + completed_at, available_until) + SELECT action_id, proposal_id, submission_version, authority, $2, '{}'::jsonb, 'approved', + transaction_timestamp(), transaction_timestamp()+interval '1 day' + FROM registry_internal.registry_proposal_review_submissions WHERE proposal_id=$1", + &[&id, &Uuid::new_v4()], + ) + .await + .unwrap(); + check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + let ReviewRecoveryError::Ineligible { reason, .. } = operator + .resubmit(scope(id)) + .await + .expect_err("the completed review cannot be resent") + else { + panic!("resubmit must preserve the recorded-result refusal"); + }; + assert_eq!(reason.as_str(), "result-recorded"); + fixture.finish().await; +} + #[tokio::test] async fn activation_fences_inflight_submission_and_recovers_only_to_cancel() { let authority = Authority::start(true, true).await; diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 1572923e10..9fdd287158 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -17739,6 +17739,27 @@ mod tests { .contains("reason request-erased, state failed, code result-poll-attempts-exhausted")); } + #[test] + fn older_initiator_recovery_uses_the_upgrade_remedy() { + let report = review_recovery_failure( + "review-recovery resubmit", + ReviewRecoveryCliError::Ineligible { + reason: "initiator-upgrade", + state: "failed".into(), + code: Some("operator-closed".into()), + }, + ); + let encoded = serde_json::to_string(&report).unwrap(); + for expected in [ + "review-recovery.submission.ineligible", + "initiator-upgrade", + "previous matching Registry Stack release", + "finish or cancel the affected work", + ] { + assert!(encoded.contains(expected)); + } + } + #[test] fn package_changed_recovery_directs_the_requester_to_fresh_review_or_cancel() { for command in [ From 41b065c55155cd7bbdf02117eacdef9bf2ceef70 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:46:26 +0000 Subject: [PATCH 15/33] fix(breg): fence recoverable reviews with legacy initiators Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/review_recovery.rs | 33 ++++++++++++------ crates/registry-breg/src/review_store.rs | 34 ++++++++++++++++--- .../tests/support/review_go_live.rs | 7 ++-- crates/registry-bregctl/src/lib.rs | 4 +++ .../operate/advanced/upgrade-and-retire.mdx | 10 ++++-- 5 files changed, 68 insertions(+), 20 deletions(-) diff --git a/crates/registry-breg/src/review_recovery.rs b/crates/registry-breg/src/review_recovery.rs index bb078b8cd8..ed0213ce0b 100644 --- a/crates/registry-breg/src/review_recovery.rs +++ b/crates/registry-breg/src/review_recovery.rs @@ -23,10 +23,11 @@ use serde_json::Value; use uuid::Uuid; use crate::proposal_retention::{ProposalRetentionError, ProposalRetentionOperatorService}; +use crate::review_store::{PREVIOUS_REVIEW_INITIATOR, REVIEW_RESULT_RECORDED}; /// Codes a failed review may carry and still be resubmitted: each one means /// BReg gave up waiting, never that the authority refused or decided. -const RESUBMITTABLE_FAILURE_CODES: [&str; 3] = [ +pub(crate) const RESUBMITTABLE_FAILURE_CODES: [&str; 3] = [ "result-poll-attempts-exhausted", "submission-recovery-expired", "operator-closed", @@ -72,6 +73,8 @@ pub enum ReviewRecoveryRefusal { ApplicationRefused, /// The submission's state and code do not call for this operation. SubmissionState, + /// The retained initiator predates claim binding and requires the previous release. + InitiatorUpgrade, /// The application job has no transient failure with remaining attempts. ApplicationState, /// The exact proposal no longer has an unexpired approval. @@ -88,6 +91,7 @@ impl ReviewRecoveryRefusal { Self::PackageChanged => "package-changed", Self::ApplicationRefused => "application-refused", Self::SubmissionState => "submission-state", + Self::InitiatorUpgrade => "initiator-upgrade", Self::ApplicationState => "application-state", Self::ApprovalUnavailable => "approval-unavailable", } @@ -183,7 +187,8 @@ impl ReviewRecoveryOperatorService { /// /// Accepted only for a review the authority answered as unknown, or one /// BReg failed for waiting too long, while its proposal still awaits - /// review. The authority that still holds the request replays its + /// review. A named initiator from before claim binding must be settled on + /// the previous release. The authority that still holds the request replays its /// original acceptance. If a previously accepted request was lost, a new /// acceptance is refused and the author must submit a new Proposal version. pub async fn resubmit(&self, scope: ReviewRecoveryScope<'_>) -> Result { @@ -326,19 +331,19 @@ impl ReviewRecoveryOperatorService { } let row = transaction .query_opt( - "SELECT s.state,s.last_error_code,s.withdrawn,s.authority, - s.create_request <> '{}'::jsonb, - EXISTS ( - SELECT 1 FROM registry_internal.registry_proposal_review_results r - WHERE (r.action_id,r.proposal_id,r.submission_version) - =(s.action_id,s.proposal_id,s.submission_version)), + &format!( + "SELECT s.state,s.last_error_code,s.withdrawn,s.authority, + s.create_request <> '{{}}'::jsonb, + {REVIEW_RESULT_RECORDED}, w.state='submitted' AND w.submission_version=s.submission_version, - CASE WHEN w.submission_version=s.submission_version THEN w.blocked_reason END + CASE WHEN w.submission_version=s.submission_version THEN w.blocked_reason END, + ({PREVIOUS_REVIEW_INITIATOR}) IS TRUE FROM registry_internal.registry_proposal_review_submissions s LEFT JOIN registry_internal.registry_proposal_state w ON (w.action_id,w.proposal_id)=(s.action_id,s.proposal_id) WHERE s.action_id=$1 AND s.proposal_id=$2 AND s.submission_version=$3 - FOR UPDATE OF s", + FOR UPDATE OF s" + ), &[ &scope.action_id, &scope.proposal_id, @@ -387,6 +392,14 @@ impl ReviewRecoveryOperatorService { let (next_state, next_code) = match operation { Operation::RetryApplication => unreachable!("application recovery handled above"), Operation::Resubmit => { + if row.get::<_, bool>(8) { + return Err(ReviewRecoveryError::Ineligible { + reason: ReviewRecoveryRefusal::InitiatorUpgrade, + state, + code, + } + .into()); + } // Retry the original request and key while preserving any concrete // acceptance. A different acceptance cannot replace it even // when the original selector delegated policy selection. diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index 8212c1cf5b..e846bd3a29 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -93,7 +93,18 @@ const RETAINED_REVIEW_SUBMISSION: &str = (s.action_id,s.proposal_id,s.submission_version) AND w.state='submitted'))"; -pub(crate) const REVIEW_INITIATOR_UPGRADE_ADVICE: &str = "retained Review requests use the previous release's initiator format. Use the previous matching Registry Stack release to finish or cancel the affected work before retrying"; +/// A named initiator from before claim binding. The preflight and operator +/// recovery read the same predicate on a review submission aliased as `s`. +pub(crate) const PREVIOUS_REVIEW_INITIATOR: &str = + "jsonb_typeof(s.create_request->'initiator') = 'object' + AND NULLIF(s.create_request->'initiator'->>'principalClaim','') IS NULL"; +pub(crate) const REVIEW_RESULT_RECORDED: &str = "EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_review_results r + WHERE (r.action_id,r.proposal_id,r.submission_version) + =(s.action_id,s.proposal_id,s.submission_version))"; + +/// Operator guidance when work must settle on the release that created it. +pub const REVIEW_INITIATOR_UPGRADE_ADVICE: &str = "retained Review requests use the previous release's initiator format. Use the previous matching Registry Stack release to finish or cancel the affected work before retrying"; /// Inspect resumable Review work without claiming a job or rewriting a request. pub(crate) async fn review_initiator_upgrade_required( @@ -109,16 +120,29 @@ pub(crate) async fn review_initiator_upgrade_required( if !has_review_store { return Ok(false); } + let resubmittable_codes = crate::review_recovery::RESUBMITTABLE_FAILURE_CODES + .into_iter() + .map(str::to_owned) + .collect::>(); + // Failed requests count for the format check exactly when operator + // recovery could requeue them. Authority retention has its own lifecycle. let row = client .query_one( &format!( "SELECT EXISTS ( SELECT 1 FROM registry_internal.registry_proposal_review_submissions s - WHERE ({RETAINED_REVIEW_SUBMISSION}) - AND jsonb_typeof(s.create_request->'initiator') = 'object' - AND NULLIF(s.create_request#>>'{{initiator,principalClaim}}','') IS NULL)" + WHERE ({PREVIOUS_REVIEW_INITIATOR}) + AND (({RETAINED_REVIEW_SUBMISSION}) + OR (s.state='failed' AND NOT s.withdrawn + AND s.last_error_code=ANY($1) + AND NOT {REVIEW_RESULT_RECORDED} + AND EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_state w + WHERE (w.action_id,w.proposal_id,w.submission_version) + =(s.action_id,s.proposal_id,s.submission_version) + AND w.state='submitted' AND w.blocked_reason IS NULL))))" ), - &[], + &[&resubmittable_codes], ) .await?; Ok(row.get(0)) diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index b3596aa109..8a70b441a1 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -1130,6 +1130,7 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { .unwrap() }; let current = snapshot().await.get::<_, Value>(0)["create_request"].clone(); + let accepted = json!(retained_binding(&fixture, id).await); let mut previous = current.clone(); previous["initiator"] = json!({"issuer":"https://previous.example.test","subject":"older-human"}); @@ -1139,12 +1140,13 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { "submission-recovery-expired", "operator-closed", ] { + let binding = (code != "submission-recovery-expired").then_some(&accepted); db.execute( "UPDATE registry_internal.registry_proposal_review_submissions SET state='failed',last_error_code=$2,create_request=$3,attempt_count=3, - result_poll_attempts=2 + result_poll_attempts=2,accepted_binding=$4 WHERE proposal_id=$1", - &[&id, &code, &previous], + &[&id, &code, &previous, &binding], ) .await .unwrap(); @@ -1202,6 +1204,7 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { assert_eq!(operator.resubmit(scope(id)).await.unwrap().state, "pending"); let after: Value = snapshot().await.get(0); assert_eq!(after["create_request"], current); + assert_eq!(after["accepted_binding"], accepted); assert_eq!(after["attempt_count"], 0); assert_eq!(after["result_poll_attempts"], 0); assert!(authority.state.creates.lock().unwrap().is_empty()); diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 9fdd287158..36a69e386a 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -4670,6 +4670,10 @@ fn review_recovery_failure(command: &'static str, error: ReviewRecoveryCliError) "review-recovery.submission.ineligible", "the current request is blocked by a refused Apply (application-refused); its requester must Rebase and submit for fresh Review, or Cancel it".to_owned(), ), + ReviewRecoveryCliError::Ineligible { reason: "initiator-upgrade", .. } => ( + "review-recovery.submission.ineligible", + format!("initiator-upgrade: {}", registry_breg::review_store::REVIEW_INITIATOR_UPGRADE_ADVICE), + ), ReviewRecoveryCliError::Ineligible { reason, state, diff --git a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx index 70f8a9c77b..a55e83444f 100644 --- a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx +++ b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx @@ -83,9 +83,12 @@ database forward in place when you run `messagingctl apply`. When a release introduces `initiator.principalClaim`, pause new Review submissions and let the previous matching release settle outstanding BReg Proposal reviews. Finish or cancel Coordinator runs that submit reviews on -that release. BReg names unfinished requests using the earlier initiator -format at startup, plan and apply. Coordinator holds runs sealed with the -earlier Review operation binding before dispatch. +that release. BReg checks unfinished requests using the earlier initiator +format at startup, plan and apply. This includes failed reviews that an +operator could still resubmit. If `bregctl review-recovery resubmit` reports +`initiator-upgrade`, finish or cancel the affected work on the previous +matching release. Coordinator holds runs sealed with the earlier Review +operation binding before dispatch. Record any needed BReg review status for older reviews with a named initiator before upgrading. Reading this status afterward requires a pre-upgrade backup and its matching release. @@ -96,6 +99,7 @@ for its retained-state requirements before restarting the paired runtimes and clients on the same release. {/* Evidence: crates/registry-breg/src/review_store.rs, check_review_initiator_upgrade; + crates/registry-breg/src/review_recovery.rs, ReviewRecoveryRefusal::InitiatorUpgrade; crates/registry-breg/src/startup.rs, review_binding_startup_error; crates/registry-breg/src/migration.rs, activate; crates/registry-coordinator/src/operations.rs, submit_review; From 97bbb22290cdaacebbbedb404afba37af5132bf1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 08:50:48 +0000 Subject: [PATCH 16/33] test(breg): pass ordinary membership authority to compiler fixtures Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/immediate_actions.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index 11b8dec8fb..f72aeb58d1 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -4426,6 +4426,7 @@ mod membership_target_tests { profile, &profile.permissions.actions[0], uses, + true, &mut errors, ); let targets = discriminate_permission_targets(&locks, uses, &mut errors); @@ -4450,6 +4451,7 @@ mod membership_target_tests { &project.access_profiles, &project.review_authorities, &action.target_uses, + &BTreeSet::new(), &mut errors, ); let crate::model::CompiledActionExecution::Proposal { proposal } = execution else { From addf29933ebb86ddb7e1bc667eb13e45c4f7fdda Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:00:14 +0000 Subject: [PATCH 17/33] test(breg): cover retained terminal review status after upgrade Signed-off-by: Jeremi Joslin --- .../tests/support/review_go_live.rs | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index 8a70b441a1..d736b4d908 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -1211,6 +1211,117 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { fixture.finish().await; } +#[tokio::test] +async fn upgrade_preserves_terminal_status_for_a_previous_named_initiator() { + use registry_breg::review_store::check_review_initiator_upgrade; + use registry_breg_client::{BRegProposalReviewHandoffState, BRegProposalState}; + use registry_review_protocol::{canonical_bytes, submission_digest, ContentDigest}; + + let authority = Authority::start(false, true).await; + let (fixture, source) = reviewed_fixture_with_recovery(&authority, false, true).await; + let proposal = submitted_proposal(&fixture, "retained-review-status").await; + let id = Uuid::parse_str(proposal.id()).unwrap(); + let db = &fixture.database.admin; + + let mut accepted = retained_binding(&fixture, id).await; + accept(&fixture, id, &accepted).await; + let mut decision = result(&accepted, Uuid::new_v4(), ReviewResultStatus::Rejected); + decision.outcome = Some("rejected".to_owned()); + { + let mut client = fixture.pool.get_for_test().await.unwrap(); + let tx = client.transaction().await.unwrap(); + reconcile_result(&tx, AUTHORITY, &accepted, &decision, &fixture.mutations) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + + // Keep a complete predecessor closure with the previous wire shape and + // digest in the retained rows, including the provider's recorded result. + let mut previous: Value = db + .query_one( + "SELECT create_request FROM registry_internal.registry_proposal_review_submissions + WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + previous["initiator"] = + json!({"issuer":"https://previous.example.test","subject":"previous-reviewer-canary"}); + let request: ReviewCreateRequest = serde_json::from_value(previous.clone()).unwrap(); + assert!(request.check().is_err()); + assert!(submission_digest(PRODUCER, &accepted.subject.source, &request).is_err()); + let envelope = json!({ + "producer":PRODUCER, + "sourceNamespace":accepted.subject.source, + "request":previous + }); + let digest = ContentDigest::for_bytes(&canonical_bytes(&envelope).unwrap()); + accepted.submission_digest = digest.clone(); + decision.submission_digest = digest; + let updated = db + .execute( + "WITH retained AS ( + UPDATE registry_internal.registry_proposal_review_submissions + SET create_request=$2,expected_submission_digest=$3,accepted_binding=$4 + WHERE proposal_id=$1 RETURNING action_id,proposal_id,submission_version + ) + UPDATE registry_internal.registry_proposal_review_results r SET result=$5 + FROM retained s + WHERE (r.action_id,r.proposal_id,r.submission_version)= + (s.action_id,s.proposal_id,s.submission_version)", + &[ + &id, + &previous, + &accepted.submission_digest.as_str(), + &json!(accepted), + &json!(decision), + ], + ) + .await + .unwrap(); + assert_eq!(updated, 1); + + check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + let (package, active) = activate(&fixture, &source, &authority).await; + let (http, _) = + active_package_client(&fixture, package.registry(), &active, &authority, claims()).await; + let metadata = http.client.registry_contract(Some("clerk")).await.unwrap(); + let get = metadata.value.select_proposal_get("clerk").unwrap(); + let terminal = http + .client + .get_proposal(&get, proposal.id()) + .await + .unwrap() + .value; + assert_eq!(terminal.state(), BRegProposalState::Rejected); + assert!(terminal.link("reviewContext").is_none()); + assert!(terminal.link("reviewStatus").is_some()); + let status = http + .client + .read_proposal_review_status(&terminal) + .await + .unwrap() + .value; + assert_eq!(status.request_id, Some(accepted.request_id.to_string())); + assert_eq!( + status.handoff.as_ref().unwrap().state, + BRegProposalReviewHandoffState::Accepted + ); + assert!(!status.reviewable); + assert!(status.context.fields.is_none()); + assert!(!json!(status) + .to_string() + .contains("previous-reviewer-canary")); + let retained = status.result.unwrap(); + assert_eq!(retained.state, "rejected"); + assert_eq!(retained.result_id, Some(decision.result_id.to_string())); + assert_eq!(authority.state.requests.load(Ordering::SeqCst), 0); + drop(http); + fixture.finish().await; +} + #[tokio::test] async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { use registry_breg::review_store::{check_review_initiator_upgrade, verify_retained_bindings}; From 3f61a6d2c675b525b5a692f1651933daaed8cd13 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:04:15 +0000 Subject: [PATCH 18/33] fix(breg): preserve terminal review status across initiator upgrades Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/mutation/proposal.rs | 18 +- crates/registry-breg/src/review_store.rs | 248 ++++++++++++++++-- .../operate/advanced/upgrade-and-retire.mdx | 10 +- 3 files changed, 242 insertions(+), 34 deletions(-) diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index 87737f6e35..7af2a32702 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -3889,14 +3889,8 @@ impl MutationTransaction { { return Err(MutationError::PreconditionFailed); } - let accepted = crate::review_store::load_status_binding( - tx, - registry, - &document.action_id, - document.proposal_id, - frozen, - ) - .await?; + let accepted = + crate::review_store::load_review_status_binding(tx, registry, document, frozen).await?; if let Some(row) = tx .query_opt( "SELECT authority,result_id,result,status,completed_at,available_until @@ -4155,12 +4149,8 @@ impl MutationTransaction { frozen.review_requirement(), CompiledProposalReview::Required { .. } ) { - if let Some(accepted) = crate::review_store::load_status_binding( - tx, - registry, - &document.action_id, - document.proposal_id, - frozen, + if let Some(accepted) = crate::review_store::load_review_status_binding( + tx, registry, document, frozen, ) .await? { diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index e846bd3a29..c4e7047e59 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -20,6 +20,11 @@ use registry_review_client::{ ReviewResultResponse, ReviewResultsQuery, SourceContextBinding, SubjectBinding, SubmissionDigest, }; +use registry_review_protocol::{ + canonical_bytes, ProtocolError, SubmissionIdentity, MAXIMUM_CANONICAL_CREATE_BYTES, + MAXIMUM_IDENTIFIER_BYTES, MAXIMUM_REFERENCE_BYTES, +}; +use serde::Deserialize; use serde_json::Value; use std::collections::BTreeMap; use std::sync::Arc; @@ -30,6 +35,7 @@ use uuid::Uuid; use crate::model::{CompiledProposalReview, CompiledRegistry}; use crate::mutation::MutationError; use crate::postgres::SqlIdentifier; +use crate::proposal_store::ProposalDocument; use crate::proposal_workflow::ProposalSnapshot; const APPLICATION_LEASE_MINIMUM_SECONDS: i64 = 30; @@ -54,13 +60,27 @@ pub(crate) fn stored_submission_digest_compatibility( stored: &SubmissionDigest, accepted: Option<&ReviewRequestAccepted>, ) -> Result<(StoredSubmissionDigestCompatibility, SubmissionDigest), MutationError> { - let current = submission_digest(producer, &request.subject.source, request) - .map_err(|_| MutationError::PreconditionFailed)?; + stored_submission_digest_compatibility_with( + &request.subject.source, + registry_id, + stored, + accepted, + |namespace| submission_digest(producer, namespace, request), + ) +} + +fn stored_submission_digest_compatibility_with( + source: &str, + registry_id: &str, + stored: &SubmissionDigest, + accepted: Option<&ReviewRequestAccepted>, + digest: impl Fn(&str) -> Result, +) -> Result<(StoredSubmissionDigestCompatibility, SubmissionDigest), MutationError> { + let current = digest(source).map_err(|_| MutationError::PreconditionFailed)?; let compatibility = if *stored == current { StoredSubmissionDigestCompatibility::Current } else { - let legacy = submission_digest(producer, registry_id, request) - .map_err(|_| MutationError::PreconditionFailed)?; + let legacy = digest(registry_id).map_err(|_| MutationError::PreconditionFailed)?; if *stored != legacy { return Err(MutationError::PreconditionFailed); } @@ -72,6 +92,63 @@ pub(crate) fn stored_submission_digest_compatibility( Ok((compatibility, current)) } +/// Verify the predecessor's named initiator only for a terminal status read. +/// Its stored request must serialize exactly as issued, with no claim member. +fn verify_previous_status_digest( + producer: &str, + registry_id: &str, + request: &ReviewCreateRequest, + stored_request: &Value, + stored_digest: &SubmissionDigest, + accepted: Option<&ReviewRequestAccepted>, +) -> Result<(), MutationError> { + fn bounded_text(value: &str, maximum: usize) -> bool { + !value.trim().is_empty() && value.len() <= maximum && !value.chars().any(char::is_control) + } + + let valid_initiator = request.initiator.as_ref().is_some_and(|initiator| { + initiator.principal_claim.is_empty() + && bounded_text(&initiator.issuer, MAXIMUM_REFERENCE_BYTES) + && bounded_text(&initiator.subject, MAXIMUM_REFERENCE_BYTES) + }); + if !valid_initiator + || serde_json::to_value(request).map_err(|_| MutationError::PreconditionFailed)? + != *stored_request + || canonical_bytes(request) + .map_err(|_| MutationError::PreconditionFailed)? + .len() + > MAXIMUM_CANONICAL_CREATE_BYTES + { + return Err(MutationError::PreconditionFailed); + } + let mut without_initiator = request.clone(); + without_initiator.initiator = None; + without_initiator + .check() + .map_err(|_| MutationError::PreconditionFailed)?; + + stored_submission_digest_compatibility_with( + &request.subject.source, + registry_id, + stored_digest, + accepted, + |namespace| { + if !bounded_text(producer, MAXIMUM_IDENTIFIER_BYTES) + || !bounded_text(namespace, MAXIMUM_IDENTIFIER_BYTES) + { + return Err(ProtocolError::Text); + } + let bytes = canonical_bytes(&SubmissionIdentity { + producer, + source_namespace: namespace, + request, + })?; + Ok(SubmissionDigest::for_bytes(&bytes)) + }, + )?; + Ok(()) +} + /// A review submission is claimable once it is due and no live lease holds /// it: a `submitting` claim stays with its holder until its lease expires, /// and a `cancelling` row is free when it has no lease or an expired one. @@ -1546,14 +1623,45 @@ pub(crate) async fn load_handoff_status( }) } -/// Read the exact accepted correlation without treating worker state as authority. -/// In particular, cancellation keeps the original accepted binding while it settles. +/// Read the exact accepted correlation with the current request contract, +/// without treating worker state as authority. pub(crate) async fn load_status_binding( client: &impl GenericClient, registry: &CompiledRegistry, action_id: &str, proposal_id: Uuid, frozen: &ProposalSnapshot, +) -> Result, MutationError> { + load_status_binding_inner(client, registry, action_id, proposal_id, frozen, false).await +} + +/// Read the exact accepted correlation for display-free status. Cancellation +/// keeps the original accepted binding while it settles. Terminal work may +/// also retain the previous release's frozen request format. +pub(crate) async fn load_review_status_binding( + client: &impl GenericClient, + registry: &CompiledRegistry, + document: &ProposalDocument, + frozen: &ProposalSnapshot, +) -> Result, MutationError> { + load_status_binding_inner( + client, + registry, + &document.action_id, + document.proposal_id, + frozen, + document.header.is_terminal(), + ) + .await +} + +async fn load_status_binding_inner( + client: &impl GenericClient, + registry: &CompiledRegistry, + action_id: &str, + proposal_id: Uuid, + frozen: &ProposalSnapshot, + allow_previous_initiator: bool, ) -> Result, MutationError> { let CompiledProposalReview::Required { authority: expected_authority, @@ -1574,10 +1682,8 @@ pub(crate) async fn load_status_binding( .await .map_err(|_| MutationError::Unavailable)? .ok_or(MutationError::PreconditionFailed)?; - let create: registry_review_client::ReviewCreateRequest = - serde_json::from_value(row.get(3)).map_err(|_| MutationError::PreconditionFailed)?; - create - .check() + let stored_request: Value = row.get(3); + let create = ReviewCreateRequest::deserialize(&stored_request) .map_err(|_| MutationError::PreconditionFailed)?; let context_reference = format!( "breg:{}:{}:{}:{}", @@ -1615,13 +1721,30 @@ pub(crate) async fn load_status_binding( { return Err(MutationError::PreconditionFailed); } - stored_submission_digest_compatibility( - &row.get::<_, String>(4), - registry.registry_id(), - &create, - &stored_digest, - accepted.as_ref(), - )?; + let producer: String = row.get(4); + if allow_previous_initiator + && create + .initiator + .as_ref() + .is_some_and(|initiator| initiator.principal_claim.is_empty()) + { + verify_previous_status_digest( + &producer, + registry.registry_id(), + &create, + &stored_request, + &stored_digest, + accepted.as_ref(), + )?; + } else { + stored_submission_digest_compatibility( + &producer, + registry.registry_id(), + &create, + &stored_digest, + accepted.as_ref(), + )?; + } Ok(accepted) } @@ -3176,6 +3299,97 @@ fn result_status(status: registry_review_client::ReviewResultStatus) -> &'static mod tests { use super::*; + #[test] + fn previous_status_digest_requires_the_exact_frozen_request_and_acceptance() { + use registry_review_client::PolicyBinding; + use serde_json::json; + + let producer = "review-producer"; + let registry_id = "registry"; + let source = "review-source"; + let previous = json!({ + "policy":{"id":"review-policy"}, + "subject":{"source":source,"type":"proposal","id":"proposal-7","version":"1", + "digest":SubmissionDigest::for_bytes(b"effect")}, + "requesterReference":"proposal-reference", + "initiator":{"issuer":"https://previous.example.test","subject":"previous-human"}, + "context":{"mode":"current-source","binding":{"reference":"breg:registry:action:proposal-7:1"}} + }); + let digest_for = |namespace: &str, value: &Value| { + let identity = json!({"producer":producer,"sourceNamespace":namespace,"request":value}); + SubmissionDigest::for_bytes(&canonical_bytes(&identity).unwrap()) + }; + let request = ReviewCreateRequest::deserialize(&previous).unwrap(); + let old_digest = digest_for(registry_id, &previous); + let source_digest = digest_for(source, &previous); + let mut accepted = ReviewRequestAccepted { + request_id: Uuid::from_u128(1), + subject: request.subject.clone(), + policy: PolicyBinding { + id: request.policy.id.clone(), + version: "1".to_owned(), + digest: SubmissionDigest::for_bytes(b"policy"), + }, + submission_digest: old_digest.clone(), + }; + assert!(request.check().is_err()); + assert!(submission_digest(producer, source, &request).is_err()); + assert!(verify_previous_status_digest( + producer, + registry_id, + &request, + &previous, + &source_digest, + None, + ) + .is_ok()); + assert!(verify_previous_status_digest( + producer, + registry_id, + &request, + &previous, + &old_digest, + Some(&accepted), + ) + .is_ok()); + + accepted.submission_digest = source_digest; + assert!(verify_previous_status_digest( + producer, + registry_id, + &request, + &previous, + &old_digest, + Some(&accepted), + ) + .is_err()); + let changed = |key: &str, value: Value| { + let mut changed = previous.clone(); + changed["initiator"][key] = value; + changed + }; + let empty_claim = changed("principalClaim", json!("")); + let empty_issuer = changed("issuer", json!("")); + let different_subject = changed("subject", json!("different-human")); + for (different, digest) in [ + (&different_subject, &old_digest), + (&empty_claim, &old_digest), + (&empty_claim, &digest_for(registry_id, &empty_claim)), + (&empty_issuer, &digest_for(registry_id, &empty_issuer)), + ] { + let parsed = ReviewCreateRequest::deserialize(different).unwrap(); + assert!(verify_previous_status_digest( + producer, + registry_id, + &parsed, + different, + digest, + None, + ) + .is_err()); + } + } + #[test] fn stored_digest_accepts_only_current_or_exact_legacy_request_and_binding() { let proposal_id = Uuid::new_v4(); diff --git a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx index a55e83444f..98ba463b0a 100644 --- a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx +++ b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx @@ -89,9 +89,12 @@ operator could still resubmit. If `bregctl review-recovery resubmit` reports `initiator-upgrade`, finish or cancel the affected work on the previous matching release. Coordinator holds runs sealed with the earlier Review operation binding before dispatch. -Record any needed BReg review status for older reviews with a named initiator -before upgrading. Reading this status afterward requires a pre-upgrade backup -and its matching release. + +After upgrading, you can still follow the `reviewStatus` link for a retained +terminal BReg Proposal, including one with a named initiator from the previous +release. Your current access profile must grant review status. The response +displays the retained result status and, after acceptance, the provider's +request ID. Review context and initiator details stay private. Update the Casework producer pin and any authored initiator mapping, then recheck and package with the target release. Follow the Casework release notes @@ -99,6 +102,7 @@ for its retained-state requirements before restarting the paired runtimes and clients on the same release. {/* Evidence: crates/registry-breg/src/review_store.rs, check_review_initiator_upgrade; + crates/registry-breg/tests/support/review_go_live.rs, upgrade_preserves_terminal_status_for_a_previous_named_initiator; crates/registry-breg/src/review_recovery.rs, ReviewRecoveryRefusal::InitiatorUpgrade; crates/registry-breg/src/startup.rs, review_binding_startup_error; crates/registry-breg/src/migration.rs, activate; From 4030622e109d0391a4c113269518a113a33de53c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:15:27 +0000 Subject: [PATCH 19/33] test(breg): scope the notification-only activation fixture Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/support/hook_activation.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/registry-breg/tests/support/hook_activation.rs b/crates/registry-breg/tests/support/hook_activation.rs index 3c11883b91..0c343b0d19 100644 --- a/crates/registry-breg/tests/support/hook_activation.rs +++ b/crates/registry-breg/tests/support/hook_activation.rs @@ -789,6 +789,7 @@ async fn classified_proposal_across_activation( .unwrap() .remove("principal") .is_some()); + project["accessProfiles"]["case-hook"]["requiredScopes"] = json!(["records:write"]); } let initial = package(&project, &assets, None).await; let mut setup = activated_setup(&initial, &receiver, false).await; From f4388e23fedf43b2d151881a4d4bbf24dec554f9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:16:05 +0000 Subject: [PATCH 20/33] test(breg): cover status of a refused predecessor review Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/http_auth.rs | 3 + .../tests/support/review_go_live.rs | 125 +++++++++++++++--- 2 files changed, 107 insertions(+), 21 deletions(-) diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index a2d7922e23..4d17cfcfe9 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -4584,6 +4584,9 @@ fn an_unknown_access_profile_on_an_issuer_entry_is_refused() { diag.path, "/authentication/oidc/issuers/first/accessProfiles/0" ); + assert!(diag + .suggested_action + .contains("exclude profiles reserved for proposing Record hooks")); } #[test] diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index d736b4d908..6724c89612 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -1211,11 +1211,41 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { fixture.finish().await; } +async fn previous_named_review( + fixture: &client_http::ClientFixture, + id: Uuid, +) -> (Value, registry_review_protocol::ContentDigest) { + use registry_review_protocol::{canonical_bytes, submission_digest, ContentDigest}; + + let mut previous: Value = fixture + .database + .admin + .query_one( + "SELECT create_request FROM registry_internal.registry_proposal_review_submissions + WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + previous["initiator"] = + json!({"issuer":"https://previous.example.test","subject":"previous-reviewer-canary"}); + let request: ReviewCreateRequest = serde_json::from_value(previous.clone()).unwrap(); + assert!(request.check().is_err()); + assert!(submission_digest(PRODUCER, &request.subject.source, &request).is_err()); + let envelope = json!({ + "producer":PRODUCER, + "sourceNamespace":request.subject.source, + "request":previous + }); + let digest = ContentDigest::for_bytes(&canonical_bytes(&envelope).unwrap()); + (previous, digest) +} + #[tokio::test] async fn upgrade_preserves_terminal_status_for_a_previous_named_initiator() { use registry_breg::review_store::check_review_initiator_upgrade; use registry_breg_client::{BRegProposalReviewHandoffState, BRegProposalState}; - use registry_review_protocol::{canonical_bytes, submission_digest, ContentDigest}; let authority = Authority::start(false, true).await; let (fixture, source) = reviewed_fixture_with_recovery(&authority, false, true).await; @@ -1238,26 +1268,7 @@ async fn upgrade_preserves_terminal_status_for_a_previous_named_initiator() { // Keep a complete predecessor closure with the previous wire shape and // digest in the retained rows, including the provider's recorded result. - let mut previous: Value = db - .query_one( - "SELECT create_request FROM registry_internal.registry_proposal_review_submissions - WHERE proposal_id=$1", - &[&id], - ) - .await - .unwrap() - .get(0); - previous["initiator"] = - json!({"issuer":"https://previous.example.test","subject":"previous-reviewer-canary"}); - let request: ReviewCreateRequest = serde_json::from_value(previous.clone()).unwrap(); - assert!(request.check().is_err()); - assert!(submission_digest(PRODUCER, &accepted.subject.source, &request).is_err()); - let envelope = json!({ - "producer":PRODUCER, - "sourceNamespace":accepted.subject.source, - "request":previous - }); - let digest = ContentDigest::for_bytes(&canonical_bytes(&envelope).unwrap()); + let (previous, digest) = previous_named_review(&fixture, id).await; accepted.submission_digest = digest.clone(); decision.submission_digest = digest; let updated = db @@ -1322,6 +1333,78 @@ async fn upgrade_preserves_terminal_status_for_a_previous_named_initiator() { fixture.finish().await; } +#[tokio::test] +async fn upgrade_preserves_owner_status_after_a_previous_review_was_refused() { + use registry_breg::review_store::{check_review_initiator_upgrade, verify_retained_bindings}; + use registry_breg_client::{ + BRegProposalReviewHandoffReason, BRegProposalReviewHandoffState, BRegProposalState, + }; + + let authority = Authority::start(false, true).await; + let (fixture, _) = reviewed_fixture_with_recovery(&authority, false, true).await; + let proposal = submitted_proposal(&fixture, "retained-refused-review").await; + let id = Uuid::parse_str(proposal.id()).unwrap(); + let (previous, digest) = previous_named_review(&fixture, id).await; + let updated = fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET create_request=$2,expected_submission_digest=$3,state='failed',attempt_count=1, + last_error_code='remote-refused',refusal_code='review.refused' + WHERE proposal_id=$1", + &[&id, &previous, &digest.as_str()], + ) + .await + .unwrap(); + assert_eq!(updated, 1); + + check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) + .await + .unwrap(); + let ReviewRecoveryError::Ineligible { + reason, + state, + code, + } = recovery(&fixture, &fixture.registry, &fixture.identity) + .resubmit(scope(id)) + .await + .expect_err("a provider refusal ends this review submission") + else { + panic!("resubmit must preserve the existing failure reason"); + }; + assert_eq!(reason.as_str(), "submission-state"); + assert_eq!(state, "failed"); + assert_eq!(code.as_deref(), Some("remote-refused")); + + let client = &fixture.http.client; + let submitted = client.read_proposal(&proposal).await.unwrap().value; + assert_eq!(submitted.state(), BRegProposalState::Submitted); + assert_eq!(submitted.blocked_reason(), None); + assert!(submitted.link("reviewStatus").is_some()); + let status = client + .read_proposal_review_status(&submitted) + .await + .unwrap() + .value; + let handoff = status.handoff.as_ref().unwrap(); + assert_eq!(handoff.state, BRegProposalReviewHandoffState::Failed); + assert_eq!( + handoff.reason, + Some(BRegProposalReviewHandoffReason::RemoteRefused) + ); + assert!(status.request_id.is_none()); + assert!(status.progress_code.is_none()); + assert!(status.context.fields.is_none()); + assert!(status.context.asks.is_empty()); + assert!(!json!(status) + .to_string() + .contains("previous-reviewer-canary")); + assert_eq!(authority.state.requests.load(Ordering::SeqCst), 0); + fixture.finish().await; +} + #[tokio::test] async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { use registry_breg::review_store::{check_review_initiator_upgrade, verify_retained_bindings}; From 24f831743c12d5572d63b819a45fc9083b8e3b7a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:17:30 +0000 Subject: [PATCH 21/33] fix(breg): preserve status of exact retained reviews after upgrade Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/review_store.rs | 11 ++++++----- crates/registry-breg/src/runtime_config.rs | 11 +++++------ .../docs/operate/advanced/upgrade-and-retire.mdx | 10 ++++++---- products/breg/CHANGELOG.md | 8 +++++--- 4 files changed, 22 insertions(+), 18 deletions(-) diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index c4e7047e59..b6480c1592 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -92,7 +92,7 @@ fn stored_submission_digest_compatibility_with( Ok((compatibility, current)) } -/// Verify the predecessor's named initiator only for a terminal status read. +/// Verify the predecessor's named initiator only for a display-free status read. /// Its stored request must serialize exactly as issued, with no claim member. fn verify_previous_status_digest( producer: &str, @@ -1635,9 +1635,10 @@ pub(crate) async fn load_status_binding( load_status_binding_inner(client, registry, action_id, proposal_id, frozen, false).await } -/// Read the exact accepted correlation for display-free status. Cancellation -/// keeps the original accepted binding while it settles. Terminal work may -/// also retain the previous release's frozen request format. +/// Read the exact retained correlation for display-free status. The original +/// frozen request and any accepted binding govern this metadata read. +/// Cancellation keeps the original accepted binding while it settles. +/// Eligibility to dispatch or resume the Review is independent of this read. pub(crate) async fn load_review_status_binding( client: &impl GenericClient, registry: &CompiledRegistry, @@ -1650,7 +1651,7 @@ pub(crate) async fn load_review_status_binding( &document.action_id, document.proposal_id, frozen, - document.header.is_terminal(), + true, ) .await } diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 8a83ee1fc7..3b16a75706 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -2845,7 +2845,7 @@ impl AuthenticationConfig { let pointer = format!("{}/accessProfiles/{index}", entry.pointer()); let code = "breg.runtime.unknown-access-profile"; let message = "This issuer entry names an access profile that the compiled registry does not declare."; - let action = "List only access profiles declared in the registry project, or omit accessProfiles to reach every profile."; + let action = "List only declared profiles available to HTTP, or omit accessProfiles to use the default HTTP profiles, which exclude profiles reserved for proposing Record hooks."; let diag = if let Some(check) = check { check.error_at(RUNTIME_CONFIG_KIND, code, &pointer, message, action) } else { @@ -3262,8 +3262,8 @@ impl OidcVerifierConfig { }) } - /// The compiled access profiles this issuer entry may reach, or `None` when - /// it reaches every profile in the package. + /// The explicit access profile list, or `None` to use the package's default + /// HTTP reach, which excludes profiles reserved for proposing Record hooks. #[must_use] pub fn access_profiles(&self) -> Option<&[String]> { self.access_profiles.as_deref() @@ -4497,8 +4497,7 @@ fn non_empty_revoked_key_ids<'de, D: serde::Deserializer<'de>>( Ok(kids) } -/// An empty list is not how the file says "reach every profile" (CFG-EMPTY-2): -/// omitting `accessProfiles` says it. +/// Omit `accessProfiles` for the default HTTP reach (CFG-EMPTY-2). fn optional_non_empty_access_profiles<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> std::result::Result>, D::Error> { @@ -4506,7 +4505,7 @@ fn optional_non_empty_access_profiles<'de, D: serde::Deserializer<'de>>( if profiles.as_ref().is_some_and(Vec::is_empty) { return Err(registry_platform_yaml::Invalid::expected( "at least one access profile", - "List at least one access profile this issuer entry reaches, or omit accessProfiles to reach every profile.", + "List at least one access profile this issuer entry reaches, or omit accessProfiles to use the default HTTP profiles, which exclude profiles reserved for proposing Record hooks.", ) .into_error()); } diff --git a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx index 98ba463b0a..a5262dab5f 100644 --- a/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx +++ b/docs/site/src/content/docs/operate/advanced/upgrade-and-retire.mdx @@ -91,10 +91,11 @@ matching release. Coordinator holds runs sealed with the earlier Review operation binding before dispatch. After upgrading, you can still follow the `reviewStatus` link for a retained -terminal BReg Proposal, including one with a named initiator from the previous -release. Your current access profile must grant review status. The response -displays the retained result status and, after acceptance, the provider's -request ID. Review context and initiator details stay private. +BReg Review with a named initiator from the previous release. This includes +a provider refusal on a Proposal that remains submitted. Your current access +profile must grant review status. The response shows the handoff and result +status and, after acceptance, the provider's request ID. Review context and +initiator details stay private. Update the Casework producer pin and any authored initiator mapping, then recheck and package with the target release. Follow the Casework release notes @@ -103,6 +104,7 @@ clients on the same release. {/* Evidence: crates/registry-breg/src/review_store.rs, check_review_initiator_upgrade; crates/registry-breg/tests/support/review_go_live.rs, upgrade_preserves_terminal_status_for_a_previous_named_initiator; + crates/registry-breg/tests/support/review_go_live.rs, upgrade_preserves_owner_status_after_a_previous_review_was_refused; crates/registry-breg/src/review_recovery.rs, ReviewRecoveryRefusal::InitiatorUpgrade; crates/registry-breg/src/startup.rs, review_binding_startup_error; crates/registry-breg/src/migration.rs, activate; diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index e311122419..9677ace671 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -49,9 +49,11 @@ to the selection before regenerating. - BREAKING: Before upgrading BReg, settle or cancel outstanding Proposal reviews with a named initiator using the previous matching release. - Startup, plan and apply refuse retained work that lacks the initiator's - claim binding. Export any needed historical review status before upgrading - because older named-initiator status reads require the previous release. + Startup, plan and apply refuse unfinished work that lacks the initiator's + claim binding, including failed reviews that an operator could resubmit. + After upgrading, current review-status grants still allow read-only access + to exact retained Review metadata, including provider refusals on submitted + Proposals. - Record and read-path permissions can select stored fields with `readableFields.upToClassification`. Consent-gated permissions require From 340de377d86ca3a4a3eefb2cc6fa337fee0ee4a7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:19:48 +0000 Subject: [PATCH 22/33] docs(breg): clarify issuer reach for reserved hook profiles Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/auth.rs | 2 +- crates/registry-breg/src/runtime_config.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 1dd3cd7486..d8e9a5aa97 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -295,7 +295,7 @@ struct IssuerRules { /// the allowance for a task-grant token's `iat` ahead of this clock. leeway: Duration, /// The compiled access profiles this issuer entry may reach, or `None` for - /// every profile in the package. + /// all HTTP-reachable profiles. access_profiles: Option>, } diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 3b16a75706..d7575cd140 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -4461,9 +4461,9 @@ struct RawOidcVerifierConfig { /// Optional JWKS fetch and cache tuning. Defaults to bounded cache behavior. #[serde(default)] jwks_cache: RawJwksCacheConfig, - /// The compiled access profiles this issuer entry may reach. Omitted, it - /// reaches every profile in the package; written, it lists at least one - /// profile identifier. + /// The compiled access profiles this issuer entry may reach. Omit the list + /// to reach all HTTP-reachable profiles. An explicit list needs at least + /// one profile identifier. Record hook profiles are reserved for delivery. #[serde( default, skip_serializing_if = "Option::is_none", From 10a2e8d2cdddceaaa47da7beca666f48e02c0cb3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:23:35 +0000 Subject: [PATCH 23/33] docs(breg): describe hook profile compilation and application Signed-off-by: Jeremi Joslin --- products/breg/CHANGELOG.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 9677ace671..1db5251370 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -31,12 +31,12 @@ 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`. -- BREAKING: A Record hook that declares a proposal `principal` makes that - project access profile internal-only. It must use unrestricted scopes and - have no live caller requirements. BReg automatically excludes it from - issuer HTTP reach when `accessProfiles` is omitted and refuses a runtime - issuer that lists it explicitly. Keep ordinary HTTP access on another - profile, and omit `principal` for a notification-only hook. +- BREAKING: BReg reserves a Record hook's proposal `principal` for hook + delivery. When `accessProfiles` is omitted, issuer HTTP access includes only + HTTP-reachable profiles. BReg refuses an issuer that lists the reserved + profile explicitly. Applying a hook Proposal requires an Action grant that + runs without caller context. Keep ordinary HTTP access on another profile, + and omit `principal` for a notification-only hook. - PublicSchema derivation classifies application and decision subject references as restricted in their respective Record types. Review the access profiles of existing derived projects before redeploying. From 09b12e5daa5f1881b9b61cca99a321d5453b04eb Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:26:14 +0000 Subject: [PATCH 24/33] docs(breg): regenerate issuer access profile description Signed-off-by: Jeremi Joslin --- products/breg/generated/runtime/runtime.schema.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/breg/generated/runtime/runtime.schema.json b/products/breg/generated/runtime/runtime.schema.json index d147742477..d18a91c4b1 100644 --- a/products/breg/generated/runtime/runtime.schema.json +++ b/products/breg/generated/runtime/runtime.schema.json @@ -1603,7 +1603,7 @@ "description": "One issuer a token may come from: the members every caller issuer entry\nshares, and the verification rules this registry adds.", "properties": { "accessProfiles": { - "description": "The compiled access profiles this issuer entry may reach. Omitted, it\nreaches every profile in the package; written, it lists at least one\nprofile identifier.", + "description": "The compiled access profiles this issuer entry may reach. Omit the list\nto reach all HTTP-reachable profiles. An explicit list needs at least\none profile identifier. Record hook profiles are reserved for delivery.", "items": { "$ref": "#/$defs/LocalId" }, From 249ea64132409058a83f1b3f819e0915e1dcf572 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:34:51 +0000 Subject: [PATCH 25/33] docs(breg): record the accepted scope of proposing hook writes Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/operate/breg-webhooks.mdx | 6 ++++++ products/breg/contracts/security-invariant-matrix.yaml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/operate/breg-webhooks.mdx b/docs/site/src/content/docs/operate/breg-webhooks.mdx index 0c6aaea65d..c6184ac403 100644 --- a/docs/site/src/content/docs/operate/breg-webhooks.mdx +++ b/docs/site/src/content/docs/operate/breg-webhooks.mdx @@ -219,6 +219,12 @@ use `requiredScopes: unrestricted` and omit `requiredPurposes`, `actorKind`, `re target's `rowBoundaries` to `unrestricted`. At application, the worker checks the compiled grant and refuses caller-dependent grants and targets with claim or membership boundaries. +The handler can write any Record of a type declared by the Action, including a Record other than +the one that triggered the hook. The Action's declared fields limit each write. For a URL handler, +the operator configures the receiver and BReg signs each delivery with HMAC. BReg records the +triggering event in the causation of the resulting write. The integration test creates a separate +follow-up Record from a case event. + BReg reserves the bound profile for the hook and exempts it from the principal-boundary requirement for open writes. When an issuer omits `accessProfiles`, BReg excludes the reserved profile from HTTP access. An issuer that lists the profile explicitly is refused with diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index bca2772b9d..41b918bcbd 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -311,4 +311,4 @@ invariants: # Explicit issuer reach: crates/registry-breg/tests/http_auth.rs::an_issuer_entry_cannot_explicitly_reach_a_proposing_hook_profile and authenticator_construction_refuses_an_explicit_proposing_hook_profile # Exact source binding: crates/registry-breg/tests/postgres_webhook_outbox.rs::real_postgres_webhook_outbox_capture_is_atomic_package_bound_and_deterministically_identified # Action Invoke dispatch: crates/registry-breg/src/api/tests/immediate_action_tests.rs::internal_hook_profile_is_excluded_from_action_invoke_http_authority - - {id: BREG-SEC-291, state: enforced, targetWave: W5, threat: "An HTTP caller selects the Action profile reserved for a proposing Record hook, the hook borrows caller authority it does not hold, or a loaded delivery substitutes another profile binding.", enforcementPoint: "Authentication excludes every proposing Record hook profile from issuer HTTP reach and refuses an issuer that explicitly lists one. The compiler requires a handler and an existing project access profile for a hook declaring principal. Only these bound profiles are exempt from the open-write principal-boundary check. Mutation planning re-derives the principal from the governed hook and live proposal application rechecks the compiled Action grant.", refusal: "Refuse explicit issuer reach with breg.runtime.hook-profile-http-reachable and HTTP selection with profile.not-authorized. Refuse a missing handler with breg.event.delivery-required and an unknown profile with breg.event.hook-authority-unknown. Refuse a principal-unbounded open HTTP write with breg.access.open-write-without-principal-boundary. Refuse a caller-dependent compiled Action grant at application with hook.proposal.unauthorized and apply no Record mutation. Notification-only hooks that omit principal remain valid.", negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} + - {id: BREG-SEC-291, state: enforced, targetWave: W5, threat: "An HTTP caller selects the Action profile reserved for a proposing Record hook, the hook borrows caller authority it does not hold, or a loaded delivery substitutes another profile binding.", enforcementPoint: "Authentication excludes every proposing Record hook profile from issuer HTTP reach and refuses an issuer that explicitly lists one. The compiler requires a handler and an existing project access profile for a hook declaring principal. Only these bound profiles are exempt from the open-write principal-boundary check. Mutation planning re-derives the principal from the governed hook and live proposal application rechecks the compiled Action grant. The handler can write any Record of an Action-declared type through its declared fields, including a Record other than the one that triggered the hook. The operator configures the URL receiver, BReg signs the delivery with HMAC, and the resulting write records causation.", refusal: "Refuse explicit issuer reach with breg.runtime.hook-profile-http-reachable and HTTP selection with profile.not-authorized. Refuse a missing handler with breg.event.delivery-required and an unknown profile with breg.event.hook-authority-unknown. Refuse a principal-unbounded open HTTP write with breg.access.open-write-without-principal-boundary. Refuse a caller-dependent compiled Action grant at application with hook.proposal.unauthorized and apply no Record mutation. Notification-only hooks that omit principal remain valid.", negativeId: BREG-NEG-291, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_omitted_issuer_profile_list_keeps_hook_authority_off_http_routes}} From 1381a5a26433174d581eda2d19de8099f25de1da Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:34:44 +0000 Subject: [PATCH 26/33] test(breg): cover progress reads after a retained review refusal Signed-off-by: Jeremi Joslin --- .../postgres_proposal_review_delivery.rs | 42 +++++++++++++++++- .../tests/support/review_go_live.rs | 44 +++++++++++++++++-- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs index 476ce5819a..4f481bc06c 100644 --- a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs +++ b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs @@ -183,6 +183,7 @@ impl Authority { }); let app = Router::new() .route("/v1/review-requests", post(create_review)) + .route("/v1/review-requests/{id}", get(lookup_progress)) .route("/v1/review-requests/{id}/cancel", post(cancel_review)) .route("/v1/review-requests/{id}/result", get(lookup_result)) .route("/v1/review-results", get(empty_feed)) @@ -378,6 +379,42 @@ async fn lookup_result( ), } } +async fn lookup_progress( + State(state): State>, + AxumPath(id): AxumPath, + axum::extract::RawQuery(query): axum::extract::RawQuery, + headers: HeaderMap, +) -> Response { + state.requests.fetch_add(1, Ordering::SeqCst); + assert_eq!( + headers.get("authorization").unwrap(), + format!("Bearer {OUTGOING_TOKEN}").as_str() + ); + assert_eq!( + query.as_deref(), + Some("include=progress&accessProfile=producer") + ); + let accepted = state.accepted.lock().unwrap().clone().unwrap(); + assert_eq!(id, accepted.request_id); + let now = chrono::Utc::now(); + response( + StatusCode::OK, + json!(registry_review_client::ReviewRequestView { + request_id: id, + subject: accepted.subject, + policy: accepted.policy, + submission_digest: accepted.submission_digest, + requester_reference: "progress-test".into(), + lifecycle: registry_review_client::ReviewRequestLifecycle::Reviewing, + active_stage: Some("internal-stage".into()), + progress_code: Some( + registry_review_client::ReviewProgressCode::parse("institution-check").unwrap(), + ), + created_at: now, + updated_at: now, + }), + ) +} async fn empty_feed() -> Response { response(StatusCode::OK, json!({"items":[]})) } @@ -403,9 +440,12 @@ fn result( } } fn claims() -> VerifiedRequestClaims { + claims_for("author-canary") +} +fn claims_for(principal: &str) -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "sub", - "author-canary", + principal, BTreeSet::from(["proposal:manage".into()]), Some("registry-administration".into()), BTreeMap::from([( diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index 6724c89612..f067827233 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -61,6 +61,8 @@ async fn reviewed_fixture_options( ]); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableContextFields"] = json!(["proposedName"]); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0] + ["readableReviewProgress"] = json!(true); } if !automatic { source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] @@ -1398,10 +1400,46 @@ async fn upgrade_preserves_owner_status_after_a_previous_review_was_refused() { assert!(status.progress_code.is_none()); assert!(status.context.fields.is_none()); assert!(status.context.asks.is_empty()); - assert!(!json!(status) - .to_string() - .contains("previous-reviewer-canary")); + let local = json!(status); + assert!(!local.to_string().contains("previous-reviewer-canary")); + let progress = client + .read_proposal_review_status_with_progress(&submitted) + .await + .unwrap(); + assert_eq!(json!(progress.value), local); + assert!(progress.metadata.etag().is_none()); assert_eq!(authority.state.requests.load(Ordering::SeqCst), 0); + + let current = submitted_proposal(&fixture, "current-review-progress").await; + send(&fixture, &authority).await; + let current = client.read_proposal(¤t).await.unwrap().value; + let progress = client + .read_proposal_review_status_with_progress(¤t) + .await + .unwrap(); + assert_eq!( + progress.value.handoff.unwrap().state, + BRegProposalReviewHandoffState::Accepted + ); + assert_eq!( + progress.value.progress_code.unwrap().as_str(), + "institution-check" + ); + assert_eq!(authority.state.requests.load(Ordering::SeqCst), 2); + + let other = fixture.client_for(claims_for("other-author-canary")).await; + let denied = reqwest::Client::new() + .get(format!( + "{}/v1/proposals/{}/review-status?accessProfile=clerk&include=progress", + other.base_url, + current.id() + )) + .send() + .await + .unwrap(); + assert_eq!(denied.status(), StatusCode::NOT_FOUND); + assert_eq!(authority.state.requests.load(Ordering::SeqCst), 2); + drop(other); fixture.finish().await; } From 159e5f180d6e04761b567e9f94c37b01feeced74 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:35:54 +0000 Subject: [PATCH 27/33] fix(breg): preserve local review status when progress has ended Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/review_store.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index b6480c1592..57e3c7d5e1 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -1798,11 +1798,6 @@ pub(crate) async fn load_progress_binding( else { return Ok(None); }; - let Some(accepted) = - load_status_binding(client, registry, action_id, proposal_id, frozen).await? - else { - return Ok(None); - }; let row = client .query_opt( "SELECT s.authority,s.producer_id,s.state,s.withdrawn,s.accepted_binding, @@ -1819,17 +1814,22 @@ pub(crate) async fn load_progress_binding( .await .map_err(|_| MutationError::Unavailable)? .ok_or(MutationError::PreconditionFailed)?; + // The local status already validates retained correlation. Only a live + // acceptance needs the current request contract for a provider lookup. + if row.get::<_, String>(2) != "accepted" || row.get::<_, bool>(3) || !row.get::<_, bool>(5) { + return Ok(None); + } + let Some(accepted) = + load_status_binding(client, registry, action_id, proposal_id, frozen).await? + else { + return Ok(None); + }; let retained: ReviewRequestAccepted = serde_json::from_value( row.get::<_, Option>(4) .ok_or(MutationError::PreconditionFailed)?, ) .map_err(|_| MutationError::PreconditionFailed)?; - if row.get::<_, String>(0) != *expected_authority - || row.get::<_, String>(2) != "accepted" - || row.get::<_, bool>(3) - || retained != accepted - || !row.get::<_, bool>(5) - { + if row.get::<_, String>(0) != *expected_authority || retained != accepted { return Ok(None); } Ok(Some(ReviewProgressBinding { From b9266339eb4996ec85b51ad23337f5815e30fc93 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:42:36 +0000 Subject: [PATCH 28/33] docs(breg): clarify issuer profile restrictions Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/api/context.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index d50345bd58..6cff4d7753 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -208,8 +208,8 @@ impl VerifiedRequestClaims { }) } - /// Restrict the access profiles this caller may reach to those named on the - /// verifying issuer entry. `None` reaches every profile in the package. + /// Restrict profile reachability to those named on the verifying issuer + /// entry. `None` imposes no issuer-specific restriction. #[must_use] pub(crate) fn with_reachable_profiles(mut self, profiles: Option>) -> Self { self.reachable_profiles = profiles; From 5d2bc8b5f5171667cbbce8350a17d8217c259624 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:50:46 +0000 Subject: [PATCH 29/33] chore(breg): bind the generated runtime schema digest Signed-off-by: Jeremi Joslin --- products/identifiers/generated/catalog.v1.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index ae6e81e053..313262536b 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -6166,7 +6166,7 @@ }, "artifact": { "path": "products/breg/generated/runtime/runtime.schema.json", - "sha256": "e99a03becdfdf693da8cbdd8e37319a4c1ce2f9c1588ec78c4813005e9f0f0c2", + "sha256": "feb29c3b0909b5334f40cf633cf22792e27e8b85c5c70e51015c0968685fd40c", "mediaType": "application/schema+json" } }, From 017227e188525933b212a6caffccea427d286945 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:04:08 +0000 Subject: [PATCH 30/33] test(breg): cover predecessor cancellation after a retained refusal Signed-off-by: Jeremi Joslin --- .../postgres_proposal_review_delivery.rs | 26 +++ .../tests/support/review_go_live.rs | 198 ++++++++++++++++++ 2 files changed, 224 insertions(+) diff --git a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs index 4f481bc06c..b9ff9f4c46 100644 --- a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs +++ b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs @@ -142,10 +142,12 @@ struct AuthorityState { gates: [Gate; 2], gated: bool, first_succeeds: bool, + refuse_create: AtomicBool, cancel_already_terminal: AtomicBool, result_replies: [ResultReply; 2], requests: AtomicUsize, creates: Mutex>, + cancellations: Mutex>, accepted: Mutex>, result_id: Uuid, } @@ -174,10 +176,12 @@ impl Authority { gates: [Gate::default(), Gate::default()], gated, first_succeeds, + refuse_create: false.into(), cancel_already_terminal: false.into(), result_replies, requests: 0.into(), creates: Mutex::new(Vec::new()), + cancellations: Mutex::new(Vec::new()), accepted: Mutex::new(None), result_id: Uuid::new_v4(), }); @@ -307,10 +311,27 @@ async fn create_review( if call == 0 && !state.first_succeeds { return response(StatusCode::SERVICE_UNAVAILABLE, json!({})); } + if state.refuse_create.load(Ordering::SeqCst) { + return ( + StatusCode::FORBIDDEN, + [ + ("content-type", "application/problem+json"), + ("traceparent", TRACE), + ], + json!({ + "type":"https://review-provider.example.test/problems/refused", + "title":"Review refused","status":403,"code":"producer.refused", + "traceId":"0123456789abcdef0123456789abcdef" + }) + .to_string(), + ) + .into_response(); + } response(StatusCode::CREATED, json!(accepted)) } async fn cancel_review( State(state): State>, + AxumPath(id): AxumPath, axum::extract::Query(query): axum::extract::Query>, headers: HeaderMap, Json(request): Json, @@ -319,6 +340,11 @@ async fn cancel_review( request.check().unwrap(); let accepted = state.accepted.lock().unwrap().clone().unwrap(); assert_eq!(request.subject, accepted.subject); + state.cancellations.lock().unwrap().push(( + id, + headers["idempotency-key"].to_str().unwrap().into(), + request, + )); let call = state.requests.fetch_add(1, Ordering::SeqCst); if state.gated { if let Some(gate) = state.gates.get(call) { diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index f067827233..d2359aafb4 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -1443,6 +1443,204 @@ async fn upgrade_preserves_owner_status_after_a_previous_review_was_refused() { fixture.finish().await; } +#[tokio::test] +async fn upgrade_dispatches_previous_review_cancellation_after_owner_withdrawal() { + previous_accepted_review_cancellation(true).await; +} + +#[tokio::test] +async fn upgrade_dispatches_previous_review_cancellation_after_incompatible_activation() { + previous_accepted_review_cancellation(false).await; +} + +async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { + use registry_breg::{ + migration::MigrationError, + review_store::{ + check_review_initiator_upgrade, verify_retained_bindings, RetainedReviewBindingError, + }, + }; + use registry_breg_client::BRegProposalState; + + let authority = + Authority::start_with_results(false, true, [ResultReply::Pending, ResultReply::Unknown]) + .await; + let (fixture, mut successor) = reviewed_fixture_with_recovery(&authority, true, true).await; + let proposal = submitted_proposal(&fixture, "retained-review-cancellation").await; + let id = Uuid::parse_str(proposal.id()).unwrap(); + send(&fixture, &authority).await; + let mut accepted = authority.state.accepted.lock().unwrap().clone().unwrap(); + assert_eq!(job(&fixture, id).await["binding"], json!(accepted)); + + assert!( + run_review_authority_once_for_test(&fixture.pool, &authority.registry, &fixture.mutations) + .await + .unwrap() + ); + assert_eq!(job(&fixture, id).await["error"], "result-unknown-to-authority"); + let operator = recovery(&fixture, &fixture.registry, &fixture.identity); + assert_eq!(operator.resubmit(scope(id)).await.unwrap().state, "pending"); + authority.state.refuse_create.store(true, Ordering::SeqCst); + send(&fixture, &authority).await; + let refused = job(&fixture, id).await; + assert_eq!(refused["state"], "failed"); + assert_eq!(refused["error"], "remote-refused"); + assert_eq!(refused["binding"], json!(accepted)); + let creates = authority.state.creates.lock().unwrap().clone(); + assert_eq!(creates.len(), 2); + assert_eq!(creates[0], creates[1]); + + // Represent the same accepted and refused round as retained by the predecessor. + let (previous, digest) = previous_named_review(&fixture, id).await; + accepted.submission_digest = digest; + let db = &fixture.database.admin; + assert_eq!( + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET create_request=$2,expected_submission_digest=$3,accepted_binding=$4 + WHERE proposal_id=$1", + &[&id, &previous, &accepted.submission_digest.as_str(), &json!(accepted)], + ) + .await + .unwrap(), + 1 + ); + *authority.state.accepted.lock().unwrap() = Some(accepted.clone()); + + check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + let ReviewRecoveryError::Ineligible { reason, state, code } = + operator.resubmit(scope(id)).await.unwrap_err() + else { + panic!("a provider refusal ends submission recovery even with a retained acceptance"); + }; + assert_eq!(reason.as_str(), "submission-state"); + assert_eq!(state, "failed"); + assert_eq!(code.as_deref(), Some("remote-refused")); + + if withdraw_by_owner { + let client = &fixture.http.client; + let refused = client.read_proposal(&proposal).await.unwrap().value; + let cancel = client + .prepare_proposal( + &refused, + "cancel", + json!({}), + &BRegIdempotencyKey::parse("withdraw-retained-review").unwrap(), + ) + .unwrap(); + let cancelled = client.execute_proposal(&cancel).await.unwrap().value; + assert_eq!(cancelled.state(), BRegProposalState::Cancelled); + assert_eq!(job(&fixture, id).await["state"], "cancelling"); + check_review_initiator_upgrade(&fixture.pool) + .await + .expect("an owner withdrawal leaves only the retained cancellation to dispatch"); + } + + successor["actions"]["correct-name"]["inputs"] + .as_array_mut() + .unwrap() + .push(json!({"id":"review-note","type":"string","maximumLength":32,"required":false,"classification":"internal"})); + successor["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("review-note")); + let (package, active) = proposal_activation::activate_with_compatibility( + &fixture, + &fixture.registry, + &fixture.identity, + &successor, + Some(&authority.registry), + ) + .await; + let cancelling = job(&fixture, id).await; + assert_eq!(cancelling["state"], "cancelling"); + assert_eq!(cancelling["binding"], json!(accepted)); + verify_retained_bindings(&fixture.pool, package.registry(), Some(&authority.registry)) + .await + .expect("startup admits the exact retained cancellation after activation"); + + if withdraw_by_owner { + // A retained JSON object alone is insufficient to resolve the acceptance. + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET accepted_binding='{}'::jsonb WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap(); + assert_eq!( + check_review_initiator_upgrade(&fixture.pool).await, + Err(MigrationError::ReviewInitiatorUpgrade) + ); + assert_eq!( + verify_retained_bindings(&fixture.pool, package.registry(), Some(&authority.registry)) + .await, + Err(RetainedReviewBindingError::ReviewInitiatorUpgrade) + ); + db.execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET accepted_binding=$2 WHERE proposal_id=$1", + &[&id, &json!(accepted)], + ) + .await + .unwrap(); + assert_eq!(job(&fixture, id).await, cancelling); + } + + let ReviewRecoveryError::Ineligible { reason, .. } = + recovery(&fixture, package.registry(), &active) + .resubmit(scope(id)) + .await + .unwrap_err() + else { + panic!("withdrawn work cannot return to submission"); + }; + let expected_refusal = if withdraw_by_owner { + "withdrawn" + } else { + "package-changed" + }; + assert_eq!(reason.as_str(), expected_refusal); + let (http, mutations) = + active_package_client(&fixture, package.registry(), &active, &authority, claims()).await; + let requests = authority.state.requests.load(Ordering::SeqCst); + assert!(run_review_authority_once_for_test(&fixture.pool, &authority.registry, &mutations) + .await + .unwrap()); + assert_eq!(authority.state.requests.load(Ordering::SeqCst), requests + 1); + let cancellations = authority.state.cancellations.lock().unwrap().clone(); + assert_eq!(cancellations.len(), 1); + assert_eq!(cancellations[0].0, accepted.request_id); + assert_eq!(cancellations[0].1, format!("{}-cancel", creates[0].0)); + assert_eq!(cancellations[0].2.subject, accepted.subject); + assert_eq!(*authority.state.creates.lock().unwrap(), creates); + + let cancelled = job(&fixture, id).await; + assert_eq!(cancelled["state"], "cancelled"); + assert_eq!(cancelled["binding"], json!(accepted)); + let terminal = db + .query_one( + "SELECT s.create_request,r.result + FROM registry_internal.registry_proposal_review_results r + JOIN registry_internal.registry_proposal_review_submissions s + USING (action_id,proposal_id,submission_version) + WHERE r.proposal_id=$1", + &[&id], + ) + .await + .unwrap(); + assert_eq!(terminal.get::<_, Value>(0), previous); + let terminal: ReviewResult = serde_json::from_value(terminal.get(1)).unwrap(); + assert_eq!(terminal.status, ReviewResultStatus::Cancelled); + assert_eq!(terminal.request_id, accepted.request_id); + assert_eq!(terminal.subject, accepted.subject); + assert_eq!(terminal.policy, accepted.policy); + assert_eq!(terminal.submission_digest, accepted.submission_digest); + assert!(application_jobs(&fixture, id).await.is_empty()); + drop(http); + fixture.finish().await; +} + #[tokio::test] async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { use registry_breg::review_store::{check_review_initiator_upgrade, verify_retained_bindings}; From 07f1b5af64f10c1dda01c7292b4979d707405236 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:09:57 +0000 Subject: [PATCH 31/33] fix(breg): admit exact predecessor cancellations at upgrade Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/migration.rs | 1 + crates/registry-breg/src/review_store.rs | 171 +++++++++++++----- .../tests/support/review_go_live.rs | 93 +++++++--- .../registry-bregctl/src/apply_lifecycle.rs | 15 +- 4 files changed, 206 insertions(+), 74 deletions(-) diff --git a/crates/registry-breg/src/migration.rs b/crates/registry-breg/src/migration.rs index 87730c8e37..26d495894b 100644 --- a/crates/registry-breg/src/migration.rs +++ b/crates/registry-breg/src/migration.rs @@ -1382,6 +1382,7 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> // when plan would otherwise return an unchanged activation. match crate::review_store::review_initiator_upgrade_required( connection.client_for_proposal_retention_guard(), + request.package.registry().registry_id(), ) .await { diff --git a/crates/registry-breg/src/review_store.rs b/crates/registry-breg/src/review_store.rs index 57e3c7d5e1..3008689378 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -29,7 +29,7 @@ use serde_json::Value; use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; -use tokio_postgres::{GenericClient, Transaction}; +use tokio_postgres::{GenericClient, Row, Transaction}; use uuid::Uuid; use crate::model::{CompiledProposalReview, CompiledRegistry}; @@ -92,9 +92,10 @@ fn stored_submission_digest_compatibility_with( Ok((compatibility, current)) } -/// Verify the predecessor's named initiator only for a display-free status read. +/// Verify the predecessor's named initiator for display-free status or +/// cancellation using a retained acceptance. /// Its stored request must serialize exactly as issued, with no claim member. -fn verify_previous_status_digest( +fn verify_previous_submission_digest( producer: &str, registry_id: &str, request: &ReviewCreateRequest, @@ -170,6 +171,9 @@ const RETAINED_REVIEW_SUBMISSION: &str = (s.action_id,s.proposal_id,s.submission_version) AND w.state='submitted'))"; +const REVIEW_BINDING_COLUMNS: &str = "s.authority,s.proposal_digest,s.expected_policy, + s.create_request,s.producer_id,s.expected_submission_digest,s.accepted_binding"; + /// A named initiator from before claim binding. The preflight and operator /// recovery read the same predicate on a review submission aliased as `s`. pub(crate) const PREVIOUS_REVIEW_INITIATOR: &str = @@ -186,6 +190,7 @@ pub const REVIEW_INITIATOR_UPGRADE_ADVICE: &str = "retained Review requests use /// Inspect resumable Review work without claiming a job or rewriting a request. pub(crate) async fn review_initiator_upgrade_required( client: &impl GenericClient, + registry_id: &str, ) -> Result { let has_review_store: bool = client .query_one( @@ -201,15 +206,16 @@ pub(crate) async fn review_initiator_upgrade_required( .into_iter() .map(str::to_owned) .collect::>(); - // Failed requests count for the format check exactly when operator - // recovery could requeue them. Authority retention has its own lifecycle. - let row = client + // Failed requests count here exactly when operator recovery could requeue + // them. Withdrawn cancellations have their own accepted-binding check. + let create_required: bool = client .query_one( &format!( "SELECT EXISTS ( SELECT 1 FROM registry_internal.registry_proposal_review_submissions s WHERE ({PREVIOUS_REVIEW_INITIATOR}) - AND (({RETAINED_REVIEW_SUBMISSION}) + AND ((({RETAINED_REVIEW_SUBMISSION}) + AND (s.state<>'cancelling' OR NOT s.withdrawn)) OR (s.state='failed' AND NOT s.withdrawn AND s.last_error_code=ANY($1) AND NOT {REVIEW_RESULT_RECORDED} @@ -221,8 +227,57 @@ pub(crate) async fn review_initiator_upgrade_required( ), &[&resubmittable_codes], ) + .await? + .get(0); + if create_required { + return Ok(true); + } + + let cancellations = client + .query( + &format!( + "SELECT {REVIEW_BINDING_COLUMNS},s.action_id,s.proposal_id,s.submission_version, + p.effect_digest,p.snapshot->'reviewRequirement',p.erased_at IS NOT NULL + FROM registry_internal.registry_proposal_review_submissions s + JOIN registry_internal.registry_proposal_submissions p + USING (action_id,proposal_id,submission_version) + WHERE s.state='cancelling' AND s.withdrawn AND ({PREVIOUS_REVIEW_INITIATOR})" + ), + &[], + ) .await?; - Ok(row.get(0)) + Ok(cancellations + .iter() + .any(|row| verify_previous_cancellation(registry_id, row).is_err())) +} + +fn verify_previous_cancellation(registry_id: &str, row: &Row) -> Result<(), MutationError> { + let action_id: String = row.get(7); + let effect_digest: String = row.get(10); + let requirement = row + .get::<_, Option>(11) + .map(serde_json::from_value) + .transpose() + .map_err(|_| MutationError::PreconditionFailed)?; + // Detail erasure retains the work row, its accepted binding and the + // submission's effect digest until cancellation settles. + if requirement.is_none() && !row.get::<_, bool>(12) { + return Err(MutationError::PreconditionFailed); + } + verify_retained_review_binding( + registry_id, + &ReviewSubmissionReference { + action_id: &action_id, + proposal_id: row.get(8), + version: row.get(9), + effect_digest: &effect_digest, + requirement: requirement.as_ref(), + }, + row, + true, + )? + .ok_or(MutationError::PreconditionFailed)?; + Ok(()) } fn outbound_lease_seconds(request_timeout: Duration) -> i64 { @@ -292,13 +347,14 @@ impl std::error::Error for RetainedReviewBindingError {} /// Refuse an upgrade before activation contacts a Review authority. pub async fn check_review_initiator_upgrade( pool: &crate::postgres::RuntimePool, + registry_id: &str, ) -> Result<(), crate::migration::MigrationError> { use crate::migration::MigrationError; let client = pool .get() .await .map_err(|_| MigrationError::DatabaseUnavailable)?; - if review_initiator_upgrade_required(&**client) + if review_initiator_upgrade_required(&**client, registry_id) .await .map_err(|_| MigrationError::ApplyFailed)? { @@ -319,7 +375,7 @@ pub async fn verify_retained_bindings( .get() .await .map_err(|_| RetainedReviewBindingError::Unavailable)?; - if review_initiator_upgrade_required(&**client) + if review_initiator_upgrade_required(&**client, registry.registry_id()) .await .map_err(|_| RetainedReviewBindingError::Unavailable)? { @@ -1664,34 +1720,52 @@ async fn load_status_binding_inner( frozen: &ProposalSnapshot, allow_previous_initiator: bool, ) -> Result, MutationError> { - let CompiledProposalReview::Required { - authority: expected_authority, - source, - policy, - } = frozen.review_requirement() - else { - return Err(MutationError::PreconditionFailed); - }; let row = client .query_opt( - "SELECT authority,proposal_digest,expected_policy,create_request, - producer_id,expected_submission_digest,accepted_binding - FROM registry_internal.registry_proposal_review_submissions - WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3", + &format!( + "SELECT {REVIEW_BINDING_COLUMNS} + FROM registry_internal.registry_proposal_review_submissions s + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3" + ), &[&action_id, &proposal_id, &i64::from(frozen.version().get())], ) .await .map_err(|_| MutationError::Unavailable)? .ok_or(MutationError::PreconditionFailed)?; + verify_retained_review_binding( + registry.registry_id(), + &ReviewSubmissionReference { + action_id, + proposal_id, + version: i64::from(frozen.version().get()), + effect_digest: frozen.effect_digest().as_str(), + requirement: Some(frozen.review_requirement()), + }, + &row, + allow_previous_initiator, + ) +} + +struct ReviewSubmissionReference<'a> { + action_id: &'a str, + proposal_id: Uuid, + version: i64, + effect_digest: &'a str, + requirement: Option<&'a CompiledProposalReview>, +} + +fn verify_retained_review_binding( + registry_id: &str, + submission: &ReviewSubmissionReference<'_>, + row: &Row, + allow_previous_initiator: bool, +) -> Result, MutationError> { let stored_request: Value = row.get(3); let create = ReviewCreateRequest::deserialize(&stored_request) .map_err(|_| MutationError::PreconditionFailed)?; let context_reference = format!( "breg:{}:{}:{}:{}", - registry.registry_id(), - action_id, - proposal_id, - frozen.version().get() + registry_id, submission.action_id, submission.proposal_id, submission.version ); let stored_digest = SubmissionDigest::parse(&row.get::<_, String>(5)) .map_err(|_| MutationError::PreconditionFailed)?; @@ -1700,16 +1774,29 @@ async fn load_status_binding_inner( .map(serde_json::from_value::) .transpose() .map_err(|_| MutationError::PreconditionFailed)?; - if row.get::<_, String>(0) != *expected_authority - || row.get::<_, String>(1) != frozen.effect_digest().as_str() + if let Some(requirement) = submission.requirement { + let CompiledProposalReview::Required { + authority, + source, + policy, + } = requirement + else { + return Err(MutationError::PreconditionFailed); + }; + if row.get::<_, String>(0) != *authority + || create.subject.source != *source + || create.policy != *policy + { + return Err(MutationError::PreconditionFailed); + } + } + if row.get::<_, String>(1) != submission.effect_digest || row.get::<_, Value>(2) - != serde_json::to_value(policy).map_err(|_| MutationError::Unavailable)? - || create.policy != *policy - || create.subject.source != *source + != serde_json::to_value(&create.policy).map_err(|_| MutationError::Unavailable)? || create.subject.subject_type != "proposal" - || create.subject.id != proposal_id.to_string() - || create.subject.version != frozen.version().get().to_string() - || create.subject.digest.as_str() != frozen.effect_digest().as_str() + || create.subject.id != submission.proposal_id.to_string() + || create.subject.version != submission.version.to_string() + || create.subject.digest.as_str() != submission.effect_digest || !matches!(&create.context,registry_review_client::ReviewContext::CurrentSource { binding } if binding.reference == context_reference) || accepted.as_ref().is_some_and(|accepted| { @@ -1717,7 +1804,7 @@ async fn load_status_binding_inner( || accepted.subject.check().is_err() || accepted.policy.check().is_err() || accepted.subject != create.subject - || !policy.matches(&accepted.policy) + || !create.policy.matches(&accepted.policy) }) { return Err(MutationError::PreconditionFailed); @@ -1729,9 +1816,9 @@ async fn load_status_binding_inner( .as_ref() .is_some_and(|initiator| initiator.principal_claim.is_empty()) { - verify_previous_status_digest( + verify_previous_submission_digest( &producer, - registry.registry_id(), + registry_id, &create, &stored_request, &stored_digest, @@ -1740,7 +1827,7 @@ async fn load_status_binding_inner( } else { stored_submission_digest_compatibility( &producer, - registry.registry_id(), + registry_id, &create, &stored_digest, accepted.as_ref(), @@ -3335,7 +3422,7 @@ mod tests { }; assert!(request.check().is_err()); assert!(submission_digest(producer, source, &request).is_err()); - assert!(verify_previous_status_digest( + assert!(verify_previous_submission_digest( producer, registry_id, &request, @@ -3344,7 +3431,7 @@ mod tests { None, ) .is_ok()); - assert!(verify_previous_status_digest( + assert!(verify_previous_submission_digest( producer, registry_id, &request, @@ -3355,7 +3442,7 @@ mod tests { .is_ok()); accepted.submission_digest = source_digest; - assert!(verify_previous_status_digest( + assert!(verify_previous_submission_digest( producer, registry_id, &request, @@ -3379,7 +3466,7 @@ mod tests { (&empty_issuer, &digest_for(registry_id, &empty_issuer)), ] { let parsed = ReviewCreateRequest::deserialize(different).unwrap(); - assert!(verify_previous_status_digest( + assert!(verify_previous_submission_digest( producer, registry_id, &parsed, diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index d2359aafb4..b6f214c9cd 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -124,17 +124,25 @@ fn recovery( registry: ®istry_breg::CompiledRegistry, identity: &ExpectedRegistryIdentity, ) -> ReviewRecoveryOperatorService { - ReviewRecoveryOperatorService::over_retention_service_for_test( - ProposalRetentionOperatorService::new_for_test( - registry.clone(), - identity.clone(), - ExpectedManagedCatalog::compiled(registry), - RegistryLockKey::derive(registry.registry_id()).unwrap(), - fixture.database.migration_config.clone(), - fixture.database.migration_role.clone(), - fixture.database.runtime_role.clone(), - fixture.database.activation_audit(), - ), + ReviewRecoveryOperatorService::over_retention_service_for_test(retention( + fixture, registry, identity, + )) +} + +fn retention( + fixture: &client_http::ClientFixture, + registry: ®istry_breg::CompiledRegistry, + identity: &ExpectedRegistryIdentity, +) -> ProposalRetentionOperatorService { + ProposalRetentionOperatorService::new_for_test( + registry.clone(), + identity.clone(), + ExpectedManagedCatalog::compiled(registry), + RegistryLockKey::derive(registry.registry_id()).unwrap(), + fixture.database.migration_config.clone(), + fixture.database.migration_role.clone(), + fixture.database.runtime_role.clone(), + fixture.database.activation_audit(), ) } @@ -1154,7 +1162,7 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { .unwrap(); let before = snapshot().await; assert_eq!( - check_review_initiator_upgrade(&fixture.pool).await, + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await, Err(MigrationError::ReviewInitiatorUpgrade), "{code}" ); @@ -1202,7 +1210,7 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { ) .await .unwrap(); - check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); assert_eq!(operator.resubmit(scope(id)).await.unwrap().state, "pending"); let after: Value = snapshot().await.get(0); assert_eq!(after["create_request"], current); @@ -1296,7 +1304,7 @@ async fn upgrade_preserves_terminal_status_for_a_previous_named_initiator() { .unwrap(); assert_eq!(updated, 1); - check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); let (package, active) = activate(&fixture, &source, &authority).await; let (http, _) = active_package_client(&fixture, package.registry(), &active, &authority, claims()).await; @@ -1361,7 +1369,7 @@ async fn upgrade_preserves_owner_status_after_a_previous_review_was_refused() { .unwrap(); assert_eq!(updated, 1); - check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) .await .unwrap(); @@ -1456,6 +1464,7 @@ async fn upgrade_dispatches_previous_review_cancellation_after_incompatible_acti async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { use registry_breg::{ migration::MigrationError, + proposal_retention::ProposalDetailErasureScope, review_store::{ check_review_initiator_upgrade, verify_retained_bindings, RetainedReviewBindingError, }, @@ -1477,7 +1486,10 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { .await .unwrap() ); - assert_eq!(job(&fixture, id).await["error"], "result-unknown-to-authority"); + assert_eq!( + job(&fixture, id).await["error"], + "result-unknown-to-authority" + ); let operator = recovery(&fixture, &fixture.registry, &fixture.identity); assert_eq!(operator.resubmit(scope(id)).await.unwrap().state, "pending"); authority.state.refuse_create.store(true, Ordering::SeqCst); @@ -1499,7 +1511,12 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { "UPDATE registry_internal.registry_proposal_review_submissions SET create_request=$2,expected_submission_digest=$3,accepted_binding=$4 WHERE proposal_id=$1", - &[&id, &previous, &accepted.submission_digest.as_str(), &json!(accepted)], + &[ + &id, + &previous, + &accepted.submission_digest.as_str(), + &json!(accepted), + ], ) .await .unwrap(), @@ -1507,7 +1524,7 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { ); *authority.state.accepted.lock().unwrap() = Some(accepted.clone()); - check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); let ReviewRecoveryError::Ineligible { reason, state, code } = operator.resubmit(scope(id)).await.unwrap_err() else { @@ -1531,7 +1548,7 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { let cancelled = client.execute_proposal(&cancel).await.unwrap().value; assert_eq!(cancelled.state(), BRegProposalState::Cancelled); assert_eq!(job(&fixture, id).await["state"], "cancelling"); - check_review_initiator_upgrade(&fixture.pool) + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) .await .expect("an owner withdrawal leaves only the retained cancellation to dispatch"); } @@ -1544,6 +1561,8 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { .as_array_mut() .unwrap() .push(json!("review-note")); + successor["actions"]["correct-name"]["execution"]["proposal"]["retention"] = + json!({"mode":"operator-erase"}); let (package, active) = proposal_activation::activate_with_compatibility( &fixture, &fixture.registry, @@ -1569,7 +1588,7 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { .await .unwrap(); assert_eq!( - check_review_initiator_upgrade(&fixture.pool).await, + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await, Err(MigrationError::ReviewInitiatorUpgrade) ); assert_eq!( @@ -1585,6 +1604,20 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { .await .unwrap(); assert_eq!(job(&fixture, id).await, cancelling); + + let erased = retention(&fixture, package.registry(), &active) + .erase(ProposalDetailErasureScope { + action_id: "correct-name", + proposal_id: id, + submission_version: 1, + }) + .await + .unwrap(); + assert_eq!(erased.erasure.proposal_snapshots, 1); + assert_eq!(erased.erasure.review_accepted_bindings, 0); + verify_retained_bindings(&fixture.pool, package.registry(), Some(&authority.registry)) + .await + .expect("detail erasure preserves the exact retained cancellation"); } let ReviewRecoveryError::Ineligible { reason, .. } = @@ -1604,10 +1637,16 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { let (http, mutations) = active_package_client(&fixture, package.registry(), &active, &authority, claims()).await; let requests = authority.state.requests.load(Ordering::SeqCst); - assert!(run_review_authority_once_for_test(&fixture.pool, &authority.registry, &mutations) - .await - .unwrap()); - assert_eq!(authority.state.requests.load(Ordering::SeqCst), requests + 1); + assert_eq!(requests, 3, "only the original create, poll and recovery ran"); + assert!( + run_review_authority_once_for_test(&fixture.pool, &authority.registry, &mutations) + .await + .unwrap() + ); + assert_eq!( + authority.state.requests.load(Ordering::SeqCst), + requests + 1 + ); let cancellations = authority.state.cancellations.lock().unwrap().clone(); assert_eq!(cancellations.len(), 1); assert_eq!(cancellations[0].0, accepted.request_id); @@ -1709,7 +1748,9 @@ async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { ) .await .unwrap(); - check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) + .await + .unwrap(); verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) .await .unwrap(); @@ -1751,7 +1792,7 @@ async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { ) .await .unwrap(); - check_review_initiator_upgrade(&fixture.pool).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); let ReviewRecoveryError::Ineligible { reason, .. } = operator .resubmit(scope(id)) .await diff --git a/crates/registry-bregctl/src/apply_lifecycle.rs b/crates/registry-bregctl/src/apply_lifecycle.rs index 24fee1429c..0727d855f4 100644 --- a/crates/registry-bregctl/src/apply_lifecycle.rs +++ b/crates/registry-bregctl/src/apply_lifecycle.rs @@ -523,12 +523,15 @@ async fn prepare_proposal_compatibility( let pool = connection .build_pool() .map_err(|_| ApplyLifecycleError::DatabaseConfiguration)?; - registry_breg::review_store::check_review_initiator_upgrade(&pool) - .await - .map_err(|error| match error { - MigrationError::ReviewInitiatorUpgrade => ApplyLifecycleError::Apply(error), - _ => ApplyLifecycleError::ProposalCompatibility, - })?; + registry_breg::review_store::check_review_initiator_upgrade( + &pool, + target.registry().registry_id(), + ) + .await + .map_err(|error| match error { + MigrationError::ReviewInitiatorUpgrade => ApplyLifecycleError::Apply(error), + _ => ApplyLifecycleError::ProposalCompatibility, + })?; match registry_breg::proposal_retention::prepare_proposal_activation_compatibility( &pool, current, From 6e260542f14a474505e6d7cebfee2b3153a21cf0 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:16:17 +0000 Subject: [PATCH 32/33] test(breg): return a complete provider refusal in the cancellation fixture Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/postgres_proposal_review_delivery.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs index b9ff9f4c46..f55d4f6117 100644 --- a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs +++ b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs @@ -321,6 +321,7 @@ async fn create_review( json!({ "type":"https://review-provider.example.test/problems/refused", "title":"Review refused","status":403,"code":"producer.refused", + "detail":"The provider refused this review submission.", "traceId":"0123456789abcdef0123456789abcdef" }) .to_string(), From 8fe72373de0c909a2f2f440f9fea5a53c5002bf7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:22:15 +0000 Subject: [PATCH 33/33] test(breg): format the retained review regression fixtures Signed-off-by: Jeremi Joslin --- .../tests/support/review_go_live.rs | 44 +++++++++++++------ 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/crates/registry-breg/tests/support/review_go_live.rs b/crates/registry-breg/tests/support/review_go_live.rs index b6f214c9cd..435a683f30 100644 --- a/crates/registry-breg/tests/support/review_go_live.rs +++ b/crates/registry-breg/tests/support/review_go_live.rs @@ -1210,7 +1210,9 @@ async fn upgrade_fences_failed_reviews_that_can_be_resubmitted() { ) .await .unwrap(); - check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) + .await + .unwrap(); assert_eq!(operator.resubmit(scope(id)).await.unwrap().state, "pending"); let after: Value = snapshot().await.get(0); assert_eq!(after["create_request"], current); @@ -1304,7 +1306,9 @@ async fn upgrade_preserves_terminal_status_for_a_previous_named_initiator() { .unwrap(); assert_eq!(updated, 1); - check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) + .await + .unwrap(); let (package, active) = activate(&fixture, &source, &authority).await; let (http, _) = active_package_client(&fixture, package.registry(), &active, &authority, claims()).await; @@ -1369,7 +1373,9 @@ async fn upgrade_preserves_owner_status_after_a_previous_review_was_refused() { .unwrap(); assert_eq!(updated, 1); - check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) + .await + .unwrap(); verify_retained_bindings(&fixture.pool, &fixture.registry, Some(&authority.registry)) .await .unwrap(); @@ -1481,11 +1487,13 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { let mut accepted = authority.state.accepted.lock().unwrap().clone().unwrap(); assert_eq!(job(&fixture, id).await["binding"], json!(accepted)); - assert!( - run_review_authority_once_for_test(&fixture.pool, &authority.registry, &fixture.mutations) - .await - .unwrap() - ); + assert!(run_review_authority_once_for_test( + &fixture.pool, + &authority.registry, + &fixture.mutations + ) + .await + .unwrap()); assert_eq!( job(&fixture, id).await["error"], "result-unknown-to-authority" @@ -1524,9 +1532,14 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { ); *authority.state.accepted.lock().unwrap() = Some(accepted.clone()); - check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); - let ReviewRecoveryError::Ineligible { reason, state, code } = - operator.resubmit(scope(id)).await.unwrap_err() + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) + .await + .unwrap(); + let ReviewRecoveryError::Ineligible { + reason, + state, + code, + } = operator.resubmit(scope(id)).await.unwrap_err() else { panic!("a provider refusal ends submission recovery even with a retained acceptance"); }; @@ -1637,7 +1650,10 @@ async fn previous_accepted_review_cancellation(withdraw_by_owner: bool) { let (http, mutations) = active_package_client(&fixture, package.registry(), &active, &authority, claims()).await; let requests = authority.state.requests.load(Ordering::SeqCst); - assert_eq!(requests, 3, "only the original create, poll and recovery ran"); + assert_eq!( + requests, 3, + "only the original create, poll and recovery ran" + ); assert!( run_review_authority_once_for_test(&fixture.pool, &authority.registry, &mutations) .await @@ -1792,7 +1808,9 @@ async fn upgrade_allows_failed_reviews_that_cannot_be_resubmitted() { ) .await .unwrap(); - check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()).await.unwrap(); + check_review_initiator_upgrade(&fixture.pool, fixture.registry.registry_id()) + .await + .unwrap(); let ReviewRecoveryError::Ineligible { reason, .. } = operator .resubmit(scope(id)) .await