diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 014fcf35fc..d8028c3994 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2887,7 +2887,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 e4831c55c0..5027dc14bf 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 095bdd1b45a0e8031bb3d6cff6b2223514c250f14c985ca177abe6f8d18d9277 +// Source SHA-256 843ccf26e5f9831d52416305c075e822607128bb505a5b34bbdd0dc6f7976928 // 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) })) @@ -172,7 +172,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) @@ -334,7 +334,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\"}]}")], @@ -449,7 +449,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 2a1071e4bd..62285d217f 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -748,6 +748,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 15d4d7ed35..a929427470 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 2ad4ae9b66..1822fa11bd 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, } @@ -412,6 +416,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 { @@ -471,15 +487,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; } @@ -510,6 +533,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( @@ -736,6 +770,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 d01c7cad6b..ebd6482b8a 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -325,6 +325,12 @@ pub fn compile_project_with_assets( &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); @@ -4002,6 +4008,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 @@ -6986,11 +7040,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 100563c211..588e4913f3 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. @@ -1366,6 +1369,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 cf5acc356c..8dad4c34f3 100644 --- a/crates/registry-breg/src/migration_reconcile.rs +++ b/crates/registry-breg/src/migration_reconcile.rs @@ -249,6 +249,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 284262e5fe..5898f0f84f 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -882,6 +882,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. @@ -900,6 +915,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 { @@ -2072,6 +2132,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 d75af96ea7..9130f12b2d 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -588,6 +588,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 216bb8761f..94478ecba6 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -1156,6 +1156,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 8eb1b5c6a2..485ef72dae 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 37725e8c2b..278197876a 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -2820,8 +2820,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, @@ -2829,6 +2830,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() { @@ -2850,6 +2852,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); } } } @@ -2857,6 +2876,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; } @@ -2922,8 +2944,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 ecaccfdd3c..1d6c47ec8f 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 40c7add613..d6809d5b9c 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 2be5fc3237..1172ab9dca 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 3c8e4a11c4..161c88eef7 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. @@ -2512,6 +2527,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 7d3de18076..61f77f70db 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 acfa6a4890..aab634a32b 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 2b8fd2239a..7e33f94d34 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -8423,6 +8423,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 31a8c718a0..016ec41981 100644 --- a/crates/registry-bregctl/tests/cli.rs +++ b/crates/registry-bregctl/tests/cli.rs @@ -5531,6 +5531,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 356d9099ae..9a6472f553 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 6056b0bcbb..cf546b766c 100644 --- a/crates/registry-casework-client-node/client.d.ts +++ b/crates/registry-casework-client-node/client.d.ts @@ -230,7 +230,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 fdcd3cd411..68bb495a5a 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 @@ -458,6 +458,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 807d941dba..76e3628aff 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 300a857a45..04327964f2 100644 --- a/crates/registry-casework/src/review.rs +++ b/crates/registry-casework/src/review.rs @@ -2834,11 +2834,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 97817bac20..f3a6911032 100644 --- a/crates/registry-casework/src/store.rs +++ b/crates/registry-casework/src/store.rs @@ -871,6 +871,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() @@ -886,6 +887,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 787e4d2c22..a1e8c7b9e4 100644 --- a/crates/registry-casework/src/task_grants/http_tests.rs +++ b/crates/registry-casework/src/task_grants/http_tests.rs @@ -205,7 +205,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 b1bae5f60a..4167457c6a 100644 --- a/crates/registry-casework/src/task_grants/native_exchange_tests.rs +++ b/crates/registry-casework/src/task_grants/native_exchange_tests.rs @@ -1228,7 +1228,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 d11ff73577..bc875f32e6 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( @@ -266,6 +266,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 8109055b61..e78f6c9f7b 100644 --- a/crates/registry-casework/tests/review_http.rs +++ b/crates/registry-casework/tests/review_http.rs @@ -52,6 +52,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>>); @@ -233,7 +234,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, @@ -358,6 +359,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()], @@ -376,6 +378,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()], @@ -417,6 +420,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 { @@ -5088,6 +5092,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 898f72a1ff..fe58234ca9 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -378,6 +378,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()], @@ -403,6 +404,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]; @@ -490,6 +519,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 { @@ -499,6 +529,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, @@ -2887,6 +2979,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] @@ -12254,12 +12473,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 1a1c39c61b..66bea57077 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) } } @@ -949,6 +976,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 { @@ -960,6 +988,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 35fca0986d..4915125d86 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -5945,6 +5945,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 6056b0bcbb..cf546b766c 100644 --- a/crates/registry-stack-client-node/casework/client.d.ts +++ b/crates/registry-stack-client-node/casework/client.d.ts @@ -230,7 +230,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 066133f9d3..1d8bcc6140 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 bd3c65aa03..14f8f6c1cb 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 @@ -79,6 +79,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 0f759ad9ba..745183e84c 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. @@ -104,6 +105,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. */} @@ -204,6 +206,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 eb9eaadce7..559f379623 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-246`). | 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-246; + 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 aa90faadea..281d375665 100644 --- a/docs/site/src/content/docs/security/casework.mdx +++ b/docs/site/src/content/docs/security/casework.mdx @@ -295,12 +295,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 496b471e97..2aa7e661bb 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,27 @@ ## Unreleased +- 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 2316d0aea8..99c8fafc9e 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -262,3 +262,7 @@ invariants: - {"id":"BREG-SEC-243","state":"enforced","targetWave":"W4","threat":"Pruning value-free dedupe receipts causes a cursor reset to fetch or duplicate a retained ask.","enforcementPoint":"Maintenance uses the observation recovery window; feed processing checks the stored mirror before network I/O.","refusal":"Prune exact bounded receipt counts while preserving mirrored questions and answers and skipping stored observations.","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} - {id: BREG-SEC-244, state: enforced, targetWave: W5, threat: "A signed hook is sent in plaintext to a non-loopback destination.", enforcementPoint: "BReg networkProfile decoding and shared destination policy construction before key resolution.", refusal: "Refuse non-loopback HTTP in both postures, including when the origin falls within allowedPrivateCidrs.", negativeId: BREG-NEG-244, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: event_destinations_refuse_non_loopback_plaintext_in_both_postures}} - {id: BREG-SEC-245, state: enforced, targetWave: W5, threat: "A field addition or reclassification widens a gated permission under the same consent scope.", enforcementPoint: "The compiler checks direct and read-path readableFields on every composed permission with requireConsent.", refusal: "Refuse a classification ceiling with breg.consent.readable-fields-explicit-required. Require explicit field lists on the gated permission.", negativeId: BREG-NEG-245, negativeTest: {path: crates/registry-breg/tests/consent_access.rs, name: a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths}} + # 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-246, 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-246, 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 e30f32be5a..f4dcc1db69 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -303,3 +303,4 @@ traceability: - {"id":"BREG-SEC-243","state":"enforced","negativeId":"BREG-NEG-243","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"pruning_a_receipt_then_resetting_the_cursor_never_refetches_or_duplicates_its_stored_ask"}} - {id: BREG-SEC-244, state: enforced, negativeId: BREG-NEG-244, negativeTest: {path: crates/registry-breg/tests/runtime_config.rs, name: event_destinations_refuse_non_loopback_plaintext_in_both_postures}} - {id: BREG-SEC-245, state: enforced, negativeId: BREG-NEG-245, negativeTest: {path: crates/registry-breg/tests/consent_access.rs, name: a_consent_scope_requires_explicit_fields_on_direct_reads_and_read_paths}} + - {id: BREG-SEC-246, state: enforced, negativeId: BREG-NEG-246, 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 f7610da015..d68b68b432 100644 --- a/products/breg/scripts/test_validate_product.py +++ b/products/breg/scripts/test_validate_product.py @@ -74,7 +74,7 @@ def test_security_range_and_negative_ids_are_closed(self) -> None: ) extension_rows = matrix["invariants"][24:] self.assertEqual( - [f"BREG-NEG-{index:02d}" for index in range(25, 246) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 247) if index not in {61, 62}], [invariant["negativeId"] for invariant in extension_rows], ) for invariant in extension_rows: diff --git a/products/breg/scripts/validate_product.py b/products/breg/scripts/validate_product.py index 0082f48510..6d3e4979cc 100644 --- a/products/breg/scripts/validate_product.py +++ b/products/breg/scripts/validate_product.py @@ -31,7 +31,7 @@ CONTRACT_STATES = {"enforced", "partial", "planned"} V1_REQUIREMENT_IDS = tuple(f"BREG-V1-{index:02d}" for index in range(1, 45)) ACCEPTANCE_JOURNEY_IDS = tuple(f"BREG-J{index:02d}" for index in range(1, 25)) -SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 246) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 247) if index not in {61, 62}) ACCEPTANCE_FIXTURES = { "BREG-J01": ("asset-site-placement", "acceptance/asset-site-placement"), "BREG-J02": ("asset-site-placement", "acceptance/asset-site-placement"), diff --git a/products/casework/CHANGELOG.md b/products/casework/CHANGELOG.md index 365cf965af..3341ca59de 100644 --- a/products/casework/CHANGELOG.md +++ b/products/casework/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- 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 408f2f75fe..41ef081b87 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 51f855982a..cd93c23e20 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" @@ -4365,6 +4369,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 cd876287d2..9064a773e4 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- 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 5d0404501e..52212ce38c 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5926,7 +5926,7 @@ }, "artifact": { "path": "products/breg/generated/tools/model-selection.v1alpha1.schema.json", - "sha256": "975478df7cdc216115fcf370f1478ffc3309c6ac6ae47f79be1c8b358c90dd7e", + "sha256": "d01c4852709b392ba92df20525e79d8917e77a7f75ccc02d9a3b8879fb508988", "mediaType": "application/schema+json" } }, @@ -6124,7 +6124,7 @@ }, "artifact": { "path": "products/casework/generated/project/project.schema.json", - "sha256": "046d67a79c31a867499c61e681913002dcd1ac50c3e1cad2585feb5f1f1619af", + "sha256": "aab7b69e1dafb5eb660177e7e6c2a6aa2401e50754355c4c934e2dbbde1eb007", "mediaType": "application/schema+json" } }, @@ -6142,7 +6142,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 98506e34a5..81f49ca927 100644 --- a/release/scripts/check-gates-inventory.py +++ b/release/scripts/check-gates-inventory.py @@ -740,7 +740,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 9fa748ea33..97669573b3 100644 --- a/release/scripts/test_check_gates_inventory.py +++ b/release/scripts/test_check_gates_inventory.py @@ -1991,7 +1991,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 57e0b3cbff..cee1cbce6e 100755 --- a/release/scripts/test_registry_release.py +++ b/release/scripts/test_registry_release.py @@ -5468,13 +5468,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: @@ -5719,6 +5835,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 90b3e5efa6..5bd73d9eac 100644 --- a/release/scripts/test_release_workflow_structure.py +++ b/release/scripts/test_release_workflow_structure.py @@ -2906,6 +2906,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")