From 6387d9490a52a2fd6009c23eb3d8f62c1f309c75 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 06:56:57 +0000 Subject: [PATCH 1/4] feat(breg): authorize organisation stewardship through membership Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/access.rs | 98 +- crates/registry-breg/src/api/actions.rs | 18 + .../src/api/actions/availability.rs | 34 + crates/registry-breg/src/api/attachments.rs | 24 + crates/registry-breg/src/api/context.rs | 16 + crates/registry-breg/src/api/mod.rs | 27 +- crates/registry-breg/src/api/proposals.rs | 23 +- .../src/api/proposals/answers.rs | 12 +- crates/registry-breg/src/artifacts.rs | 3 +- crates/registry-breg/src/auth.rs | 2 + crates/registry-breg/src/compiler.rs | 18 +- .../src/compiler/disclosure/reach.rs | 42 +- .../registry-breg/src/compiler/statistics.rs | 21 +- crates/registry-breg/src/contract.rs | 232 +- crates/registry-breg/src/contract/sentinel.rs | 323 +- crates/registry-breg/src/disclosure.rs | 27 + .../src/evidence_source/tests.rs | 36 +- crates/registry-breg/src/fixtures.rs | 90 +- .../registry-breg/src/fixtures/proposals.rs | 1 + crates/registry-breg/src/generated_ddl.rs | 340 +- crates/registry-breg/src/history_schema.rs | 1 + crates/registry-breg/src/immediate_actions.rs | 155 +- crates/registry-breg/src/ingestion_store.rs | 4 +- crates/registry-breg/src/membership.rs | 900 +++- crates/registry-breg/src/model.rs | 6 + crates/registry-breg/src/mutation.rs | 239 +- crates/registry-breg/src/mutation/action.rs | 553 ++- .../src/mutation/action/membership.rs | 709 +++ .../registry-breg/src/mutation/membership.rs | 264 ++ crates/registry-breg/src/mutation/proposal.rs | 470 +- .../mutation/proposal/context_projection.rs | 76 +- crates/registry-breg/src/package.rs | 24 +- .../src/package/tests/immediate_actions.rs | 4 +- .../src/postgres/cancellation.rs | 65 +- crates/registry-breg/src/postgres/catalog.rs | 20 +- crates/registry-breg/src/postgres/config.rs | 57 +- crates/registry-breg/src/postgres/context.rs | 266 +- .../registry-breg/src/postgres/interlock.rs | 2 +- crates/registry-breg/src/postgres/mod.rs | 12 +- crates/registry-breg/src/postgres/mutation.rs | 111 +- crates/registry-breg/src/postgres/proposal.rs | 37 +- .../src/postgres/proposal_context.rs | 70 +- crates/registry-breg/src/proposal_ddl.rs | 14 + crates/registry-breg/src/proposal_hooks.rs | 5 +- crates/registry-breg/src/proposal_prepare.rs | 65 +- .../src/proposal_prepare/tests.rs | 2 +- crates/registry-breg/src/runtime_config.rs | 74 + .../tests/action_handler_benchmark_tests.rs | 4 +- .../tests/action_outcome_wasm_parity_tests.rs | 4 +- .../src/tests/wasm_runtime_tests.rs | 2 +- crates/registry-breg/src/tooling.rs | 79 + .../registry-breg/tests/access_explanation.rs | 137 +- crates/registry-breg/tests/access_log.rs | 2 +- .../tests/action_evidence_compiler.rs | 2 +- .../tests/action_handler_declaration.rs | 2 +- .../registry-breg/tests/compiled_ddl_pins.rs | 140 +- .../registry-breg/tests/compiler_contract.rs | 12 +- .../tests/compiler_statistics.rs | 47 +- crates/registry-breg/tests/data_operations.rs | 6 +- .../registry-breg/tests/disclosure/fields.rs | 3 +- .../registry-breg/tests/disclosure/history.rs | 4 +- .../tests/disclosure/proposals.rs | 3 +- .../registry-breg/tests/disclosure/writes.rs | 3 +- .../registry-breg/tests/disclosure_compile.rs | 56 +- .../tests/disclosure_exposure.rs | 3 + .../tests/explicit_row_authority.rs | 23 +- .../tests/field_encryption_contract.rs | 2 +- crates/registry-breg/tests/fixture_tooling.rs | 16 +- .../absent-optional-action-inputs.yaml | 2 +- .../tests/fixtures/authority-mapping.yaml | 2 +- .../tests/fixtures/event-record/shapes.yaml | 2 +- .../fixtures/fixed-optional-action-input.yaml | 2 +- .../fixtures/fixture-tooling/journeys.yaml | 6 + .../fixtures/fixture-tooling/project.yaml | 2 +- .../fixture-tooling/terminal-failure.yaml | 2 + .../tests/generated_identifier_compiler.rs | 6 +- .../tests/golden/membership-access.json | 113 + .../tests/golden/membership-ddl.json | 334 ++ .../tests/golden/membership-ddl.sha256 | 1 + .../tests/golden/membership-revision.txt | 1 + .../tests/golden/membership_refusals.json | 336 ++ .../tests/golden/metrics-scrape-sampled.txt | 1 + .../tests/golden/metrics-scrape-unsampled.txt | 1 + crates/registry-breg/tests/http_read_only.rs | 11 +- .../tests/immediate_action_compiler.rs | 14 +- .../tests/immediate_action_handler.rs | 2 +- .../tests/import_grant_admission.rs | 2 +- .../registry-breg/tests/membership_access.rs | 147 +- .../tests/membership_authoring.rs | 617 +++ .../tests/native_plan_security.rs | 2 +- crates/registry-breg/tests/odrl_export.rs | 51 +- .../tests/ordered_plan_contract.rs | 2 +- .../tests/package_change_plan.rs | 73 +- .../tests/postgres_access_log.rs | 26 +- .../tests/postgres_action_handlers.rs | 2 +- crates/registry-breg/tests/postgres_batch.rs | 10 +- .../tests/postgres_client_capabilities.rs | 4 +- .../tests/postgres_compiled_schema.rs | 14 +- .../tests/postgres_constraint_races.rs | 2 +- .../tests/postgres_data_export.rs | 4 +- .../tests/postgres_data_facility.rs | 6 +- .../tests/postgres_derived_values.rs | 4 +- .../tests/postgres_event_record_examples.rs | 2 +- .../tests/postgres_event_record_reader.rs | 4 +- .../tests/postgres_field_encryption.rs | 2 +- .../tests/postgres_fixture_journeys.rs | 9 +- ...tgres_generated_identifier_batch_import.rs | 4 +- .../tests/postgres_generated_identifiers.rs | 2 +- .../tests/postgres_history_commit.rs | 2 +- .../tests/postgres_history_erasure.rs | 4 +- .../tests/postgres_history_migration.rs | 4 +- .../tests/postgres_history_rebaseline.rs | 2 +- .../tests/postgres_hook_changes.rs | 88 +- .../tests/postgres_immediate_actions.rs | 2 +- .../tests/postgres_import_authority.rs | 6 +- .../tests/postgres_ingestion_contract.rs | 4 +- .../tests/postgres_ingestion_receipts.rs | 4 +- .../tests/postgres_ingestion_runs.rs | 10 +- crates/registry-breg/tests/postgres_kernel.rs | 2 +- .../tests/postgres_membership_access.rs | 106 +- .../registry-breg/tests/postgres_migration.rs | 2 +- .../registry-breg/tests/postgres_mutation.rs | 34 +- .../tests/postgres_mutation_logical_names.rs | 2 +- .../registry-breg/tests/postgres_package.rs | 2 +- .../postgres_package/compiler_upgrade.rs | 2 +- .../tests/postgres_package/policy_upgrade.rs | 10 +- .../postgres_package/reference_upgrade.rs | 2 +- .../tests/postgres_pilot_acceptance.rs | 14 +- .../registry-breg/tests/postgres_proposal.rs | 221 + .../tests/postgres_proposal_security.rs | 923 +++- .../tests/postgres_read_dependencies.rs | 4 +- .../postgres_record_profile_conformance.rs | 2 +- .../tests/postgres_record_timer_clock.rs | 2 +- .../tests/postgres_record_timer_retention.rs | 2 +- .../tests/postgres_record_timers.rs | 2 +- .../tests/postgres_reference_integrity.rs | 8 +- .../tests/postgres_spatial_migration.rs | 2 +- .../tests/postgres_spatial_storage.rs | 6 +- .../tests/postgres_statistics_exact.rs | 2 +- .../tests/postgres_statistics_http.rs | 2 +- .../tests/postgres_statistics_measures.rs | 2 +- .../tests/postgres_tombstone_revision.rs | 2 +- .../tests/postgres_webhook_delivery.rs | 4 +- .../tests/postgres_webhook_outbox.rs | 2 +- .../tests/postgres_workspace_metadata.rs | 4 +- .../proposal_generated_identifier_policies.rs | 2 +- crates/registry-breg/tests/script_baseline.rs | 2 +- .../tests/standing_agent_ceiling.rs | 4 +- .../tests/support/action_evidence_provider.rs | 4 + .../tests/support/event_record_registry.rs | 2 +- .../tests/support/membership_targets.rs | 112 + .../support/membership_write_journeys.rs | 3881 +++++++++++++++++ .../tests/support/membership_write_project.rs | 266 ++ .../tests/support/pilot_acceptance_harness.rs | 2 + .../support/postgres_membership_writes.rs | 583 +++ .../tests/task_grant_row_findings.rs | 6 +- .../tests/value_type_consistency.rs | 4 +- .../tests/wasm_handler_admission.rs | 2 +- .../src/action_handler_test.rs | 2 +- crates/registry-bregctl/src/check.rs | 4 +- .../src/consent_module/module.yaml | 1 + .../src/consent_module/profiles.yaml | 5 +- crates/registry-bregctl/src/data_lifecycle.rs | 4 +- crates/registry-bregctl/src/lib.rs | 2 +- crates/registry-bregctl/tests/cli.rs | 26 +- .../tests/explain_contract.rs | 37 + .../src/observability/golden-scrape.txt | 1 + .../src/observability/golden-scrape.txt | 1 + .../src/refusal.rs | 9 +- crates/registry-rstack-dev/src/products.rs | 83 + .../content/docs/configure/breg-access.mdx | 208 +- docs/site/src/content/docs/security/breg.mdx | 91 +- products/breg/AGENTS.md | 12 +- products/breg/CHANGELOG.md | 8 + .../asset-site-placement/registry.yaml | 4 +- .../asset-site-placement/tests/journeys.yaml | 8 + .../breg/acceptance/business/registry.yaml | 2 +- .../acceptance/business/tests/journeys.yaml | 3 + products/breg/acceptance/facility/dev.yaml | 4 +- .../breg/acceptance/facility/registry.yaml | 2 +- .../acceptance/facility/tests/journeys.yaml | 12 +- .../breg/acceptance/inspection/registry.yaml | 2 +- .../acceptance/inspection/tests/journeys.yaml | 6 + .../explain/AccessExplanation.schema.json | 112 +- .../contracts/security-invariant-matrix.yaml | 12 +- .../contracts/security-test-traceability.yaml | 10 + .../action-plan-branches/registry.yaml | 2 +- .../modules/consent-tenure-right/module.yaml | 5 + .../consent-land-registry/registry.yaml | 10 +- .../modules/consent-person/module.yaml | 1 + .../consent-person-registry/registry.yaml | 7 +- .../registry.yaml | 21 +- .../authoring/registry-module.schema.json | 95 +- .../authoring/registry-project.schema.json | 150 +- .../breg/scripts/test-adopter-workflow.sh | 14 +- .../breg/scripts/test_validate_product.py | 7 +- products/breg/scripts/validate_product.py | 2 +- products/platform/CHANGELOG.md | 2 + 198 files changed, 13866 insertions(+), 1452 deletions(-) create mode 100644 crates/registry-breg/src/mutation/action/membership.rs create mode 100644 crates/registry-breg/src/mutation/membership.rs create mode 100644 crates/registry-breg/tests/golden/membership-access.json create mode 100644 crates/registry-breg/tests/golden/membership-ddl.json create mode 100644 crates/registry-breg/tests/golden/membership-ddl.sha256 create mode 100644 crates/registry-breg/tests/golden/membership-revision.txt create mode 100644 crates/registry-breg/tests/golden/membership_refusals.json create mode 100644 crates/registry-breg/tests/membership_authoring.rs create mode 100644 crates/registry-breg/tests/support/membership_targets.rs create mode 100644 crates/registry-breg/tests/support/membership_write_journeys.rs create mode 100644 crates/registry-breg/tests/support/membership_write_project.rs create mode 100644 crates/registry-breg/tests/support/postgres_membership_writes.rs diff --git a/crates/registry-breg/src/access.rs b/crates/registry-breg/src/access.rs index d1c9f26081..1b629dcc06 100644 --- a/crates/registry-breg/src/access.rs +++ b/crates/registry-breg/src/access.rs @@ -8,8 +8,9 @@ use serde::Serialize; use crate::compiler::operation_id; use crate::contract::{ AccessProfileSource, AccessRequirementsSource, ActorKindSource, BoundaryOperator, - Classification, ConsentIssuerSource, EntitySource, FieldTypeSource, MembershipBoundarySource, - Operation, ProjectAccessProfileSource, RegistryProject, RowBoundarySource, + Classification, ConsentIssuerSource, EntitySource, ExpandedMembershipBoundarySource, + FieldTypeSource, MembershipBoundarySource, Operation, ProjectAccessProfileSource, + RegistryProject, RowBoundarySource, }; use crate::diagnostics::Diagnostic; use crate::model::{ @@ -114,28 +115,42 @@ pub(crate) fn check_profile( path: &str, errors: &mut Vec, ) { - for scope in requirements - .required_scopes - .difference(&profile.required_scopes) - { + check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + path, + errors, + ); + for boundary in &requirements.row_boundaries { + if !profile.row_boundaries.contains(boundary) { + errors.push(Diagnostic::error( + "breg.access.requirements-row-boundary-missing", + format!("{path}.rowBoundaries[field={}]", boundary.field), + "Include the Record type's exact field, claim and operator binding. Request filters and other claim names do not satisfy this requirement.", + )); + } + } +} + +pub(crate) fn check_profile_authority( + requirements: &AccessRequirementsSource, + required_scopes: &crate::contract::UniqueSet, + required_purposes: &crate::contract::UniqueSet, + path: &str, + errors: &mut Vec, +) { + for scope in requirements.required_scopes.difference(required_scopes) { errors.push(Diagnostic::error("breg.access.requirements-scope-missing", format!("{path}.requiredScopes[value={scope}]"), "add the record type's mandatory scope to this profile; granting other scopes does not satisfy it")); } if !requirements.allowed_purposes.is_empty() - && (profile.required_purposes.is_empty() - || !profile - .required_purposes - .is_subset(&requirements.allowed_purposes)) + && (required_purposes.is_empty() + || !required_purposes.is_subset(&requirements.allowed_purposes)) { errors.push(Diagnostic::error("breg.access.requirements-purpose-widened", format!("{path}.requiredPurposes"), "require a nonempty subset of the record type's allowedPurposes; an empty list allows every purpose")); } - for boundary in &requirements.row_boundaries { - if !profile.row_boundaries.contains(boundary) { - errors.push(Diagnostic::error("breg.access.requirements-row-boundary-missing", format!("{path}.rowBoundaries[field={}]", boundary.field), - "include the record type's exact field, claim, and operator binding; request filters and other claim names do not satisfy this requirement")); - } - } } const TASK_GRANT_ROWS_UNBOUND: &str = "breg.access-profile.task-grant-rows-unbound"; @@ -377,7 +392,7 @@ pub(crate) fn compiled_access_findings( grant.entity_target_locks().map(move |target| { ( &target.entity_id, - &target.row_boundaries, + target.row_boundaries.is_empty() && target.membership_boundaries.is_empty(), format!( "actions[id={}].permissions[profile={}].targets[recordType={}].rowBoundaries", action.id, grant.profile_id, target.entity_id @@ -392,7 +407,7 @@ pub(crate) fn compiled_access_findings( grant.targets.iter().map(move |target| { ( &target.entity_id, - &target.row_boundaries, + target.row_boundaries.is_empty() && target.membership_boundaries.is_empty(), format!( "actions[id={}].execution.proposal.permissions[profile={}].targets[recordType={}].rowBoundaries", action.id, grant.profile_id, target.entity_id @@ -400,8 +415,8 @@ pub(crate) fn compiled_access_findings( ) }) }); - for (entity_id, boundaries, path) in action_targets.chain(proposal_targets) { - if boundaries.is_empty() + for (entity_id, unbounded, path) in action_targets.chain(proposal_targets) { + if unbounded && entities .get(entity_id) .is_some_and(|entity| entity.classification != Classification::Public) @@ -852,7 +867,7 @@ fn inspect_record_profile( profile: &AccessProfileSource, ) -> serde_json::Value { let mut value = serde_json::to_value(profile).expect("compiled access profile serializes"); - if profile.row_boundaries.is_empty() { + if profile.row_boundaries.is_empty() && profile.membership_boundaries.is_empty() { value["rowBoundaries"] = serde_json::json!("unrestricted"); } value["allowCount"] = serde_json::json!(profile.allow_count); @@ -879,7 +894,7 @@ pub struct RowReachExplanation { pub rows: &'static str, pub row_boundaries: Vec, #[serde(skip_serializing_if = "Vec::is_empty")] - pub membership_boundaries: Vec, + pub membership_boundaries: Vec, pub owner_only: bool, /// Action target authority is enforced only while the named Action runs. /// It is an additional grant and never becomes ordinary Record CRUD. @@ -911,13 +926,40 @@ fn row_reach( entities: &BTreeMap, actions: &CompiledActionInventory, ) -> Vec { + let record_memberships = |entries: &[MembershipBoundarySource]| { + entries + .iter() + .filter_map(|entry| match entry { + MembershipBoundarySource::Expanded(entry) => Some(entry.clone()), + MembershipBoundarySource::Declared(_) => None, + }) + .collect() + }; + let target_memberships = |entries: &[crate::model::CompiledMembershipBoundary]| { + entries + .iter() + .filter_map(|entry| { + let declaration = entities + .get(&entry.membership_entity)? + .membership + .as_ref()?; + Some(ExpandedMembershipBoundarySource { + field: entry.field.clone(), + membership_entity: entry.membership_entity.clone(), + membership_key_field: declaration.key.clone(), + principal_field: declaration.principal.clone(), + active_field: declaration.active.clone(), + }) + }) + .collect() + }; let mut reach = Vec::new(); let mut add = |entity: &str, profile: &str, source_path: String, surface, boundaries: &[RowBoundarySource], - memberships: &[MembershipBoundarySource], + memberships: Vec, owner, action_target_authority| { reach.push(RowReachExplanation { @@ -932,7 +974,7 @@ fn row_reach( (false, false) => "claim_and_membership_bound", }, row_boundaries: boundaries.to_vec(), - membership_boundaries: memberships.to_vec(), + membership_boundaries: memberships, owner_only: owner, action_target_authority, }); @@ -946,7 +988,7 @@ fn row_reach( format!("{path}.rowBoundaries"), "record", &profile.row_boundaries, - &profile.membership_boundaries, + record_memberships(&profile.membership_boundaries), false, None, ); @@ -960,7 +1002,7 @@ fn row_reach( format!("{path}.readPaths[path={}]", grant.path), "read_path", &profile.row_boundaries, - &profile.membership_boundaries, + record_memberships(&profile.membership_boundaries), false, None, ); @@ -979,7 +1021,7 @@ fn row_reach( ), "action_target", &target.row_boundaries, - &[], + target_memberships(&target.membership_boundaries), false, Some(ActionTargetAuthorityExplanation { enforcement: "runtime_enforced", @@ -1028,7 +1070,7 @@ fn row_reach( ), "proposal_target", &target.row_boundaries, - &[], + target_memberships(&target.membership_boundaries), grant.ownership == Some(crate::contract::ProposalOwnership::Caller), None, ); diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index 30a9d2c214..d12b918b48 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -295,6 +295,18 @@ fn authorize_action_mode<'a>( target_authority, grant.results.clone(), ) + .with_target_memberships( + grant + .entity_target_locks() + .filter(|target| !target.membership_boundaries.is_empty()) + .map(|target| { + ( + target.entity_id.clone(), + target.membership_boundaries.clone(), + ) + }) + .collect(), + ) .with_audit_context(claims) .with_task_grant(task_grant), admitted_profiles: vec![selected.to_owned()], @@ -563,6 +575,9 @@ pub(super) async fn dispatch( } } } + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(error) => mutation_problem(error), } } @@ -581,6 +596,9 @@ pub(super) async fn dispatch( Err(crate::mutation::MutationError::PreconditionFailed) => { concealed(FailedCheck::RowBoundary) } + Err(MutationError::MembershipPreconditionFailed) => { + concealed(FailedCheck::Membership) + } Err(error) => mutation_problem(error), } } diff --git a/crates/registry-breg/src/api/actions/availability.rs b/crates/registry-breg/src/api/actions/availability.rs index 15db17d548..89847a93d8 100644 --- a/crates/registry-breg/src/api/actions/availability.rs +++ b/crates/registry-breg/src/api/actions/availability.rs @@ -6,6 +6,7 @@ use super::*; use crate::contract::FieldTypeSource; +use crate::postgres::ActionTargetMembershipObservation; pub(super) enum Availability { Satisfied { @@ -115,6 +116,12 @@ pub(super) async fn observe( record_id, &guard_fields, &boundaries, + action + .context + .target_memberships() + .get(target) + .map(Vec::as_slice) + .unwrap_or_default(), correlation, ) .await? @@ -184,6 +191,7 @@ pub(in crate::api) async fn observe_target( record_id: &str, guard_fields: &BTreeSet, boundaries: &[crate::postgres::RowBoundaryContext], + memberships: &[crate::model::CompiledMembershipBoundary], correlation: &RequestCorrelation, ) -> Result, Response> { let target = &entity.id; @@ -196,6 +204,7 @@ pub(in crate::api) async fn observe_target( .filter(|boundary| boundary.field() != entity.canonical_id.id) .map(|boundary| boundary.field().to_owned()), ) + .chain(memberships.iter().map(|boundary| boundary.field.clone())) .collect::>(); let Some(route) = service .registry @@ -222,6 +231,7 @@ pub(in crate::api) async fn observe_target( if let Some(refusal) = field_encryption_refusal(service, entity) { return Err(refusal); } + let membership_context = (!memberships.is_empty()).then(|| surface.context.clone()); let read = service .records .get(RecordReadRequest { @@ -286,6 +296,30 @@ pub(in crate::api) async fn observe_target( { return Err(concealed(FailedCheck::RowBoundary)); } + if let Some(context) = &membership_context { + let mutations = service.mutations.as_ref().ok_or_else(unavailable)?; + let observation = mutations + .observe_action_target_membership( + context, + entity, + Uuid::parse_str(record_id).map_err(|_| unavailable())?, + i64::try_from(revision).map_err(|_| unavailable())?, + memberships, + &fields, + ) + .await + .map_err(|_| unavailable())?; + match observation { + ActionTargetMembershipObservation::Authorized => {} + ActionTargetMembershipObservation::OutsideBoundary => { + return Err(concealed(FailedCheck::Membership)); + } + ActionTargetMembershipObservation::Withheld => return Ok(None), + ActionTargetMembershipObservation::Missing => { + return Err(concealed(FailedCheck::Visibility)); + } + } + } Ok(Some(ObservedTarget { revision, current })) } diff --git a/crates/registry-breg/src/api/attachments.rs b/crates/registry-breg/src/api/attachments.rs index eba680ff4a..5e0cff9023 100644 --- a/crates/registry-breg/src/api/attachments.rs +++ b/crates/registry-breg/src/api/attachments.rs @@ -254,6 +254,23 @@ async fn mutate( ) .await } + MutationError::MembershipPreconditionFailed => { + super::proposals::admitted_http_refusal_with( + mutations, + &authority, + mutation_method(removal, addition), + &correlation, + || { + if addition { + concealed(FailedCheck::Membership) + } else { + // Count the generic 412 only after audit accepts it. + membership_precondition_problem(&correlation) + } + }, + ) + .await + } MutationError::PreconditionFailed if addition => { super::proposals::admitted_http_refusal( mutations, @@ -388,6 +405,12 @@ async fn mutate( "", service.field_encryption.as_deref(), ), + Err(MutationError::MembershipPreconditionFailed) if addition => { + concealed(FailedCheck::Membership) + } + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(MutationError::PreconditionFailed) => precondition_failed(), Err(error) => super::proposals::proposal_target_problem(error), } @@ -510,6 +533,7 @@ async fn download_file( .header(VARY, "authorization") .body(Body::from(bytes)) .unwrap_or_else(|_| unavailable()), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => super::proposals::proposal_target_problem(error), } diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index 2a1071e4bd..56930ef8ee 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -626,6 +626,7 @@ pub struct AuthorizedActionContext { purpose: Option, selected_profile: String, target_authority: BTreeMap>, + target_memberships: BTreeMap>, result_effects: BTreeSet, audit_context: Option, task_grant: Option, @@ -647,6 +648,7 @@ impl AuthorizedActionContext { purpose, selected_profile, target_authority, + target_memberships: BTreeMap::new(), result_effects, audit_context: None, task_grant: None, @@ -654,6 +656,20 @@ impl AuthorizedActionContext { } } + pub(crate) fn with_target_memberships( + mut self, + memberships: BTreeMap>, + ) -> Self { + self.target_memberships = memberships; + self + } + + pub(crate) fn target_memberships( + &self, + ) -> &BTreeMap> { + &self.target_memberships + } + pub(crate) fn with_audit_context(mut self, claims: &VerifiedRequestClaims) -> Self { self.audit_context = crate::audit::RequestAuditContext::from_claims(claims); self.caller_issuer = claims.caller_issuer().map(str::to_owned); diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index 48c4428dc7..90b5cbb309 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -2109,7 +2109,7 @@ async fn create_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2288,7 +2288,7 @@ async fn patch_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2441,7 +2441,7 @@ async fn batch_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2592,7 +2592,7 @@ async fn tombstone_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -6037,6 +6037,11 @@ fn attachment_slot_problem(problem: ProblemCode, slot: &str) -> Response { ) } +fn membership_precondition_problem(correlation: &RequestCorrelation) -> Response { + crate::correlation::record_refusal_check(FailedCheck::Membership, correlation); + precondition_failed() +} + fn mutation_problem(error: MutationError) -> Response { let check = error.failed_check(); let response = mutation_problem_response(error); @@ -6054,10 +6059,14 @@ fn mutation_problem_response(error: MutationError) -> Response { MutationError::InvalidRequestAt(location) => invalid_request_at(&location), MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed + | MutationError::MembershipPreconditionFailed | MutationError::ProposalTargetChanged | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) | MutationError::TimerGenerationUnsupported => precondition_failed(), + MutationError::MembershipWriteOutsideBoundary => { + refusal_problem(ProblemCode::WriteOutsideBoundary, FailedCheck::Membership) + } MutationError::WriteOutsideBoundary => { refusal_problem(ProblemCode::WriteOutsideBoundary, FailedCheck::RowBoundary) } @@ -6094,6 +6103,7 @@ fn mutation_problem_response(error: MutationError) -> Response { // the match stays exhaustive over the whole closed vocabulary. MutationError::Unavailable | MutationError::RetryableConflict + | MutationError::MembershipKeyDrift | MutationError::CommitUnresolved | MutationError::MigrationLockHeld | MutationError::PostureMismatch { .. } @@ -6130,8 +6140,10 @@ fn mutation_problem_response(error: MutationError) -> Response { fn mutation_problem_for_fields( error: MutationError, readable_fields: &BTreeSet, + correlation: &RequestCorrelation, ) -> Response { match error { + MutationError::MembershipPreconditionFailed => membership_precondition_problem(correlation), MutationError::InvalidTimerWindow { at_field, not_after_field, @@ -6302,7 +6314,7 @@ mod held_body_encryption_tests { secret ] }}, - "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"case","rowBoundaries":"unrestricted","operations":["get","list","create","patch"], "readableFields":["label","secret"],"writableFields":["label","secret"] }]}}} @@ -6821,6 +6833,10 @@ mod refusal_check_tests { MutationError::WriteOutsideBoundary, FailedCheck::RowBoundary, ), + ( + MutationError::MembershipWriteOutsideBoundary, + FailedCheck::Membership, + ), ( MutationError::FieldGuardFailed { input: "input".to_owned(), @@ -6833,6 +6849,7 @@ mod refusal_check_tests { } for error in [ MutationError::PreconditionFailed, + MutationError::MembershipPreconditionFailed, MutationError::Conflict, MutationError::Unavailable, ] { diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index c560c9cabc..304cb8556d 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -706,12 +706,22 @@ pub(super) async fn admitted_http_refusal( method: HttpMethod, correlation: &RequestCorrelation, response: Response, +) -> Response { + admitted_http_refusal_with(mutations, authority, method, correlation, || response).await +} + +pub(super) async fn admitted_http_refusal_with( + mutations: &crate::postgres::PostgresRecordMutationService, + authority: &ProposalAuthority, + method: HttpMethod, + correlation: &RequestCorrelation, + response: impl FnOnce() -> Response, ) -> Response { match mutations .record_proposal_http_refusal(authority, method, correlation) .await { - Ok(()) => response, + Ok(()) => response(), Err(_) => unavailable(), } } @@ -1174,6 +1184,9 @@ pub(super) async fn start( "", service.field_encryption.as_deref(), ), + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(error) => proposal_problem(error), } } @@ -1214,6 +1227,7 @@ pub(super) async fn get( .await { Ok((value, etag)) => json_response(value, Some(&etag)), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1266,6 +1280,7 @@ pub(super) async fn submission( { Ok(Some(value)) => json_response(value, None), Ok(None) => fixed_problem(ProblemCode::ProposalSubmissionExpired), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1521,6 +1536,9 @@ pub(super) async fn transition( ) .await } + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(error) => proposal_target_problem(error), } } @@ -1562,6 +1580,7 @@ async fn guard_failure_response( &failure.record_id.to_string(), &BTreeSet::from([guard.field.clone()]), boundaries, + authority.target_membership(&guard.entity_id), correlation, ) .await; @@ -1868,6 +1887,7 @@ pub(super) async fn task_grant_context( ); response } + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1949,6 +1969,7 @@ async fn review_read( .await { Ok((value, etag)) => json_response(value, etag.as_deref()), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } diff --git a/crates/registry-breg/src/api/proposals/answers.rs b/crates/registry-breg/src/api/proposals/answers.rs index dbe61b6ddc..d0833f4533 100644 --- a/crates/registry-breg/src/api/proposals/answers.rs +++ b/crates/registry-breg/src/api/proposals/answers.rs @@ -42,13 +42,20 @@ pub(in crate::api) async fn answer( }; if let Err(error) = mutations.proposal_visible(id, &authority).await { return match error { - MutationError::PreconditionFailed | MutationError::AuthorizationRefused(_) => { + MutationError::PreconditionFailed + | MutationError::AuthorizationRefused(_) + | MutationError::MembershipPreconditionFailed => { + let check = if matches!(error, MutationError::MembershipPreconditionFailed) { + FailedCheck::Membership + } else { + FailedCheck::Visibility + }; admitted_http_refusal( mutations, &authority, HttpMethod::Post, &correlation, - concealed(FailedCheck::Visibility), + concealed(check), ) .await } @@ -119,6 +126,7 @@ pub(in crate::api) async fn answer( "", service.field_encryption.as_deref(), ), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(error) => proposal_target_problem(error), } } diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index 9c82f23948..638de9e129 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -4424,7 +4424,8 @@ fn operation_may_refuse_write(spec: OpenApiOperationSpec<'_>) -> bool { .entity .access_profiles .get(profile_id) - .is_some_and(|profile| !profile.row_boundaries.is_empty()); + .is_some_and(|profile| !profile.row_boundaries.is_empty()) + || !crate::membership::boundaries(spec.entity, profile_id).is_empty(); let disclosure = crate::disclosure::plan(spec.entity, profile_id); let disclosure_refuses = if spec.route.operation == Operation::Create { disclosure diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 2ad4ae9b66..947a4c8634 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -381,6 +381,7 @@ pub(crate) fn compiled_profile_facts( .row_boundaries .iter() .any(|boundary| claim_is_principal(&boundary.claim, principal)) + || !target.membership_boundaries.is_empty() }); entry.has_subject_row_rule |= subject_row; entry.reads_principal |= subject_row; @@ -399,6 +400,7 @@ pub(crate) fn compiled_profile_facts( .row_boundaries .iter() .any(|boundary| claim_is_principal(&boundary.claim, principal)) + || !target.membership_boundaries.is_empty() }); entry.has_subject_row_rule |= subject_row; entry.reads_principal |= subject_row; diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 142294ec20..e2ed31745d 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -339,7 +339,7 @@ pub fn compile_project_with_assets( &mut diagnostics, ); crate::access::validate_access_requirements(&sources, &mut diagnostics); - crate::membership::validate(&sources, &mut diagnostics); + crate::membership::validate(project, &action_sources, &sources, &mut diagnostics); crate::consent::validate(project, &sources, &mut diagnostics); crate::event_record::validate(&sources, &mut diagnostics); findings.extend(crate::access::access_findings(&sources)); @@ -377,6 +377,13 @@ pub fn compile_project_with_assets( "relationship compilation", ) })?; + crate::membership::compile(&mut entities).map_err(|errors| { + stopped_compile_failure( + CompileFailure::from_errors(errors), + &findings, + "membership compilation", + ) + })?; let statistical_datasets = statistics::compile(project, &entities).map_err(|errors| { stopped_compile_failure( CompileFailure::from_errors(errors), @@ -405,7 +412,6 @@ pub fn compile_project_with_assets( &entities, )); crate::external_views::mark_link_fields(&external_views, &mut entities, &mut physical_names); - crate::membership::compile(&mut entities); let recipients = crate::consent::compile(project, &sources, &mut entities); crate::event_record::compile(&sources, &mut entities); let timer_actions = sources @@ -4195,7 +4201,12 @@ pub(crate) fn expand_project_access( required_filters: grant.required_filters.clone(), spatial_queries: grant.spatial_queries.clone(), row_boundaries: grant.row_boundaries.clone(), - membership_boundaries: grant.membership_boundaries.clone(), + membership_boundaries: grant + .membership_row_boundaries + .iter() + .cloned() + .map(crate::contract::MembershipBoundarySource::Declared) + .collect(), require_consent: grant.require_consent.clone(), lookups: grant.lookups.clone(), read_paths: grant.read_paths.clone(), @@ -8291,6 +8302,7 @@ fn compile_entities( batch: source.batch.clone(), classification: source.classification, access_requirements: source.access_requirements.clone(), + membership: source.membership.clone(), access_log: source.access_log.clone(), disclosure_conditions: disclosure::compile_conditions(source), geojson: source diff --git a/crates/registry-breg/src/compiler/disclosure/reach.rs b/crates/registry-breg/src/compiler/disclosure/reach.rs index 34346cdebf..7aeb530aaf 100644 --- a/crates/registry-breg/src/compiler/disclosure/reach.rs +++ b/crates/registry-breg/src/compiler/disclosure/reach.rs @@ -12,8 +12,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::contract::{ AccessProfileSource, BoundaryOperator, DerivedSource, DisclosureConditionSource, - DisclosureWithholdSource, EntitySource, Operation, RowBoundarySource, TimerPredicateSource, - UniqueSet, + DisclosureWithholdSource, EntitySource, Operation, TimerPredicateSource, UniqueSet, }; use crate::diagnostics::Diagnostic; use crate::external_views::CompiledExternalViews; @@ -139,7 +138,7 @@ pub(super) fn validate_boundaries( if profile .membership_boundaries .iter() - .any(|boundary| boundary.field == *field) + .any(|boundary| boundary.field() == field) { refuse( errors, @@ -599,12 +598,12 @@ fn reading_grant<'a>( .filter(|grant| crate::generated_ddl::grant_reads_rows(grant.operations.as_set())) } -fn backticked<'a>(values: impl IntoIterator) -> String { +fn backticked(values: impl IntoIterator + Ord>) -> String { values .into_iter() .collect::>() .into_iter() - .map(|value| format!("`{value}`")) + .map(|value| format!("`{}`", value.as_ref())) .collect::>() .join(", ") } @@ -643,7 +642,7 @@ fn withheld_source_rows( }; if !grant.membership_boundaries.is_empty() { found.push(( - source_path("membershipBoundaries"), + source_path("rowBoundaries"), format!( "{reads}, and its grant on `{source}` requires a membership through {through}, so its derived values leave out the `{source}` rows the caller holds no such membership for", source = source.id, @@ -651,7 +650,7 @@ fn withheld_source_rows( grant .membership_boundaries .iter() - .map(|boundary| &boundary.membership_entity) + .map(crate::contract::MembershipBoundarySource::record_type) ), ), )); @@ -689,7 +688,7 @@ fn unlinked_source_rows( "{reads}, and a subquery that refers to no column of the row reads every `{source}` row the profile sees, which its grant on `{source}` bounds by {boundaries}, so its derived values cover only those rows, not every `{source}` row", reads = reads_derived_from(owner, source, reader), source = source.id, - boundaries = describe_row_boundaries(&grant.row_boundaries), + boundaries = describe_row_boundaries(grant), ), )) } @@ -746,7 +745,7 @@ fn derived_source_refusal( format!( "{reads}, but the profile cannot read `{source}` rows, {missed}: {rewrite}grant it `get` on `{source}`, with only {readable} readable and the row boundaries {boundaries} of its grant on `{request_entity}`", source = source.id, - boundaries = describe_row_boundaries(&request.row_boundaries), + boundaries = describe_row_boundaries(request), readable = readable, rewrite = rewrite, ), @@ -784,10 +783,15 @@ fn derived_source_refusal( code, source_path("rowBoundaries"), format!( - "{reads}, but its grant on `{source}` is bounded by {source_rows} and its grant on `{request_entity}` by {request_rows}, {missed}: {rewrite}bound the grant on `{source}` by {request_rows} too, on fields that hold the same values", + "{reads}, but its grant on `{source}` is bounded by {source_rows} and its grant on `{request_entity}` by {request_rows}, {missed}: {rewrite}{fix}", + fix = if request.membership_boundaries.is_empty() { + format!("bound the grant on `{}` by {request_rows} too, on fields that hold the same values", source.id, request_rows = describe_row_boundaries(request)) + } else { + "align the claim boundaries on fields that hold the same values while retaining the required membership restrictions, or do not grant the derived field".to_owned() + }, source = source.id, - source_rows = describe_row_boundaries(&grant.row_boundaries), - request_rows = describe_row_boundaries(&request.row_boundaries), + source_rows = describe_row_boundaries(grant), + request_rows = describe_row_boundaries(request), rewrite = rewrite, ), )); @@ -828,11 +832,12 @@ fn derived_source_refusal( None } -fn describe_row_boundaries(boundaries: &[RowBoundarySource]) -> String { - if boundaries.is_empty() { +fn describe_row_boundaries(grant: &crate::contract::AccessProfileSource) -> String { + if grant.row_boundaries.is_empty() && grant.membership_boundaries.is_empty() { return "`unrestricted`".to_owned(); } - boundaries + grant + .row_boundaries .iter() .map(|boundary| { let operator = match boundary.operator { @@ -841,6 +846,13 @@ fn describe_row_boundaries(boundaries: &[RowBoundarySource]) -> String { }; format!("`{}` {operator} claim `{}`", boundary.field, boundary.claim) }) + .chain(grant.membership_boundaries.iter().map(|boundary| { + format!( + "`{}` requires membership through `{}`", + boundary.field(), + boundary.record_type() + ) + })) .collect::>() .join(" and ") } diff --git a/crates/registry-breg/src/compiler/statistics.rs b/crates/registry-breg/src/compiler/statistics.rs index 6ae477f835..71ddc9330d 100644 --- a/crates/registry-breg/src/compiler/statistics.rs +++ b/crates/registry-breg/src/compiler/statistics.rs @@ -1595,17 +1595,16 @@ fn validate_publisher_independence( ), )); } - let violation = if !grant.row_boundaries.is_empty() { - Some("rowBoundaries") - } else if !grant.membership_boundaries.is_empty() { - Some("membershipBoundaries") - } else if !grant.required_purposes.is_empty() { - Some("requiredPurposes") - } else if !grant.require_consent.is_empty() { - Some("requireConsent") - } else { - None - }; + let violation = + if !grant.row_boundaries.is_empty() || !grant.membership_boundaries.is_empty() { + Some("rowBoundaries") + } else if !grant.required_purposes.is_empty() { + Some("requiredPurposes") + } else if !grant.require_consent.is_empty() { + Some("requireConsent") + } else { + None + }; if let Some(member) = violation { errors.push(error( &holder.independence_code("caller-dependent"), diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index fddf2a5ffb..80fd4750e6 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -900,21 +900,24 @@ pub struct ProposalPermissionSource { pub writable_inputs: Option>, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(with = "sentinel::AuthoredTargetPermission") +)] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] +#[serde( + try_from = "sentinel::AuthoredTargetPermission", + into = "sentinel::AuthoredTargetPermission" +)] pub struct ProposalTargetPermissionSource { pub record_type: String, - #[serde( - deserialize_with = "sentinel::row_boundaries", - serialize_with = "sentinel::serialize_row_boundaries" - )] - #[cfg_attr(feature = "schema", schemars(with = "sentinel::RowBoundaries"))] pub row_boundaries: Vec, + pub membership_row_boundaries: Vec, } /// A reusable list of row boundaries, written under `rowBoundarySets`. #[derive(Clone, Debug, Eq, PartialEq)] -pub struct RowBoundarySetSource(pub Vec); +pub struct RowBoundarySetSource(Vec); impl<'de> Deserialize<'de> for RowBoundarySetSource { fn deserialize>(deserializer: D) -> Result { @@ -933,7 +936,7 @@ impl schemars::JsonSchema for RowBoundarySetSource { } fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { - generator.subschema_for::, sentinel::RowBoundarySetRows>>() + generator.subschema_for::, sentinel::RowBoundarySetRows>>() } } @@ -2108,6 +2111,8 @@ pub struct EntitySource { /// Write-once file slots filled by immediate Action create effects. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub attachments: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub membership: Option, /// Mandatory request-access requirements checked against every profile, including module contributions. #[serde( default, @@ -5451,7 +5456,7 @@ pub struct AccessProfileSource { pub sortable_fields: UniqueSet, #[serde(default, skip_serializing_if = "Option::is_none")] pub spatial_queries: Option, - /// Compiled row reach; an empty array permits every row, as the authored `unrestricted` does. + /// Compiled claim boundaries. An empty array imposes no claim restriction. pub row_boundaries: Vec, /// Current active membership required for each stored reference key. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -5540,13 +5545,69 @@ pub struct RowBoundarySource { pub operator: BoundaryOperator, } -/// A one-hop current membership requirement, combined with every other row boundary. -/// The root field and membership key must reference the same entity. The active -/// field is Boolean, and principalField matches the profile's verified principal. +/// Stored fields that establish a current membership fact. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct MembershipDeclarationSource { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub key: String, + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub principal: String, + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub active: String, +} + +/// A membership check on one field of the protected Record type. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct MembershipRowBoundarySource { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub field: String, + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub membership: String, +} + +/// Membership entries in the normalized profile, before and after expansion. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(with = "ExpandedMembershipBoundarySource") +)] +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum MembershipBoundarySource { + Expanded(ExpandedMembershipBoundarySource), + Declared(MembershipRowBoundarySource), +} + +impl Serialize for MembershipBoundarySource { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Expanded(boundary) => boundary.serialize(serializer), + Self::Declared(_) => Err(serde::ser::Error::custom( + "a compiled access profile requires expanded membership entries", + )), + } + } +} + +impl<'de> Deserialize<'de> for MembershipBoundarySource { + fn deserialize>(deserializer: D) -> Result { + ExpandedMembershipBoundarySource::deserialize(deserializer).map(Self::Expanded) + } +} + +/// Logical membership fields carried in the compiled profile and inventory. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct MembershipBoundarySource { +pub struct ExpandedMembershipBoundarySource { pub field: String, #[serde(rename = "membershipRecordType")] pub membership_entity: String, @@ -5555,6 +5616,32 @@ pub struct MembershipBoundarySource { pub active_field: String, } +impl MembershipBoundarySource { + pub(crate) fn record_type(&self) -> &str { + match self { + Self::Expanded(boundary) => &boundary.membership_entity, + Self::Declared(boundary) => &boundary.membership, + } + } + + pub(crate) fn field(&self) -> &str { + match self { + Self::Expanded(boundary) => &boundary.field, + Self::Declared(boundary) => &boundary.field, + } + } + + pub(crate) fn entry(&self) -> MembershipRowBoundarySource { + match self { + Self::Expanded(boundary) => MembershipRowBoundarySource { + field: boundary.field.clone(), + membership: boundary.membership_entity.clone(), + }, + Self::Declared(boundary) => boundary.clone(), + } + } +} + /// Compile-time requirements, not grants. Profiles must explicitly satisfy them. /// /// This is the form the compiler holds and compiled artifacts carry, where an @@ -5999,6 +6086,7 @@ pub struct CompiledTaskGrantPermissionSource { #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde( try_from = "sentinel::AuthoredEntityPermission", + into = "sentinel::AuthoredEntityPermission", rename_all = "camelCase" )] pub struct EntityPermissionSource { @@ -6017,12 +6105,9 @@ pub struct EntityPermissionSource { pub sortable_fields: UniqueSet, #[serde(skip_serializing_if = "Option::is_none")] pub spatial_queries: Option, - /// Row reach, written as `unrestricted` when it holds no boundary. - #[serde(serialize_with = "sentinel::serialize_row_boundaries")] + /// Row reach, written as unrestricted when both lists are empty. pub row_boundaries: Vec, - /// Current active membership required for each stored reference key. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub membership_boundaries: Vec, + pub membership_row_boundaries: Vec, /// Current subject-issued consent required for each row, ANDed. #[serde(skip_serializing_if = "Vec::is_empty")] pub require_consent: Vec, @@ -6109,18 +6194,19 @@ pub struct ReadPathPermissionSource { } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(with = "sentinel::AuthoredTargetPermission") +)] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] +#[serde( + try_from = "sentinel::AuthoredTargetPermission", + into = "sentinel::AuthoredTargetPermission" +)] pub struct ActionTargetPermissionSource { - #[serde(rename = "recordType")] pub entity: String, - /// Row reach: `unrestricted`, or a list of at least one row boundary. - #[serde( - deserialize_with = "sentinel::row_boundaries", - serialize_with = "sentinel::serialize_row_boundaries" - )] - #[cfg_attr(feature = "schema", schemars(with = "sentinel::RowBoundaries"))] pub row_boundaries: Vec, + pub membership_row_boundaries: Vec, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -6220,6 +6306,8 @@ const PLAN_CAPABILITIES_REPLACEMENT: &str = "Remove `plan.capabilities`. Declare /// Members `registry.yaml` no longer accepts, each with the member that /// replaced it. +const MEMBERSHIP_BOUNDARIES_REPLACEMENT: &str = "Declare membership: {key, principal, active} on the membership Record type and write each boundary as a rowBoundaries entry {field, membership}."; + const PROJECT_REMOVED_KEYS: &[RemovedKey<'static>] = &[ RemovedKey { pointer: "/datasets/*/id", @@ -6322,12 +6410,12 @@ const PROJECT_REMOVED_KEYS: &[RemovedKey<'static>] = &[ replacement: FROM_FIELD_REPLACEMENT, }, RemovedKey { - pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { - pointer: "/accessProfiles/*/permissions/records/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/accessProfiles/*/permissions/records/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { pointer: "/entities", @@ -6526,12 +6614,12 @@ const MODULE_REMOVED_KEYS: &[RemovedKey<'static>] = &[ replacement: FROM_FIELD_REPLACEMENT, }, RemovedKey { - pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { - pointer: "/extendRecordTypes/*/accessProfiles/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/extendRecordTypes/*/accessProfiles/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { pointer: "/recordTypes/*/hooks/*/handler/kind", @@ -6671,13 +6759,35 @@ fn read_with_value_types( bytes: &[u8], format: &FormatSpec<'_>, ) -> Result, Report> { - let Decoded { - mut value, - document, - } = read_authored::(file, bytes, format)?; + let ( + Decoded { + mut value, + document, + }, + removed_error, + ) = match read_authored::(file, bytes, format) { + Ok(decoded) => (decoded, None), + Err(report) + if report + .diagnostics() + .iter() + .all(|diagnostic| diagnostic.code == "config.removed-key") => + { + let without_removed = FormatSpec { + removed_keys: &[], + ..*format + }; + ( + read_authored::(file, bytes, &without_removed)?, + Some(report), + ) + } + Err(report) => return Err(report), + }; let option_errors = field_option_diagnostics(&document, &value); if !option_errors.is_empty() { - return Err(document.report_with(option_errors)); + let removed = removed_error.into_iter().flat_map(Report::into_diagnostics); + return Err(document.report_with(removed.chain(option_errors))); } let has_value_types = value.get("valueTypes").is_some(); let has_row_boundary_sets = value.get("rowBoundarySets").is_some(); @@ -6695,8 +6805,44 @@ fn read_with_value_types( "Declare the set under rowBoundarySets in this file and reference it by its identifier, with no other member.", )]) })?; - if !has_value_types && !resolved_sets && !has_row_boundary_sets { - return document.decode().map(|value| Decoded { value, document }); + let mut requirement_errors = Vec::new(); + for collection in ["recordTypes", "extendRecordTypes"] { + for (pointer, entity) in entries_mut(&mut value, collection, "") { + let Some(rows) = entity + .pointer_mut("/accessRequirements/rowBoundaries") + .and_then(Value::as_array_mut) + else { + continue; + }; + for (index, row) in rows.iter_mut().enumerate() { + if serde_json::from_value::(row.clone()).is_ok() { + let base = format!("{pointer}/accessRequirements/rowBoundaries"); + let site = format!("{base}/{index}"); + requirement_errors.push(document.diagnostic_at_value( + Severity::Error, + "breg.access.membership-access-requirement-unsupported", + if document.span_of(&site).is_some() { + &site + } else { + &base + }, + "Record type accessRequirements.rowBoundaries accepts claim entries only.", + "Use a membership entry in rowBoundaries on a grant.", + )); + // Keep the item index while decoding the rest of the document. + // The requirement diagnostic prevents this placeholder from escaping. + *row = serde_json::json!({"field":"id","claim":"sub","operator":"equals"}); + } + } + } + } + if requirement_errors.is_empty() { + if let Some(report) = removed_error { + return Err(report); + } + if !has_value_types && !resolved_sets && !has_row_boundary_sets { + return document.decode().map(|value| Decoded { value, document }); + } } // Every reference is expanded, so the read file holds the boundaries // inline and no set: it serializes to source that reads back the same. @@ -6717,10 +6863,11 @@ fn read_with_value_types( } let normalized = serde_json::to_vec(&value).expect("normalized authoring value serializes"); match read_authored::(file, &normalized, format) { - Ok(decoded) => Ok(Decoded { + Ok(decoded) if requirement_errors.is_empty() => Ok(Decoded { value: decoded.value, document, }), + Ok(_) => Err(document.report_with(requirement_errors)), Err(report) => { let diagnostics = report .into_diagnostics() @@ -6770,6 +6917,7 @@ fn read_with_value_types( .collect(); placed }) + .chain(requirement_errors) .collect(); Err(Report::new(diagnostics)) } diff --git a/crates/registry-breg/src/contract/sentinel.rs b/crates/registry-breg/src/contract/sentinel.rs index 49546f7dad..057f786e55 100644 --- a/crates/registry-breg/src/contract/sentinel.rs +++ b/crates/registry-breg/src/contract/sentinel.rs @@ -19,9 +19,10 @@ use registry_platform_yaml::{shape_union, Invalid, LocalId}; use serde::{de::IgnoredAny, Deserialize, Deserializer, Serialize, Serializer}; use super::{ - AccessProfileSource, AccessRequirementsSource, ActorKindSource, CompiledTaskGrantSource, - ConsentRequirementSource, EntityPermissionSource, LookupPermissionSource, - MembershipBoundarySource, Operation, PermissionsSource, ProvenanceFieldSource, + AccessProfileSource, AccessRequirementsSource, ActionTargetPermissionSource, ActorKindSource, + CompiledTaskGrantSource, ConsentRequirementSource, EntityPermissionSource, + LookupPermissionSource, MembershipBoundarySource, MembershipRowBoundarySource, Operation, + PermissionsSource, ProposalTargetPermissionSource, ProvenanceFieldSource, ReadPathPermissionSource, RequiredFilterSource, RowBoundarySource, SpatialQueryPermissionSource, UniqueSet, }; @@ -55,6 +56,12 @@ impl Items for Vec { } } +impl Items for Vec { + fn holds_nothing(&self) -> bool { + self.is_empty() + } +} + impl Items for Vec { fn holds_nothing(&self) -> bool { self.is_empty() @@ -167,6 +174,86 @@ pub(super) enum RequiredScopes { shape_union!(RequiredScopes { scalar => Unrestricted, list => Listed }); +/// A row is bounded either by a direct claim or a membership Record type. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub(super) enum RowBoundaryEntry { + Claim(RowBoundarySource), + Membership(MembershipRowBoundarySource), +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for RowBoundaryEntry { + fn schema_name() -> std::borrow::Cow<'static, str> { + "RowBoundaryEntry".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let local_id = generator.subschema_for::(); + let operator = generator.subschema_for::(); + schemars::json_schema!({ + "type": "object", + "description": "A claim entry {field, claim, operator} or a membership entry {field, membership}.", + "additionalProperties": false, + "required": ["field"], + "properties": { + "field": {"type": "string"}, + "claim": {"type": "string"}, + "operator": operator, + "membership": local_id.clone() + }, + "if": {"required": ["membership"]}, + "then": {"properties": {"field": local_id, "claim": false, "operator": false}}, + "else": {"required": ["claim", "operator"]} + }) + } +} + +impl<'de> Deserialize<'de> for RowBoundaryEntry { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Entry { + #[serde(default, deserialize_with = "present")] + field: Option, + #[serde(default, deserialize_with = "present")] + claim: Option, + #[serde(default, deserialize_with = "present")] + operator: Option, + #[serde(default, deserialize_with = "present")] + membership: Option, + } + fn present<'de, T: Deserialize<'de>, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + T::deserialize(deserializer).map(Some) + } + let entry = Entry::deserialize(deserializer)?; + match (entry.field, entry.claim, entry.operator, entry.membership) { + (Some(field), Some(claim), Some(operator), None) => { + Ok(Self::Claim(RowBoundarySource { + field, + claim, + operator, + })) + } + (Some(field), None, None, Some(membership)) => { + Ok(Self::Membership(MembershipRowBoundarySource { + field: LocalId::new(field) + .map_err(Invalid::into_error)? + .into_string(), + membership: membership.into_string(), + })) + } + _ => Err(Invalid::expected( + "a claim entry {field, claim, operator} or a membership entry {field, membership}", + "Write exactly one of the two rowBoundaries entry shapes.", + ) + .into_error()), + } + } +} + /// A reference to a named list of row boundaries the file declares under /// `rowBoundarySets`. The reader expands a reference into the set's boundaries /// before the typed model is decoded, so the compiler never holds one. @@ -186,9 +273,9 @@ pub(super) struct RowBoundarySetReference { pub(super) enum RowBoundaries { /// Reach every row. Unrestricted(Unrestricted), - /// Reach the rows every listed boundary binds to the caller's claims. - Listed(Listed, Rows>), - /// Reach the rows every boundary of a named set binds to the caller's claims. + /// Reach the rows bounded by every listed claim or membership entry. + Listed(Listed, Rows>), + /// Reach the rows bounded by every entry in a named set. // The reader expands the reference before decoding, so the typed model // only refuses it and never reads the identifier. Reference(#[allow(dead_code)] RowBoundarySetReference), @@ -222,40 +309,101 @@ pub(super) fn serialize_required_scopes( } } +type SplitRows = (Vec, Vec); + impl RowBoundaries { - /// The boundaries the compiler holds, where `unrestricted` is none. An - /// unexpanded reference is refused rather than read as none. - fn into_boundaries(self) -> Result, Invalid> { - match self { - Self::Unrestricted(_) => Ok(Vec::new()), - Self::Listed(Listed(boundaries, _)) => Ok(boundaries), - Self::Reference(_) => Err(Invalid::expected( - UNRESOLVED_REFERENCE, - UNRESOLVED_REFERENCE_ACTION, - )), + fn into_boundaries(self) -> Result { + let entries = match self { + Self::Unrestricted(_) => return Ok((Vec::new(), Vec::new())), + Self::Listed(Listed(entries, _)) => entries, + Self::Reference(_) => { + return Err(Invalid::expected( + UNRESOLVED_REFERENCE, + UNRESOLVED_REFERENCE_ACTION, + )) + } + }; + let mut claims = Vec::new(); + let mut memberships = Vec::new(); + for entry in entries { + match entry { + RowBoundaryEntry::Claim(claim) => claims.push(claim), + RowBoundaryEntry::Membership(membership) => memberships.push(membership), + } } + Ok((claims, memberships)) } -} -pub(super) fn row_boundaries<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - RowBoundaries::deserialize(deserializer)? - .into_boundaries() - .map_err(Invalid::into_error) + fn from_boundaries( + claims: Vec, + memberships: Vec, + ) -> Self { + if claims.is_empty() && memberships.is_empty() { + Self::Unrestricted(Unrestricted(PhantomData)) + } else { + Self::Listed(Listed( + claims + .into_iter() + .map(RowBoundaryEntry::Claim) + .chain(memberships.into_iter().map(RowBoundaryEntry::Membership)) + .collect(), + PhantomData, + )) + } + } } -pub(super) fn serialize_row_boundaries( - boundaries: &[RowBoundarySource], - serializer: S, -) -> Result { - if boundaries.is_empty() { - serializer.serialize_str(UNRESTRICTED) - } else { - boundaries.serialize(serializer) +impl Serialize for RowBoundaries { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Unrestricted(_) => serializer.serialize_str(UNRESTRICTED), + Self::Listed(Listed(entries, _)) => entries.serialize(serializer), + Self::Reference(_) => Err(serde::ser::Error::custom(UNRESOLVED_REFERENCE)), + } } } +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(super) struct AuthoredTargetPermission { + record_type: String, + row_boundaries: RowBoundaries, +} + +macro_rules! target_permission { + ($source:ident, $record_type:ident) => { + impl TryFrom for $source { + type Error = Invalid; + + fn try_from(authored: AuthoredTargetPermission) -> Result { + let (row_boundaries, membership_row_boundaries) = + authored.row_boundaries.into_boundaries()?; + Ok(Self { + $record_type: authored.record_type, + row_boundaries, + membership_row_boundaries, + }) + } + } + + impl From<$source> for AuthoredTargetPermission { + fn from(source: $source) -> Self { + Self { + record_type: source.$record_type, + row_boundaries: RowBoundaries::from_boundaries( + source.row_boundaries, + source.membership_row_boundaries, + ), + } + } + } + }; +} + +target_permission!(ActionTargetPermissionSource, entity); +target_permission!(ProposalTargetPermissionSource, record_type); + /// Declares a member that only narrows: a list of at least one item, omitted /// when it narrows nothing. A scalar is refused with the same fix as an empty /// list, so an author who writes `unrestricted` here is told to omit the @@ -343,7 +491,7 @@ narrowing_member!( RowBoundarySetRows, RowBoundarySetRowsShapes, row_boundary_set_rows, - Vec, + Vec, "a list of at least one row boundary", "List the row boundaries the set holds. A set is a reusable list, so it is never empty and never unrestricted: write unrestricted on the grant that reaches every row." ); @@ -518,14 +666,7 @@ pub(super) struct AuthoredModuleProfile { #[serde(default, skip_serializing_if = "Option::is_none")] spatial_queries: Option, /// Row reach: `unrestricted`, or a list of at least one row boundary. - #[serde( - deserialize_with = "row_boundaries", - serialize_with = "serialize_row_boundaries" - )] - #[cfg_attr(feature = "schema", schemars(with = "RowBoundaries"))] - row_boundaries: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - membership_boundaries: Vec, + row_boundaries: RowBoundaries, #[serde(default, skip_serializing_if = "Vec::is_empty")] require_consent: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -550,9 +691,12 @@ pub(super) struct AuthoredModuleProfile { allow_data_export: bool, } -impl From for AccessProfileSource { - fn from(authored: AuthoredModuleProfile) -> Self { - Self { +impl TryFrom for AccessProfileSource { + type Error = Invalid; + + fn try_from(authored: AuthoredModuleProfile) -> Result { + let (row_boundaries, memberships) = authored.row_boundaries.into_boundaries()?; + Ok(Self { id: authored.id, display: authored.display, default: authored.default, @@ -571,8 +715,11 @@ impl From for AccessProfileSource { required_filters: authored.required_filters, sortable_fields: authored.sortable_fields, spatial_queries: authored.spatial_queries, - row_boundaries: authored.row_boundaries, - membership_boundaries: authored.membership_boundaries, + row_boundaries, + membership_boundaries: memberships + .into_iter() + .map(MembershipBoundarySource::Declared) + .collect(), require_consent: authored.require_consent, lookups: authored.lookups, read_paths: authored.read_paths, @@ -580,7 +727,7 @@ impl From for AccessProfileSource { revision_access: authored.revision_access, provenance_fields: authored.provenance_fields, allow_data_export: authored.allow_data_export, - } + }) } } @@ -605,8 +752,20 @@ impl From for AuthoredModuleProfile { required_filters: profile.required_filters, sortable_fields: profile.sortable_fields, spatial_queries: profile.spatial_queries, - row_boundaries: profile.row_boundaries, - membership_boundaries: profile.membership_boundaries, + row_boundaries: RowBoundaries::from_boundaries( + profile.row_boundaries, + profile + .membership_boundaries + .into_iter() + .map(|entry| match entry { + MembershipBoundarySource::Declared(entry) => entry, + MembershipBoundarySource::Expanded(entry) => MembershipRowBoundarySource { + field: entry.field, + membership: entry.membership_entity, + }, + }) + .collect(), + ), require_consent: profile.require_consent, lookups: profile.lookups, read_paths: profile.read_paths, @@ -621,12 +780,10 @@ impl From for AuthoredModuleProfile { pub(super) fn module_access_profiles<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - Ok( - registry_platform_yaml::id_keyed_by_local_id::(deserializer)? - .into_iter() - .map(AccessProfileSource::from) - .collect(), - ) + registry_platform_yaml::id_keyed_by_local_id::(deserializer)? + .into_iter() + .map(|profile| AccessProfileSource::try_from(profile).map_err(Invalid::into_error)) + .collect() } pub(super) fn serialize_module_access_profiles( @@ -688,7 +845,7 @@ pub(super) fn permissions<'de, D: Deserializer<'de>>( /// What a profile may do with one entity. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", schemars(rename = "EntityPermissionSource"))] -#[derive(Deserialize)] +#[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] pub(super) struct AuthoredEntityPermission { #[serde(rename = "recordType")] @@ -721,30 +878,36 @@ pub(super) struct AuthoredEntityPermission { required_filters: Vec, #[serde(default)] sortable_fields: UniqueSet, - #[serde(default)] + #[serde(default, skip_serializing_if = "Option::is_none")] spatial_queries: Option, /// Row reach: `unrestricted`, or a list of at least one row boundary. #[cfg_attr(feature = "schema", schemars(with = "RowBoundaries"))] row_boundaries: Option, - /// Current active membership required for each stored reference key. - #[serde(default)] - membership_boundaries: Vec, /// Current subject-issued consent required for each row, ANDed. - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] require_consent: Vec, - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] lookups: Vec, - #[serde(default)] + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] read_paths: Vec, - #[serde(default)] + #[serde(default, skip_serializing_if = "super::is_false")] + #[cfg_attr(feature = "schema", schemars(extend("default" = false)))] allow_count: bool, #[serde(default)] revision_access: bool, - #[serde(default, deserialize_with = "super::unique_items")] + #[serde( + default, + deserialize_with = "super::unique_items", + skip_serializing_if = "Vec::is_empty" + )] #[cfg_attr( feature = "schema", schemars(with = "UniqueSet") )] + #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] provenance_fields: Vec, #[serde(default)] allow_data_export: bool, @@ -760,6 +923,7 @@ impl TryFrom for EntityPermissionSource { "Declare rowBoundaries on the permission: list the row boundaries that bind rows to the caller's claims, or write unrestricted to reach every row.", )); }; + let (row_boundaries, membership_row_boundaries) = row_boundaries.into_boundaries()?; Ok(Self { entity: authored.entity, operations: authored.operations, @@ -770,8 +934,8 @@ impl TryFrom for EntityPermissionSource { required_filters: authored.required_filters, sortable_fields: authored.sortable_fields, spatial_queries: authored.spatial_queries, - row_boundaries: row_boundaries.into_boundaries()?, - membership_boundaries: authored.membership_boundaries, + row_boundaries, + membership_row_boundaries, require_consent: authored.require_consent, lookups: authored.lookups, read_paths: authored.read_paths, @@ -782,3 +946,30 @@ impl TryFrom for EntityPermissionSource { }) } } + +impl From for AuthoredEntityPermission { + fn from(source: EntityPermissionSource) -> Self { + Self { + entity: source.entity, + operations: source.operations, + readable_fields: source.readable_fields, + readable_attachments: source.readable_attachments, + writable_fields: source.writable_fields, + filterable_fields: source.filterable_fields, + required_filters: source.required_filters, + sortable_fields: source.sortable_fields, + spatial_queries: source.spatial_queries, + row_boundaries: Some(RowBoundaries::from_boundaries( + source.row_boundaries, + source.membership_row_boundaries, + )), + require_consent: source.require_consent, + lookups: source.lookups, + read_paths: source.read_paths, + allow_count: source.allow_count, + revision_access: source.revision_access, + provenance_fields: source.provenance_fields, + allow_data_export: source.allow_data_export, + } + } +} diff --git a/crates/registry-breg/src/disclosure.rs b/crates/registry-breg/src/disclosure.rs index 7d066edcf9..f6587bd523 100644 --- a/crates/registry-breg/src/disclosure.rs +++ b/crates/registry-breg/src/disclosure.rs @@ -82,6 +82,33 @@ impl DisclosurePlan<'_> { }) } + #[cfg(feature = "runtime")] + pub(crate) fn withholds_record_before_allocation( + &self, + state: &Map, + ) -> Result { + for condition in &self.conditions { + if matches!(condition.withhold, DisclosureWithhold::Record) + && condition.when.iter().all(|predicate| { + let field = match predicate { + DisclosureWhenPredicate::FieldEquals { field, .. } + | DisclosureWhenPredicate::FieldIn { field, .. } + | DisclosureWhenPredicate::FieldIsNull { field } + | DisclosureWhenPredicate::FieldIsNotNull { field } => field, + }; + self.entity + .fields + .get(field) + .is_none_or(|field| field.generate.is_none()) + }) + && when_matches(self.entity, &condition.when, state)? + { + return Ok(true); + } + } + Ok(false) + } + /// Whether a `record` or `history` condition matches `state`, so the /// record's revisions and snapshots behave as absent. pub fn withholds_history(&self, state: &Map) -> Result { diff --git a/crates/registry-breg/src/evidence_source/tests.rs b/crates/registry-breg/src/evidence_source/tests.rs index 7c9f0bf6ed..6214a239ed 100644 --- a/crates/registry-breg/src/evidence_source/tests.rs +++ b/crates/registry-breg/src/evidence_source/tests.rs @@ -427,11 +427,13 @@ fn membership_project() -> Value { {"id":"active","type":"boolean","classification":"internal"}, {"id":"other-active","type":"boolean","classification":"internal"}]})) ]); - source["accessProfiles"]["evidence-source"]["permissions"]["records"][0] - ["membershipBoundaries"] = json!([{ - "field":"organization","membershipRecordType":"membership","membershipKeyField":"organization", - "principalField":"principal","activeField":"active" - }]); + source["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + let grant = &mut source["accessProfiles"]["evidence-source"]["permissions"]["records"][0]; + grant["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); source } @@ -441,13 +443,12 @@ fn membership_behavior_reaches_helper_semantics_source_fields_and_select_authori let registry = compiled(&original, SQL); let before = export_evidence_source(®istry, &options()).unwrap(); for (name, value) in [ - ("principalField", "other-principal"), - ("activeField", "other-active"), - ("membershipKeyField", "other-organization"), + ("principal", "other-principal"), + ("active", "other-active"), + ("key", "other-organization"), ] { let mut changed = original.clone(); - changed["accessProfiles"]["evidence-source"]["permissions"]["records"][0] - ["membershipBoundaries"][0][name] = json!(value); + changed["recordTypes"]["membership"]["membership"][name] = json!(value); let after_registry = compiled(&changed, SQL); assert_eq!( select_policies(®istry, ®istry.entities()["record"], "evidence-source"), @@ -510,10 +511,7 @@ fn membership_behavior_reaches_helper_semantics_source_fields_and_select_authori fn reached_derived_source_consumes_its_membership_helper() { let mut original = membership_project(); let reader = &original["accessProfiles"]["evidence-source"]["permissions"]["records"][0]; - let (boundary, row_boundaries) = ( - reader["membershipBoundaries"].clone(), - reader["rowBoundaries"].clone(), - ); + let row_boundaries = reader["rowBoundaries"].clone(); original["recordTypes"].as_object_mut().unwrap().insert("flag".to_owned(), json!({"route":"flags","primaryDataset":"test-dataset","mutationMode":"mutable","fields":[ {"id":"code","type":"string","maximumLength":32,"classification":"internal"}, {"id":"organization","type":"reference","target":"organization","classification":"internal"}, @@ -522,15 +520,17 @@ fn reached_derived_source_consumes_its_membership_helper() { {"id":"enabled","type":"boolean","classification":"internal"}] })); original["accessProfiles"]["evidence-source"]["permissions"]["records"].as_array_mut().unwrap().push(json!({ - "recordType":"flag","operations":["get"],"readableFields":["code","enabled"],"rowBoundaries":row_boundaries, - "membershipBoundaries":boundary + "recordType":"flag","operations":["get"],"readableFields":["code","enabled"],"rowBoundaries":row_boundaries })); let sql = "SELECT r.id AS id, f.enabled AS active FROM registry_source.record r JOIN registry_source.flag f ON f.code = r.code"; let mut selection = options(); selection.fields = vec!["active".into()]; let before = export_evidence_source(&compiled(&original, sql), &selection).unwrap(); - original["accessProfiles"]["evidence-source"]["permissions"]["records"][1] - ["membershipBoundaries"][0]["field"] = json!("other-organization"); + original["accessProfiles"]["evidence-source"]["permissions"]["records"][1]["rowBoundaries"] + .as_array_mut() + .unwrap() + .last_mut() + .unwrap()["field"] = json!("other-organization"); assert_ne!( before.behavior_revision, export_evidence_source(&compiled(&original, sql), &selection) diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index 7071d38af6..9a3a784ba6 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -744,7 +744,7 @@ struct ClaimsSource { } impl ClaimsSource { - /// The authored scopes as a set, for comparison with a profile's. + /// The full authored scope set, for exact credential binding. fn scope_set(&self) -> BTreeSet { self.scopes.iter().cloned().collect() } @@ -1792,12 +1792,22 @@ fn validate_claims( profile: &AccessProfileSource, outcome: ExpectedOutcome, ) -> Result<(), FixtureError> { + // Exact bearer binding includes every authored scope. For the profile + // comparison, set aside only OIDC scopes the profile does not require. + let profile_scopes = claims + .scopes + .iter() + .filter(|scope| { + profile.required_scopes.contains(*scope) + || !registry_platform_oidc::OPENID_CONNECT_SCOPES.contains(&scope.as_str()) + }) + .cloned() + .collect::>(); if claims .principal .as_deref() .is_none_or(|value| value.is_empty() || value.len() > MAX_BINDING_BYTES) - || !claims - .scopes + || !profile_scopes .iter() .all(|scope| profile.required_scopes.contains(scope)) { @@ -1847,7 +1857,7 @@ fn validate_claims( } if outcome == ExpectedOutcome::Success && (claims.principal.is_none() - || claims.scope_set() != *profile.required_scopes + || profile_scopes != *profile.required_scopes || (!profile.required_purposes.is_empty() && claims.purpose.is_none()) || missing_direct_claim) { @@ -6898,12 +6908,14 @@ mod tests { assert_exact_claims(&undeclared, &profile, &exact, &claims.scope_set()), Err(FixtureError::AuthorityWideningRefused) ); - let widened_scopes = - BTreeSet::from(["registry:read".to_owned(), "registry:write".to_owned()]); - assert_eq!( - assert_exact_claims(&claims, &profile, &exact, &widened_scopes), - Err(FixtureError::AuthorityWideningRefused) - ); + for scope in ["registry:write", "openid"] { + let mut widened_scopes = claims.scope_set(); + widened_scopes.insert(scope.to_owned()); + assert_eq!( + assert_exact_claims(&claims, &profile, &exact, &widened_scopes), + Err(FixtureError::AuthorityWideningRefused) + ); + } } #[test] @@ -6953,6 +6965,58 @@ mod tests { } } + #[test] + fn fixture_profile_scope_comparison_sets_aside_openid_scopes() { + for (required, scopes, expected) in [ + (json!([]), json!(["openid", "profile"]), Ok(())), + ( + json!(["fixture:write", "openid"]), + json!(["openid", "profile", "fixture:write"]), + Ok(()), + ), + ( + json!(["fixture:write", "openid"]), + json!(["profile", "fixture:write"]), + Err(FixtureError::AuthorityWideningRefused), + ), + ( + json!(["fixture:write"]), + json!(["openid", "fixture:write"]), + Ok(()), + ), + ( + json!(["fixture:write"]), + json!(["openid", "fixture:write", "fixture:extra"]), + Err(FixtureError::AuthorityWideningRefused), + ), + ( + json!(["fixture:write"]), + json!(["openid"]), + Err(FixtureError::AuthorityWideningRefused), + ), + ] { + let profile = serde_json::from_value(json!({ + "id": "fixture", + "principalClaim": "sub", + "actorKind": "human", + "operations": ["get"], + "rowBoundaries": [], + "requiredScopes": required + })) + .unwrap(); + let claims = serde_json::from_value(json!({ + "principal": "fixture-person", + "actorKind": "human", + "scopes": scopes + })) + .unwrap(); + assert_eq!( + validate_claims(&claims, &profile, ExpectedOutcome::Success), + expected + ); + } + } + #[test] fn fixture_claims_leave_reserved_consent_claims_to_the_verified_client() { let profile: AccessProfileSource = serde_json::from_value(json!({ @@ -7037,7 +7101,7 @@ journeys: - id: list-people recordType: person accessProfile: person-operator - claims: {principal: fixture-operator, purpose: person-maintenance} + claims: {principal: fixture-operator, purpose: person-maintenance, scopes: [people:write]} request: {type: list} expect: {outcome: success, status: 200, count: 0} "#; @@ -7344,7 +7408,7 @@ journeys: {"id":"name","type":"string","maximumLength":80,"required":true,"classification":"internal"}], "plan":{"type":"function","function":"person-plan","inputs":["person","name"], "writes":[{"id":"person","target":{"fromInput":"person"},"operation":"patch","fields":["name"]}]}}}, - "accessProfiles":{"person-operator": {"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["person-maintenance"], + "accessProfiles":{"person-operator": {"principalClaim":"principal","requiredScopes":["people:write"],"requiredPurposes":["person-maintenance"], "permissions":{"records":[{"recordType":"person","operations":["get","list"],"readableFields":["name"],"rowBoundaries":"unrestricted"}], "actions":[{"action":"rename-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} })).unwrap() @@ -8733,7 +8797,7 @@ journeys: .expect("constraint project compiles"); let step = |id: &str, request: &str| { format!( - " - id: {id}\n recordType: widget\n accessProfile: operator\n claims:\n principal: fixture-operator\n purpose: case-management\n directClaims: {{jurisdiction: zone-a}}\n request: {request}\n expect: {{outcome: refusal, status: 409, problemCode: mutation.conflict}}\n" + " - id: {id}\n recordType: widget\n accessProfile: operator\n claims:\n principal: fixture-operator\n scopes: [fixture:write]\n purpose: case-management\n directClaims: {{jurisdiction: zone-a}}\n request: {request}\n expect: {{outcome: refusal, status: 409, problemCode: mutation.conflict}}\n" ) }; let journeys = format!( diff --git a/crates/registry-breg/src/fixtures/proposals.rs b/crates/registry-breg/src/fixtures/proposals.rs index a917091678..b48c7bbbb3 100644 --- a/crates/registry-breg/src/fixtures/proposals.rs +++ b/crates/registry-breg/src/fixtures/proposals.rs @@ -83,6 +83,7 @@ fn profile(grant: &CompiledProposalPermission) -> Result DdlInventory { + let membership_probes = crate::membership::probes(entities, actions); let mut statements = vec![DdlStatement { id: "schema.registry_data".to_owned(), kind: DdlStatementKind::Schema, @@ -502,7 +503,10 @@ pub(crate) fn generate_ddl_with_actions( for field_id in spatial_projection_fields(entity) { statements.push(spatial_projection_statements(entity, &field_id).create_index); } - for (id, _, sql) in crate::consent::index_statements(entity) { + for (id, _, sql) in crate::consent::index_statements(entity) + .into_iter() + .chain(crate::membership::index_statement(entity)) + { statements.push(DdlStatement { id, kind: DdlStatementKind::Index, @@ -544,35 +548,48 @@ pub(crate) fn generate_ddl_with_actions( // Invoker helpers give membership facts a processing-only RLS context. // The exception block rolls back the local marker on errors; normal return // restores its prior value. No cluster-wide custom-parameter ACL is needed. - for entity in entities.values() { - for (profile_id, boundaries) in &entity.membership_boundaries { - for (index, boundary) in boundaries.iter().enumerate() { - let name = crate::membership::function_name(&entity.id, profile_id, index); - let body = format!( - "DECLARE prior_marker text := current_setting('registry.membership_probe', true); authorized boolean; BEGIN PERFORM set_config('registry.membership_probe', {}, true); SELECT EXISTS (SELECT 1 FROM registry_data.{} AS membership WHERE {} AND membership.{} = $1) INTO authorized; PERFORM set_config('registry.membership_probe', COALESCE(prior_marker, ''), true); RETURN authorized; EXCEPTION WHEN OTHERS THEN RAISE; END", - quote_literal(&name), - quote_identifier(&boundary.membership_table), - crate::membership::source_predicate(boundary, "membership"), - quote_identifier(&boundary.membership_key_column), - ); - statements.push(DdlStatement { - id: format!("registry_context.{name}"), - kind: DdlStatementKind::Function, - sql: format!( - "CREATE FUNCTION registry_context.{}(uuid) RETURNS boolean LANGUAGE plpgsql STABLE STRICT SECURITY INVOKER SET search_path = pg_catalog AS {}", - quote_identifier(&name), quote_literal(&body), - ), - }); - functions.push(DdlFunction { - id: format!("registry_context.{name}"), - schema: "registry_context".to_owned(), - name, - arguments: "uuid".to_owned(), - runtime_execute: true, - spatial_bbox_execute: false, - }); - } - } + for probe in &membership_probes { + let boundary = probe.boundary; + let name = probe.name.clone(); + let scan = format!( + "1 FROM registry_data.{} AS membership WHERE {} AND membership.{} = $1", + quote_identifier(&boundary.membership_table), + crate::membership::source_predicate(boundary, "membership"), + quote_identifier(&boundary.membership_key_column), + ); + let (query, volatility) = if probe.locks { + ( + format!( + "PERFORM {scan} ORDER BY membership.record_id FOR SHARE; authorized := FOUND" + ), + "VOLATILE", + ) + } else { + ( + format!("SELECT EXISTS (SELECT {scan}) INTO authorized"), + "STABLE", + ) + }; + let body = format!( + "DECLARE prior_marker text := current_setting('registry.membership_probe', true); authorized boolean; BEGIN PERFORM set_config('registry.membership_probe', {}, true); {query}; PERFORM set_config('registry.membership_probe', COALESCE(prior_marker, ''), true); RETURN authorized; EXCEPTION WHEN OTHERS THEN RAISE; END", + quote_literal(&name), + ); + statements.push(DdlStatement { + id: format!("registry_context.{name}"), + kind: DdlStatementKind::Function, + sql: format!( + "CREATE FUNCTION registry_context.{}(uuid) RETURNS boolean LANGUAGE plpgsql {volatility} STRICT SECURITY INVOKER SET search_path = pg_catalog AS {}", + quote_identifier(&name), quote_literal(&body), + ), + }); + functions.push(DdlFunction { + id: format!("registry_context.{name}"), + schema: "registry_context".to_owned(), + name, + arguments: "uuid".to_owned(), + runtime_execute: true, + spatial_bbox_execute: false, + }); } // Consent probes share the membership security shape: an invoker helper // whose own marker opens the consent table's guarded policy for this @@ -608,17 +625,20 @@ pub(crate) fn generate_ddl_with_actions( } } for entity in entities.values() { - let runtime_privileges = runtime_privileges(entity, entities, actions); + let runtime_privileges = runtime_privileges(entity, entities, actions, &membership_probes); let runtime_lock_column = !runtime_privileges.contains(&TablePrivilege::Update) - && actions - .actions + && (membership_probes .iter() - .flat_map(|action| &action.target_uses) - .any(|target| { - target.entity_id == entity.id - && matches!(target.operation, Operation::Get | Operation::Invoke) - }); - let policies = policies(entity, entities, actions); + .any(|probe| probe.locks && probe.boundary.membership_entity == entity.id) + || actions + .actions + .iter() + .flat_map(|action| &action.target_uses) + .any(|target| { + target.entity_id == entity.id + && matches!(target.operation, Operation::Get | Operation::Invoke) + })); + let policies = policies(entity, entities, actions, &membership_probes); let table = quote_identifier(&entity.physical_table); statements.push(DdlStatement { id: format!("entity.{}.rls.enable", entity.id), @@ -1508,6 +1528,7 @@ fn runtime_privileges( entity: &CompiledEntity, entities: &BTreeMap, actions: &CompiledActionInventory, + membership_probes: &[crate::membership::MembershipProbe<'_>], ) -> BTreeSet { let operations = entity .access_profiles @@ -1526,16 +1547,14 @@ fn runtime_privileges( | Operation::Snapshot ) }) || path_select_entities(entities).contains(&entity.id) + || membership_probes + .iter() + .any(|probe| probe.boundary.membership_entity == entity.id) || entities.values().any(|root| { - root.membership_boundaries + root.consent_requirements .values() .flatten() - .any(|boundary| boundary.membership_entity == entity.id) - || root - .consent_requirements - .values() - .flatten() - .any(|requirement| requirement.record == entity.id) + .any(|requirement| requirement.record == entity.id) }) { privileges.insert(TablePrivilege::Select); @@ -1577,6 +1596,7 @@ fn policies( entity: &CompiledEntity, entities: &BTreeMap, actions: &CompiledActionInventory, + membership_probes: &[crate::membership::MembershipProbe<'_>], ) -> Vec { let mut policies = Vec::new(); for profile in entity.access_profiles.values() { @@ -1639,7 +1659,7 @@ fn policies( }); } } - policies.extend(membership_source_policies(entity, entities)); + policies.extend(membership_source_policies(entity, membership_probes)); policies.extend(consent_source_policies(entity, entities)); policies.extend(read_path_policies_for_table(entity, entities)); policies.extend(immediate_action_target_policies_for_table(entity, actions)); @@ -1680,36 +1700,38 @@ pub(crate) fn disclosure_policy_name(entity_id: &str, condition_id: &str) -> Str fn membership_source_policies( entity: &CompiledEntity, - entities: &BTreeMap, + probes: &[crate::membership::MembershipProbe<'_>], ) -> Vec { let mut policies = Vec::new(); - for root in entities.values() { - for (profile, boundaries) in &root.membership_boundaries { - for (index, boundary) in boundaries.iter().enumerate() { - if boundary.membership_entity != entity.id { - continue; - } - policies.push(DdlPolicy { - permissive: true, - name: format!( - "registry_{}", - crate::membership::function_name(&root.id, profile, index) - ), - command: PolicyCommand::Select, - access_profile: profile.clone(), - applies_to: DdlPolicyRole::Runtime, - using_expression: Some(format!( - "({}) AND ({})", - crate::membership::source_guard(&root.id, profile, index), - crate::membership::source_predicate( - boundary, - "e_identifier(&entity.physical_table) - ) - )), - check_expression: None, - }); - } + for probe in probes + .iter() + .filter(|probe| probe.boundary.membership_entity == entity.id) + { + let select = DdlPolicy { + permissive: true, + name: format!("registry_{}", probe.name), + command: PolicyCommand::Select, + access_profile: probe.profile.to_owned(), + applies_to: DdlPolicyRole::Runtime, + using_expression: Some(format!( + "({}) AND ({})", + crate::membership::source_guard(&probe.name, probe.profile), + crate::membership::source_predicate( + probe.boundary, + "e_identifier(&entity.physical_table) + ) + )), + check_expression: None, + }; + if probe.locks { + policies.push(DdlPolicy { + name: format!("{}_update", select.name), + command: PolicyCommand::Update, + check_expression: Some("false".to_owned()), + ..select.clone() + }); } + policies.push(select); } policies } @@ -2113,6 +2135,7 @@ fn immediate_action_target_policies_for_table( if !emitted_profiles.insert(grant.profile_id.as_str()) || target_effects.is_empty() { continue; } + let first_policy = policies.len(); let expressions = immediate_action_application_expressions( target_entity, action, @@ -2211,6 +2234,7 @@ fn immediate_action_target_policies_for_table( check_expression: Some(writable), }); } + append_action_target_probes(target_entity, grant, &mut policies[first_policy..]); } for target_use in action.target_uses.iter().filter(|target_use| { @@ -2232,6 +2256,7 @@ fn immediate_action_target_policies_for_table( .iter() .any(|target| target.entity_id == target_entity.id) }) { + let first_policy = policies.len(); let expression = immediate_action_link_expression( target_entity, action, @@ -2267,12 +2292,31 @@ fn immediate_action_target_policies_for_table( using_expression: Some(format!("{expression} AND record_lifecycle = 'active'")), check_expression: Some("false".to_owned()), }); + append_action_target_probes(target_entity, grant, &mut policies[first_policy..]); } } } policies } +fn append_action_target_probes( + entity: &CompiledEntity, + grant: &crate::model::CompiledActionPermission, + policies: &mut [DdlPolicy], +) { + if let Some(target) = grant + .entity_target_locks() + .find(|target| target.entity_id == entity.id) + { + crate::membership::append_target_probes( + entity, + &grant.profile_id, + &target.membership_boundaries, + policies, + ); + } +} + fn immediate_action_application_expressions( target_entity: &CompiledEntity, action: &CompiledAction, @@ -3430,6 +3474,13 @@ pub(crate) fn quote_literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } +#[cfg(test)] +use crate as breg_fixture_crate; + +#[cfg(test)] +#[path = "../tests/support/membership_targets.rs"] +mod membership_targets; + #[cfg(test)] mod tests { use serde_json::json; @@ -3443,6 +3494,147 @@ mod tests { SPATIAL_BBOX_FUNCTION_NAME, SPATIAL_POLYGON_CONTRACT_FUNCTION_NAME, }; + #[test] + fn action_target_policies_append_the_membership_probe() { + let (registry, mut actions) = super::membership_targets::immediate(false); + let mut patch = actions.actions[0].effects[0].clone(); + patch.id = "patch-child".into(); + patch.operation = super::Operation::Patch; + patch.target.binding = crate::model::CompiledPlanTargetBinding::Existing { + input: "child".into(), + }; + actions.actions[0].effects.push(patch); + let ddl = super::generate_ddl_with_actions( + registry.entities(), + registry.physical_names(), + &actions, + ); + let probe = ddl + .functions + .iter() + .find(|f| f.name.starts_with("membership_target_")) + .unwrap(); + assert_eq!( + ddl.functions + .iter() + .filter(|f| f.name.starts_with("membership_target_")) + .count(), + 1 + ); + for (entity, commands) in [ + ( + "child", + vec![ + super::PolicyCommand::Select, + super::PolicyCommand::Insert, + super::PolicyCommand::Update, + ], + ), + ( + "parent", + vec![super::PolicyCommand::Select, super::PolicyCommand::Update], + ), + ] { + let table = ddl + .tables + .iter() + .find(|table| table.entity_id == entity) + .unwrap(); + let field = if entity == "child" { + "parent" + } else { + "directory" + }; + let suffix = format!( + " AND registry_context.{}({})", + quote_identifier(&probe.name), + quote_identifier(®istry.entities()[entity].fields[field].physical_name) + ); + assert_eq!( + table + .policies + .iter() + .map(|policy| policy.command) + .collect::>(), + commands + ); + for expression in table.policies.iter().flat_map(|policy| { + policy + .using_expression + .iter() + .chain(&policy.check_expression) + }) { + assert!( + expression == "false" || expression.ends_with(&suffix), + "{expression}" + ); + } + } + } + + #[test] + fn proposal_target_policies_append_the_membership_probe() { + for automatic in [false, true] { + let source = crate::proposal_hooks::test_model::source(json!([])); + let (registry, actions) = super::membership_targets::proposal(source, automatic); + let lockable = + crate::membership::lockable_membership_tables(registry.entities(), &actions); + assert_eq!(lockable.contains_key(&("clerk", "membership")), !automatic); + let before = super::proposal::target_policies( + ®istry.entities()["target"], + registry.actions(), + ); + let after = super::proposal::target_policies(®istry.entities()["target"], &actions); + assert_eq!(before.len(), after.len()); + let mut caller_checks = 0; + let mut system_checks = 0; + for (base, guarded) in before.iter().zip(&after) { + for (base, guarded) in base + .using_expression + .iter() + .chain(&base.check_expression) + .zip( + guarded + .using_expression + .iter() + .chain(&guarded.check_expression), + ) + { + if base.contains("'actorKind' = 'caller'") { + assert!(guarded.starts_with(&format!( + "({base}) AND registry_context.\"membership_target_" + ))); + caller_checks += 1; + } else { + assert_eq!(base, guarded); + system_checks += usize::from(base.contains("'system-proposal-apply'")); + } + } + } + assert!(caller_checks > 0); + assert_eq!(system_checks > 0, automatic); + } + } + + #[test] + fn the_membership_lock_helper_is_volatile_and_takes_for_share() { + let (registry, actions) = super::membership_targets::immediate(false); + let ddl = super::generate_ddl_with_actions( + registry.entities(), + registry.physical_names(), + &actions, + ); + let name = crate::membership::lock_function_name("registrar", "membership"); + let mut helper = ddl + .statements + .iter() + .filter(|statement| statement.id == format!("registry_context.{name}")); + let sql = &helper.next().unwrap().sql; + assert!(helper.next().is_none()); + assert!(sql.contains("(uuid) RETURNS boolean LANGUAGE plpgsql VOLATILE STRICT SECURITY INVOKER SET search_path = pg_catalog")); + assert!(sql.contains("ORDER BY membership.record_id FOR SHARE; authorized := FOUND")); + } + #[cfg(feature = "runtime")] #[test] fn an_added_required_column_carries_its_requiredness_in_a_separate_statement() { diff --git a/crates/registry-breg/src/history_schema.rs b/crates/registry-breg/src/history_schema.rs index e9454ca13b..26fd486a78 100644 --- a/crates/registry-breg/src/history_schema.rs +++ b/crates/registry-breg/src/history_schema.rs @@ -847,6 +847,7 @@ mod tests { change_control: None, classification: Classification::Restricted, access_requirements: None, + membership: None, access_log: None, disclosure_conditions: Vec::new(), geojson: None, diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index f2f746cba9..0c0046971d 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -2433,7 +2433,8 @@ fn compile_permissions( "Action permissions support only the invoke operation", )); } - let target_locks = compile_permission_targets(entities, profile, grant, errors); + let target_locks = + compile_permission_targets(entities, profile, grant, target_uses, errors); validate_permission_covers_uses(&target_locks, target_uses, errors); let targets = discriminate_permission_targets(&target_locks, target_uses, errors); for result in grant.results.iter() { @@ -2487,12 +2488,14 @@ fn validate_action_permission_sources( struct PermissionTargetLock { entity_id: String, row_boundaries: Vec, + membership_boundaries: Vec, } fn compile_permission_targets( entities: &BTreeMap, profile: &ProjectAccessProfileSource, grant: &crate::contract::ActionPermissionSource, + target_uses: &[CompiledActionTargetUse], errors: &mut Vec, ) -> Vec { let mut seen = BTreeSet::new(); @@ -2526,15 +2529,63 @@ fn compile_permission_targets( "project.accessProfiles[].permissions.actions[].targets", errors, ); + let writes = target_uses.iter().any(|use_| { + use_.entity_id == target.entity && crate::membership::is_record_write(use_.operation) + }); + let membership_boundaries = compile_target_memberships( + entities, profile, entity, &target.row_boundaries, &target.membership_row_boundaries, + true, + writes, + &format!("accessProfiles[id={}].permissions.actions[action={}].targets[recordType={}].rowBoundaries", profile.id, grant.action, target.entity), + errors, + ); targets.push(PermissionTargetLock { entity_id: target.entity.clone(), row_boundaries: target.row_boundaries.clone(), + membership_boundaries, }); } targets.sort_by(|left, right| left.entity_id.cmp(&right.entity_id)); targets } +#[allow(clippy::too_many_arguments)] +fn compile_target_memberships( + entities: &BTreeMap, + profile: &ProjectAccessProfileSource, + entity: &CompiledEntity, + row_boundaries: &[RowBoundarySource], + entries: &[crate::contract::MembershipRowBoundarySource], + write_grant: bool, + writes_record: bool, + location: &str, + errors: &mut Vec, +) -> Vec { + crate::membership::validate_write_admission( + profile.required_scopes.is_empty(), + profile.requester_clients.is_empty(), + &profile.principal_claim, + write_grant, + writes_record && entity.membership.is_some(), + row_boundaries, + !entries.is_empty(), + location, + errors, + ); + entries + .iter() + .filter_map( + |entry| match crate::membership::resolve_entry(entry, entities, location) { + Ok((physical, _)) => Some(physical), + Err(error) => { + errors.push(error); + None + } + }, + ) + .collect() +} + fn discriminate_permission_targets( target_locks: &[PermissionTargetLock], target_uses: &[CompiledActionTargetUse], @@ -2553,6 +2604,7 @@ fn discriminate_permission_targets( operation: target_use.operation, source: target_use.source.clone(), row_boundaries: target_lock.row_boundaries.clone(), + membership_boundaries: target_lock.membership_boundaries.clone(), }); } if !matched { @@ -3258,9 +3310,27 @@ fn compile_execution( "accessProfiles[].permissions.proposals[].targets", errors, ); + let write_grant = grant + .operations + .iter() + .copied() + .any(crate::membership::is_proposal_write); + let writes = write_grant + && target_uses.iter().any(|use_| { + use_.entity_id == target.record_type + && crate::membership::is_record_write(use_.operation) + }); + let membership_boundaries = compile_target_memberships( + entities, profile, entity, &target.row_boundaries, &target.membership_row_boundaries, + write_grant, + writes, + &format!("accessProfiles[id={}].permissions.proposals[action={}].targets[recordType={}].rowBoundaries", profile.id, grant.action, target.record_type), + errors, + ); targets.push(CompiledProposalTargetPermission { entity_id: target.record_type.clone(), row_boundaries: target.row_boundaries.clone(), + membership_boundaries, }); } if !authority_status @@ -3874,3 +3944,86 @@ pub(crate) fn definition_revision( )) ) } + +#[cfg(test)] +mod membership_target_tests { + use super::*; + use crate::compiler::{compile_project, CompileProfile}; + use crate::contract::{parse_project_json, MembershipRowBoundarySource}; + use serde_json::json; + + fn project() -> (crate::contract::RegistryProject, crate::CompiledRegistry) { + let mut source = crate::proposal_hooks::test_model::source(json!([])); + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../products/breg/fixtures/organization-membership-access/registry.yaml" + )) + .unwrap(); + for id in ["membership", "organization"] { + source["recordTypes"][id] = fixture["recordTypes"][id].clone(); + source["recordTypes"][id]["primaryDataset"] = json!("directory"); + } + source["recordTypes"]["membership"]["accessRequirements"]["requiredScopes"] = + json!(["proposal:manage"]); + source["recordTypes"]["target"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"organization","type":"reference","target":"organization","classification":"internal"})); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + (project, registry) + } + + fn entry() -> MembershipRowBoundarySource { + MembershipRowBoundarySource { + field: "organization".into(), + membership: "membership".into(), + } + } + + #[test] + fn an_action_target_membership_entry_reaches_every_discriminated_use() { + let (mut project, registry) = project(); + let profile = &mut project.access_profiles[0]; + profile.permissions.actions[0].targets[0].membership_row_boundaries = vec![entry()]; + let uses = ®istry.actions().actions[0].target_uses; + let mut errors = Vec::new(); + let locks = compile_permission_targets( + registry.entities(), + profile, + &profile.permissions.actions[0], + uses, + &mut errors, + ); + let targets = discriminate_permission_targets(&locks, uses, &mut errors); + assert!(targets.len() > 1); + assert!(targets.iter().all(|target| { + target.membership_boundaries.len() == 1 + && target.membership_boundaries[0].membership_entity == "membership" + })); + assert!(errors.is_empty(), "{errors:?}"); + } + + #[test] + fn a_proposal_target_membership_entry_reaches_the_compiled_target() { + let (mut project, registry) = project(); + let action = ®istry.actions().actions[0]; + project.access_profiles[0].permissions.proposals[0].targets[0].membership_row_boundaries = + vec![entry()]; + let mut errors = Vec::new(); + let execution = compile_execution( + &project.actions[0], + registry.entities(), + &project.access_profiles, + &project.review_authorities, + &action.target_uses, + &mut errors, + ); + let crate::model::CompiledActionExecution::Proposal { proposal } = execution else { + panic!("expected a Proposal"); + }; + let compiled = &proposal.permissions[0].targets[0].membership_boundaries; + assert_eq!(compiled.len(), 1); + assert_eq!(compiled[0].membership_entity, "membership"); + assert!(errors.is_empty(), "{errors:?}"); + } +} diff --git a/crates/registry-breg/src/ingestion_store.rs b/crates/registry-breg/src/ingestion_store.rs index 117c42d3e4..7edaf31c01 100644 --- a/crates/registry-breg/src/ingestion_store.rs +++ b/crates/registry-breg/src/ingestion_store.rs @@ -1619,7 +1619,7 @@ mod tests { {"id":"serial-code","apiName":"serialNumber","type":"string","maximumLength":64,"classification":"internal"} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["review"], "permissions":{"records":[{ "recordType":"entry","operations":["create"], @@ -1746,7 +1746,7 @@ mod tests { "datasets":{{"test-dataset": {{}}}},"recordTypes":{{"entry":{{"primaryDataset":"test-dataset","route":"entries","mutationMode":"mutable","classification":"internal", "fields":[{fields}] }}}}, - "accessProfiles":{{"operator":{{"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{{"operator":{{"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["review"], "permissions":{{"records":[{{ "recordType":"entry","operations":["create"], diff --git a/crates/registry-breg/src/membership.rs b/crates/registry-breg/src/membership.rs index 522bf756f4..cac18204fa 100644 --- a/crates/registry-breg/src/membership.rs +++ b/crates/registry-breg/src/membership.rs @@ -1,27 +1,61 @@ // SPDX-License-Identifier: Apache-2.0 //! One-hop current membership checks over governed stored records. -use std::collections::BTreeMap; -#[cfg(feature = "runtime")] -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; -use crate::contract::{EntitySource, FieldTypeSource, Operation}; +use crate::contract::{ + ActionPlanSource, ActionSource, EntitySource, ExpandedMembershipBoundarySource, + FieldTypeSource, MembershipBoundarySource, MembershipRowBoundarySource, Operation, + ProposalOperation, RegistryProject, RowBoundarySource, +}; use crate::diagnostics::Diagnostic; use crate::generated_ddl::{quote_identifier, quote_literal}; -use crate::model::{CompiledEntity, CompiledMembershipBoundary}; +use crate::model::{ + CompiledActionExecution, CompiledActionInventory, CompiledEntity, CompiledMembershipBoundary, +}; use crate::physical_names::hex_prefix; use sha2::{Digest, Sha256}; -pub(crate) fn validate(entities: &BTreeMap, errors: &mut Vec) { +pub(crate) fn validate( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { for entity in entities.values() { + validate_declaration(entity, entities, errors); for profile in &entity.access_profiles { - if profile.membership_boundaries.is_empty() { - continue; - } let location = format!( - "recordTypes[id={}].accessProfiles[id={}].membershipBoundaries", + "recordTypes[id={}].accessProfiles[id={}].rowBoundaries", entity.id, profile.id ); + let has_membership = !profile.membership_boundaries.is_empty(); + let writes = profile.operations.iter().copied().any(is_record_write); + let writes_membership = entity.membership.is_some() + && (writes + || profile.operations.contains(&Operation::Import) + || profile.operations.contains(&Operation::Batch)); + validate_write_admission( + profile.required_scopes.is_empty(), + profile.requester_clients.is_empty(), + &profile.principal_claim, + writes, + writes_membership, + &profile.row_boundaries, + has_membership, + &location, + errors, + ); + if !has_membership { + continue; + } + if profile.operations.contains(&Operation::Import) { + errors.push(Diagnostic::error( + "breg.access.membership-import-unsupported", + &location, + "Import grants cannot use a membership entry in rowBoundaries.", + )); + } if profile.operations.iter().any(|operation| { !matches!( operation, @@ -30,112 +64,36 @@ pub(crate) fn validate(entities: &BTreeMap, errors: &mut V | Operation::List | Operation::Revisions | Operation::Snapshot + | Operation::Create + | Operation::Patch + | Operation::Tombstone + | Operation::Batch + | Operation::Import ) - }) || !profile.writable_fields.is_empty() + }) || (!profile.writable_fields.is_empty() + && !writes + && !profile.operations.contains(&Operation::Import)) { - errors.push(Diagnostic::error("breg.access.membership-read-only", &location, - "membership boundaries support get, lookup, list, revisions and snapshot only; use a separate directly authorized profile for writes and proposal application")); + refuse_membership_write(&location, errors); } if profile.spatial_queries.is_some() { errors.push(Diagnostic::error("breg.access.membership-spatial-unsupported", &location, "spatial bbox uses a separate database authority role; use a directly authorized bbox profile or ordinary membership-filtered reads")); } - if profile.membership_boundaries.len() > 8 { - errors.push(Diagnostic::error( - "breg.access.membership-limit", - &location, - "declare at most eight one-hop membership boundaries", - )); - } - for (index, boundary) in profile.membership_boundaries.iter().enumerate() { - let path = format!("{location}[{index}]"); - if profile.membership_boundaries[..index].contains(boundary) { - errors.push(Diagnostic::error( - "breg.access.membership-duplicate", - &path, - "each membership boundary must be unique", - )); - } - let Some(membership) = entities.get(&boundary.membership_entity) else { - errors.push(Diagnostic::error( - "breg.access.membership-entity-unknown", - &path, - "membershipRecordType must name a governed Record type", - )); - continue; - }; - let root_field = entity - .fields - .iter() - .find(|field| field.id == boundary.field); - let key_field = membership - .fields - .iter() - .find(|field| field.id == boundary.membership_key_field); - let matching = match (root_field, key_field) { - (Some(root), Some(key)) => matches!((&root.field_type, &key.field_type), - (FieldTypeSource::Reference { target: a, .. }, FieldTypeSource::Reference { target: b, .. }) if a == b), - _ => false, - }; - if !matching { - errors.push(Diagnostic::error( - "breg.access.membership-key-type", - &path, - "field and membershipKeyField must be stored references to the same entity", - )); - } - if !membership.fields.iter().any(|field| { - field.id == boundary.principal_field - && matches!( - field.field_type, - FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } - ) - }) { - errors.push(Diagnostic::error("breg.access.membership-principal-type", &path, - "principalField must be a stored string or text field matching the verified principal")); - } - // The membership predicate compares the principal column to the - // verified plaintext principal, so ciphertext can never match. - if membership - .fields - .iter() - .any(|field| field.id == boundary.principal_field && field.encrypted) - { - errors.push(Diagnostic::error("breg.access.membership-principal-encrypted", &path, - "principalField must be a plaintext stored field; an encrypted field cannot match the verified principal")); - } - if !membership.fields.iter().any(|field| { - field.id == boundary.active_field - && matches!(field.field_type, FieldTypeSource::Boolean) - }) { - errors.push(Diagnostic::error("breg.access.membership-active-type", &path, - "activeField must be a stored Boolean field; only true memberships authorize access")); - } - // A membership source is a leaf authorization fact. Its own RLS must - // never traverse back into the protected root, even through an OR arm. - if membership.id == entity.id - || membership - .access_profiles - .iter() - .any(|candidate| !candidate.membership_boundaries.is_empty()) - || entities.values().any(|candidate| { - candidate - .read_paths - .iter() - .any(|path| path.through == membership.id || path.to == membership.id) - }) - { - errors.push(Diagnostic::error("breg.access.membership-source-recursive", &path, - "membership sources must be ordinary leaf entities without membership boundaries or incoming read paths; use a separate membership fact entity")); - } - if let Some(requirements) = &membership.access_requirements { - let mut processing = requirements.clone(); - processing.row_boundaries.clear(); - crate::access::check_profile(&processing, profile, &path, errors); - if !requirements.row_boundaries.is_empty() { - errors.push(Diagnostic::error("breg.access.membership-source-row-requirement", &path, - "membership source row requirements cannot be inferred from a root profile; use its mandatory scopes and purposes with the fixed principal membership predicate")); - } + let entries = profile + .membership_boundaries + .iter() + .map(MembershipBoundarySource::entry) + .collect::>(); + for source in validate_entries(entity, &entries, entities, &location, errors) { + if let Some(requirements) = &source.access_requirements { + crate::access::check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + &location, + errors, + ); } } } @@ -158,53 +116,495 @@ pub(crate) fn validate(entities: &BTreeMap, errors: &mut V } } } + validate_target_entries(project, actions, entities, errors); } -pub(crate) fn compile(entities: &mut BTreeMap) { - let resolved = entities +fn validate_declaration( + entity: &EntitySource, + entities: &BTreeMap, + errors: &mut Vec, +) { + let Some(declaration) = &entity.membership else { + return; + }; + let location = format!("recordTypes[id={}].membership", entity.id); + let field = |id: &str| entity.fields.iter().find(|field| field.id == id); + if !field(&declaration.key) + .is_some_and(|field| matches!(field.field_type, FieldTypeSource::Reference { .. })) + { + errors.push(Diagnostic::error( + "breg.access.membership-key-type", + &location, + &format!( + "membership.key must name a stored reference field, found {}", + declaration.key + ), + )); + } + let principal = field(&declaration.principal); + if !principal.is_some_and(|field| { + matches!( + field.field_type, + FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } + ) + }) { + errors.push(Diagnostic::error( + "breg.access.membership-principal-type", + &location, + &format!( + "membership.principal must name a stored string or text field, found {}", + declaration.principal + ), + )); + } + // The membership predicate compares the principal column to the + // verified plaintext principal, so ciphertext can never match. + if principal.is_some_and(|field| field.encrypted) { + errors.push(Diagnostic::error( + "breg.access.membership-principal-encrypted", + &location, + &format!( + "membership.principal must name a plaintext stored field, found encrypted field {}", + declaration.principal + ), + )); + } + if !field(&declaration.active) + .is_some_and(|field| matches!(field.field_type, FieldTypeSource::Boolean)) + { + errors.push(Diagnostic::error( + "breg.access.membership-active-type", + &location, + &format!( + "membership.active must name a stored Boolean field, found {}", + declaration.active + ), + )); + } + // A membership source is a leaf authorization fact. Its own RLS must + // never traverse back into the protected root, even through an OR arm. + if entity + .access_profiles .iter() - .map(|(id, entity)| { - let profiles = entity - .access_profiles + .any(|profile| !profile.membership_boundaries.is_empty()) + || entities.values().any(|candidate| { + candidate + .read_paths .iter() - .filter_map(|(profile_id, profile)| { - if profile.membership_boundaries.is_empty() { - return None; - } - let boundaries = profile - .membership_boundaries - .iter() - .map(|boundary| { - let source = &entities[&boundary.membership_entity]; - CompiledMembershipBoundary { - field: boundary.field.clone(), - membership_entity: source.id.clone(), - membership_table: source.physical_table.clone(), - membership_key_column: source.fields - [&boundary.membership_key_field] - .physical_name - .clone(), - principal_column: source.fields[&boundary.principal_field] - .physical_name - .clone(), - active_column: source.fields[&boundary.active_field] - .physical_name - .clone(), - } - }) - .collect(); - Some((profile_id.clone(), boundaries)) + .any(|path| path.through == entity.id || path.to == entity.id) + }) + { + refuse_recursive(&location, errors); + } + if entity + .access_requirements + .as_ref() + .is_some_and(|requirements| !requirements.row_boundaries.is_empty()) + { + errors.push(Diagnostic::error("breg.access.membership-source-row-requirement", &location, + "Use mandatory scopes and purposes on the membership Record type. The membership predicate provides its row restriction.")); + } +} + +fn refuse_recursive(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.membership-source-recursive", + location, + "A Record type declaring membership must have no membership row boundaries or incoming read paths.", + )); +} + +fn validate_entries<'a>( + entity: &EntitySource, + entries: &[MembershipRowBoundarySource], + entities: &'a BTreeMap, + location: &str, + errors: &mut Vec, +) -> Vec<&'a EntitySource> { + if entries.len() > 8 { + errors.push(Diagnostic::error( + "breg.access.membership-limit", + location, + "declare at most eight one-hop membership boundaries", + )); + } + let mut sources = Vec::new(); + for (index, entry) in entries.iter().enumerate() { + let site = format!( + "{location}[membership={}:field={}]", + entry.membership, entry.field + ); + if entries[..index].contains(entry) { + errors.push(Diagnostic::error( + "breg.access.membership-duplicate", + &site, + "each membership boundary must be unique", + )); + } + let Some((source, declaration)) = entities.get(&entry.membership).and_then(|source| { + source + .membership + .as_ref() + .map(|declaration| (source, declaration)) + }) else { + errors.push(Diagnostic::error( + "breg.access.membership-entity-unknown", + &site, + &format!( + "membership must name a Record type with a membership declaration, found {}", + entry.membership + ), + )); + continue; + }; + let root = entity.fields.iter().find(|field| field.id == entry.field); + let key = source + .fields + .iter() + .find(|field| field.id == declaration.key); + if let Some(key) = + key.filter(|key| matches!(key.field_type, FieldTypeSource::Reference { .. })) + { + if !root.is_some_and(|root| matches!( + (&root.field_type, &key.field_type), + (FieldTypeSource::Reference { target: a, .. }, FieldTypeSource::Reference { target: b, .. }) if a == b + )) { + errors.push(Diagnostic::error( + "breg.access.membership-key-type", + &site, + &format!("field {} and membership.key {} must be stored references to the same Record type", entry.field, declaration.key), + )); + } + } + sources.push(source); + } + sources +} + +fn validate_target_entries( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { + let hook_principals = entities + .values() + .flat_map(|entity| { + entity + .hooks + .iter() + .filter_map(|hook| hook.principal.as_deref()) + }) + .collect::>(); + let timer_actions = entities + .values() + .flat_map(|entity| entity.timers.iter().map(|timer| timer.invoke.as_str())) + .collect::>(); + for profile in &project.access_profiles { + let targets = profile + .permissions + .actions + .iter() + .flat_map(|grant| { + grant.targets.iter().map(move |target| { + ( + "actions", + grant.action.as_str(), + target.entity.as_str(), + &target.membership_row_boundaries, + &target.row_boundaries, + true, + ) + }) + }) + .chain(profile.permissions.proposals.iter().flat_map(|grant| { + grant.targets.iter().map(move |target| { + ( + "proposals", + grant.action.as_str(), + target.record_type.as_str(), + &target.membership_row_boundaries, + &target.row_boundaries, + grant.operations.iter().copied().any(is_proposal_write), + ) }) - .collect(); - (id.clone(), profiles) + })); + for (surface, action, id, entries, rows, write_grant) in targets { + // Invalid references receive the ordinary target diagnostics without + // embedding authored scalar values in admission paths. + if registry_platform_yaml::LocalId::new(action).is_err() + || registry_platform_yaml::LocalId::new(id).is_err() + { + continue; + } + let location = format!("accessProfiles[id={}].permissions.{surface}[action={action}].targets[recordType={id}].rowBoundaries", profile.id); + let declares_membership = entities + .get(id) + .is_some_and(|entity| entity.membership.is_some()); + let writes_membership = write_grant + && declares_membership + && actions + .get(action) + .is_some_and(|action| plan_writes(&action.source, id)); + validate_write_admission( + profile.required_scopes.is_empty(), + profile.requester_clients.is_empty(), + &profile.principal_claim, + write_grant, + writes_membership, + rows, + !entries.is_empty(), + &location, + errors, + ); + if entries.is_empty() { + continue; + } + if declares_membership { + refuse_recursive(&format!("recordTypes[id={id}].membership"), errors); + } + if surface == "actions" && hook_principals.contains(profile.id.as_str()) { + errors.push(Diagnostic::error( + "breg.access.membership-hook-unsupported", + &location, + "A grant used by a hook cannot use a membership entry in rowBoundaries.", + )); + } + if timer_actions.contains(action) { + errors.push(Diagnostic::error( + "breg.access.membership-timer-unsupported", + &location, + "A grant used by a timer cannot use a membership entry in rowBoundaries.", + )); + } + if let Some(entity) = entities.get(id) { + for source in validate_entries(entity, entries, entities, &location, errors) { + if let Some(requirements) = &source.access_requirements { + crate::access::check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + &location, + errors, + ); + } + } + } + } + } +} + +pub(crate) fn is_proposal_write(operation: ProposalOperation) -> bool { + match operation { + ProposalOperation::Answer + | ProposalOperation::Edit + | ProposalOperation::Add + | ProposalOperation::Submit + | ProposalOperation::Revise + | ProposalOperation::Cancel + | ProposalOperation::Apply + | ProposalOperation::Rebase + | ProposalOperation::Retry => true, + ProposalOperation::Get + | ProposalOperation::List + | ProposalOperation::GetReviewStatus + | ProposalOperation::GetReviewContext + | ProposalOperation::GetTaskGrantContext + | ProposalOperation::GetApplicationActor => false, + } +} + +fn plan_writes(action: &ActionSource, entity: &str) -> bool { + let writes = |target: &crate::contract::ActionTargetSource, operation| { + is_record_write(operation) && match (&target.entity, &target.from_field) { + (Some(record_type), None) => record_type == entity, + (None, Some(input)) => action.inputs.iter().any(|candidate| { + candidate.id == *input && matches!( + &candidate.field_type, FieldTypeSource::Reference { target, .. } if target == entity + ) + }), + _ => false, + } + }; + match &action.plan { + ActionPlanSource::Fixed { effects } => effects + .iter() + .any(|effect| writes(&effect.target, effect.operation)), + ActionPlanSource::Function { + writes: ceilings, .. + } => ceilings + .iter() + .any(|ceiling| writes(&ceiling.target, ceiling.operation)), + } +} + +pub(crate) fn is_record_write(operation: Operation) -> bool { + matches!( + operation, + Operation::Create | Operation::Patch | Operation::Tombstone + ) +} + +fn refuse_open_membership_principal(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.open-membership-principal-not-sub", + location, + "An open profile with a membership entry must set principalClaim to sub.", + )); +} + +#[allow(clippy::too_many_arguments)] +pub(crate) fn validate_write_admission( + scopeless: bool, + unrestricted_clients: bool, + principal_claim: &str, + writes: bool, + writes_membership: bool, + row_boundaries: &[RowBoundarySource], + has_membership: bool, + location: &str, + errors: &mut Vec, +) { + let open = scopeless && unrestricted_clients; + if open && has_membership && principal_claim != "sub" { + refuse_open_membership_principal(location, errors); + } + if open + && writes + && !has_membership + && !row_boundaries + .iter() + .any(|row| row.claim == principal_claim) + { + errors.push(Diagnostic::error( + "breg.access.open-write-without-principal-boundary", + location, + "An open profile must bound each write target with a membership entry or a row boundary on its principalClaim.", + )); + } + if scopeless && writes_membership { + errors.push(Diagnostic::error( + "breg.access.scopeless-membership-source-write", + location, + "A profile that admits tokens without scopes cannot write a Record type that declares membership.", + )); + } +} + +pub(crate) fn refuse_membership_write(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.membership-read-only", + location, + "Membership entries cannot authorize this operation. Use a separately authorized profile.", + )); +} + +pub(crate) fn resolve_entry( + entry: &MembershipRowBoundarySource, + entities: &BTreeMap, + location: &str, +) -> Result<(CompiledMembershipBoundary, ExpandedMembershipBoundarySource), Diagnostic> { + let source = entities + .get(&entry.membership) + .and_then(|source| { + source + .membership + .as_ref() + .map(|declaration| (source, declaration)) }) - .collect::>(); - for (id, boundaries) in resolved { - entities - .get_mut(&id) - .expect("compiled entity") - .membership_boundaries = boundaries; + .ok_or_else(|| { + Diagnostic::error( + "breg.access.membership-entity-unknown", + location, + &format!( + "membership must name a Record type with a membership declaration, found {}", + entry.membership + ), + ) + })?; + let (source, declaration) = source; + let column = |name: &str, field: &str, code| { + source + .fields + .get(field) + .map(|field| field.physical_name.clone()) + .ok_or_else(|| { + Diagnostic::error( + code, + location, + &format!("membership.{name} names missing field {field}"), + ) + }) + }; + Ok(( + CompiledMembershipBoundary { + field: entry.field.clone(), + membership_entity: source.id.clone(), + membership_table: source.physical_table.clone(), + membership_key_column: column( + "key", + &declaration.key, + "breg.access.membership-key-type", + )?, + principal_column: column( + "principal", + &declaration.principal, + "breg.access.membership-principal-type", + )?, + active_column: column( + "active", + &declaration.active, + "breg.access.membership-active-type", + )?, + }, + ExpandedMembershipBoundarySource { + field: entry.field.clone(), + membership_entity: source.id.clone(), + membership_key_field: declaration.key.clone(), + principal_field: declaration.principal.clone(), + active_field: declaration.active.clone(), + }, + )) +} + +pub(crate) fn compile( + entities: &mut BTreeMap, +) -> Result<(), Vec> { + let mut resolved = Vec::new(); + let mut errors = Vec::new(); + for (id, entity) in entities.iter() { + for (profile_id, profile) in &entity.access_profiles { + if profile.membership_boundaries.is_empty() { + continue; + } + let location = + format!("recordTypes[id={id}].accessProfiles[id={profile_id}].rowBoundaries"); + let mut physical = Vec::new(); + let mut logical = Vec::new(); + for boundary in &profile.membership_boundaries { + match resolve_entry(&boundary.entry(), entities, &location) { + Ok((boundary, expanded)) => { + physical.push(boundary); + logical.push(MembershipBoundarySource::Expanded(expanded)); + } + Err(error) => errors.push(error), + } + } + resolved.push((id.clone(), profile_id.clone(), physical, logical)); + } + } + if !errors.is_empty() { + return Err(errors); } + for (id, profile_id, physical, logical) in resolved { + if let Some(entity) = entities.get_mut(&id) { + if let Some(profile) = entity.access_profiles.get_mut(&profile_id) { + profile.membership_boundaries = logical; + entity.membership_boundaries.insert(profile_id, physical); + } + } + } + Ok(()) } pub(crate) fn boundaries<'a>( @@ -313,10 +713,208 @@ pub(crate) fn source_predicate(boundary: &CompiledMembershipBoundary, alias: &st ) } -pub(crate) fn source_guard(entity: &str, profile: &str, index: usize) -> String { +pub(crate) fn source_guard(name: &str, profile: &str) -> String { format!( "NULLIF(current_setting('registry.membership_probe', true), '') = {} AND NULLIF(current_setting('registry.access_profile', true), '') = {}", - quote_literal(&function_name(entity, profile, index)), + quote_literal(name), quote_literal(profile) ) } + +pub(crate) fn target_function_name(profile: &str, source: &str) -> String { + scoped_function_name("membership_target", profile, source) +} + +fn scoped_function_name(namespace: &str, profile: &str, source: &str) -> String { + let mut hash = Sha256::new(); + hash.update(format!("breg/{namespace}/v1")); + for part in [profile, source] { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + format!("{namespace}_{}", hex_prefix(&hash.finalize(), 12)) +} + +pub(super) struct MembershipProbe<'a> { + pub name: String, + pub profile: &'a str, + pub boundary: &'a CompiledMembershipBoundary, + pub locks: bool, +} + +pub(super) fn probes<'a>( + entities: &'a BTreeMap, + actions: &'a CompiledActionInventory, +) -> Vec> { + let mut probes = Vec::new(); + for entity in entities.values() { + for (profile, boundaries) in &entity.membership_boundaries { + for (index, boundary) in boundaries.iter().enumerate() { + probes.push(MembershipProbe { + name: function_name(&entity.id, profile, index), + profile, + boundary, + locks: false, + }); + } + } + } + + let mut targets = BTreeSet::new(); + for (profile, boundary, _) in target_boundaries(actions) { + if targets.insert((profile, boundary.membership_entity.as_str())) { + probes.push(MembershipProbe { + name: target_function_name(profile, &boundary.membership_entity), + profile, + boundary, + locks: false, + }); + } + } + probes.extend( + lockable_membership_tables(entities, actions) + .into_iter() + .map(|((profile, source), boundary)| MembershipProbe { + name: lock_function_name(profile, source), + profile, + boundary, + locks: true, + }), + ); + probes +} + +fn target_boundaries( + actions: &CompiledActionInventory, +) -> impl Iterator { + actions.actions.iter().flat_map(|action| { + let action_operation = if action.execution.is_proposal() { + Operation::Start + } else { + Operation::Invoke + }; + let action_targets = action + .permissions + .iter() + .filter(move |grant| grant.operations.contains(&action_operation)) + .flat_map(move |grant| { + grant.entity_target_locks().flat_map(move |target| { + target.membership_boundaries.iter().map(move |boundary| { + ( + grant.profile_id.as_str(), + boundary, + action_operation == Operation::Invoke, + ) + }) + }) + }); + let proposal_targets = match &action.execution { + CompiledActionExecution::Proposal { proposal } => proposal.permissions.as_slice(), + CompiledActionExecution::Immediate => &[], + }; + action_targets.chain(proposal_targets.iter().flat_map(move |grant| { + // Caller Apply also includes an authorized external recovery actor. + let locks = grant.operations.contains(&ProposalOperation::Apply); + grant.targets.iter().flat_map(move |target| { + target + .membership_boundaries + .iter() + .map(move |boundary| (grant.profile_id.as_str(), boundary, locks)) + }) + })) + }) +} + +pub(crate) fn lock_function_name(profile: &str, source: &str) -> String { + scoped_function_name("membership_lock", profile, source) +} + +/// The membership sources write authority can lock, by access profile and Record type. +pub(crate) fn lockable_membership_tables<'a>( + entities: &'a BTreeMap, + actions: &'a CompiledActionInventory, +) -> BTreeMap<(&'a str, &'a str), &'a CompiledMembershipBoundary> { + let mut tables = BTreeMap::new(); + for entity in entities.values() { + for (profile, boundaries) in &entity.membership_boundaries { + if entity.access_profiles[profile] + .operations + .iter() + .any(|operation| { + matches!( + operation, + Operation::Create + | Operation::Patch + | Operation::Tombstone + | Operation::Batch + ) + }) + { + for boundary in boundaries { + tables.insert( + (profile.as_str(), boundary.membership_entity.as_str()), + boundary, + ); + } + } + } + } + for (profile, boundary, locks) in target_boundaries(actions) { + if locks { + tables.insert((profile, boundary.membership_entity.as_str()), boundary); + } + } + tables +} + +pub(super) fn append_target_probes( + entity: &CompiledEntity, + profile: &str, + boundaries: &[CompiledMembershipBoundary], + policies: &mut [crate::generated_ddl::DdlPolicy], +) { + if boundaries.is_empty() { + return; + } + let predicate = boundaries + .iter() + .map(|boundary| { + format!( + "registry_context.{}({})", + quote_identifier(&target_function_name(profile, &boundary.membership_entity)), + quote_identifier(&entity.fields[&boundary.field].physical_name) + ) + }) + .collect::>() + .join(" AND "); + for policy in policies { + for expression in policy.using_expression.iter_mut().chain( + policy + .check_expression + .iter_mut() + .filter(|check| *check != "false"), + ) { + *expression = format!("({expression}) AND {predicate}"); + } + } +} + +pub(crate) fn index_statement(entity: &CompiledEntity) -> Option<(String, String, String)> { + let declaration = entity.membership.as_ref()?; + let column = |field: &str| quote_identifier(&entity.fields[field].physical_name); + let digest = Sha256::digest(format!("breg/membership-index/v1/{}/key", entity.id).as_bytes()); + let name = format!("breg_membership_key_{}", hex_prefix(&digest, 5)); + let sql = format!( + "CREATE INDEX {} ON registry_data.{} ({}, {}) WHERE {} IS TRUE AND record_lifecycle = 'active'", + quote_identifier(&name), + quote_identifier(&entity.physical_table), + column(&declaration.key), + column(&declaration.principal), + column(&declaration.active) + ); + Some(( + format!("entity.{}.membership.key-index", entity.id), + name, + sql, + )) +} diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index 284262e5fe..749941108a 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -638,6 +638,8 @@ pub struct CompiledProposalTargetPermission { #[serde(rename = "recordType")] pub entity_id: String, pub row_boundaries: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub membership_boundaries: Vec, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -879,6 +881,8 @@ pub struct CompiledActionTargetPermission { /// The effect or input that identifies this action target use. pub source: CompiledActionTargetUseSource, pub row_boundaries: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub membership_boundaries: Vec, } impl CompiledActionPermission { @@ -1090,6 +1094,8 @@ pub struct CompiledEntity { #[serde(default, skip_serializing_if = "Option::is_none")] pub access_requirements: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub membership: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub access_log: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub geojson: Option, diff --git a/crates/registry-breg/src/mutation.rs b/crates/registry-breg/src/mutation.rs index d75af96ea7..258c15e1ee 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -7,6 +7,9 @@ mod action; pub(crate) use action::erase_expired_action_evidence; pub(crate) use action::validate_action_attachments; pub(crate) use action::{HookChangeApplication, HookChangeOutcome}; +mod membership; +pub(crate) use membership::probe_action_memberships; +use membership::RecordMembership; mod proposal; pub(crate) use proposal::{ link_readable, proposal_http_method, proposal_operation_name, CheckedProposalTaskAuthority, @@ -90,7 +93,7 @@ use crate::outbox::{ }; use crate::postgres::external_refresh_queue::{capture_local_records, LocalRecordCapture}; use crate::postgres::{ - begin_action_transaction, begin_record_transaction, begin_timer_action_transaction, + begin_action_transaction, begin_record_transaction_for_write, begin_timer_action_transaction, ActionClaimContext, ClaimContext, ExpectedRegistryIdentity, ImmediateActionLinkBinding, ImmediateActionLinkContext, ImmediateActionTargetBinding, ImmediateActionTargetContext, RegistryLockKey, RowBoundaryContext, SqlIdentifier, @@ -1022,7 +1025,18 @@ impl MutationTransaction { return Err(error); } let _attempt = self.begin_boundary_audit(&request).await?; - let result = self.execute_after_attempt(client, &request, fault).await; + let mut retries = 0; + let result = loop { + let result = self.execute_after_attempt(client, &request, fault).await; + if matches!(result, Err(MutationError::MembershipKeyDrift)) + && retries < 2 + && !fault.is_enabled() + { + retries += 1; + continue; + } + break result; + }; if failure_is_refusal(&result) && !fault.is_enabled() { self.record_boundary_audit(&request, PreIoAuditKind::Refusal) .await?; @@ -1030,9 +1044,9 @@ impl MutationTransaction { // The retry distinction belongs to request actions. Ordinary mutations // retain their existing public failure for aborted SQL transactions. result.map_err(|error| match error { - MutationError::RetryableConflict | MutationError::CommitUnresolved => { - MutationError::Unavailable - } + MutationError::MembershipKeyDrift + | MutationError::RetryableConflict + | MutationError::CommitUnresolved => MutationError::Unavailable, other => other, }) } @@ -1081,17 +1095,28 @@ impl MutationTransaction { return Err(error); } let _attempt = self.begin_batch_boundary_audit(&request).await?; - let result = self - .execute_batch_after_attempt(client, &request, fault) - .await; + let mut retries = 0; + let result = loop { + let result = self + .execute_batch_after_attempt(client, &request, fault) + .await; + if matches!(result, Err(MutationError::MembershipKeyDrift)) + && retries < 2 + && !fault.is_enabled() + { + retries += 1; + continue; + } + break result; + }; if failure_is_refusal(&result) && !fault.is_enabled() { self.record_batch_boundary_audit(&request, PreIoAuditKind::Refusal) .await?; } result.map_err(|error| match error { - MutationError::RetryableConflict | MutationError::CommitUnresolved => { - MutationError::Unavailable - } + MutationError::MembershipKeyDrift + | MutationError::RetryableConflict + | MutationError::CommitUnresolved => MutationError::Unavailable, other => other, }) } @@ -1206,12 +1231,14 @@ impl MutationTransaction { key_domain: IdempotencyKeyDomain::Caller, }, )?; - let transaction = begin_record_transaction( + let transaction = begin_record_transaction_for_write( client, self.lock_key, self.lock_timeout, &self.expected, request.claims, + !crate::membership::boundaries(&request.plan.entity, request.claims.access_profile()) + .is_empty(), ) .await .map_err(|_| MutationError::Unavailable)?; @@ -1283,6 +1310,13 @@ impl MutationTransaction { if request.claims.task_grant().is_some() { return Err(MutationError::PreconditionFailed); } + let membership = RecordMembership::prepare( + transaction.transaction(), + &request.plan.entity, + request.claims.access_profile(), + std::iter::once((request.record_id, request.body.clone())), + ) + .await?; fault.fail_at(MutationFaultPoint::BeforeCurrentRow)?; let current = apply_current_row( transaction.transaction(), @@ -1290,6 +1324,7 @@ impl MutationTransaction { self.audit.profile(), &self.expected.activation_id, self.field_encryption.as_deref(), + membership.as_ref(), ) .await?; stage_record_timer_rows( @@ -1547,12 +1582,14 @@ impl MutationTransaction { }, }, )?; - let transaction = begin_record_transaction( + let transaction = begin_record_transaction_for_write( client, self.lock_key, self.lock_timeout, &self.expected, request.claims, + !crate::membership::boundaries(&request.plan.entity, request.claims.access_profile()) + .is_empty(), ) .await .map_err(|_| MutationError::Unavailable)?; @@ -1885,7 +1922,17 @@ impl MutationTransaction { }); } - prelock_batch_current_rows(transaction.transaction(), request).await?; + let mut membership = RecordMembership::prepare( + transaction.transaction(), + &request.plan.entity, + request.claims.access_profile(), + request.items.iter().map(|item| { + let (id, _, body) = item.request_parts(); + (id, body) + }), + ) + .await?; + prelock_batch_current_rows(transaction.transaction(), request, membership.as_ref()).await?; set_temporal_exclusion_constraints( transaction.transaction(), @@ -1920,8 +1967,12 @@ impl MutationTransaction { self.audit.profile(), &self.expected.activation_id, self.field_encryption.as_deref(), + membership.as_ref(), ) .await?; + if let Some(membership) = &mut membership { + membership.record_batch_write(¤t); + } let record_reference = record_reference( self.audit.profile(), &self.expected.activation_id, @@ -2448,8 +2499,14 @@ pub enum MutationError { /// stale-condition failures, which remain generic precondition refusals. #[error("the resulting record is outside the selected access profile's row boundary")] WriteOutsideBoundary, + #[error("the resulting record is outside the selected access profile's row boundary")] + MembershipWriteOutsideBoundary, #[error("mutation precondition failed")] PreconditionFailed, + #[error("mutation precondition failed")] + MembershipPreconditionFailed, + #[error("a target key changed before the mutation locked the target")] + MembershipKeyDrift, /// An admitted frozen application found a changed target. It keeps the /// ordinary precondition problem, but records Rebase as its recovery. #[error("mutation precondition failed")] @@ -2560,6 +2617,7 @@ impl MutationError { match self { Self::AuthorizationRefused(check) => Some(*check), Self::WriteOutsideBoundary => Some(FailedCheck::RowBoundary), + Self::MembershipWriteOutsideBoundary => Some(FailedCheck::Membership), Self::FieldGuardFailed { .. } | Self::ProposalGuardFailed(_) => { Some(FailedCheck::ActionGuard) } @@ -2567,6 +2625,8 @@ impl MutationError { | Self::InvalidRequestAt(_) | Self::InvalidTimerWindow { .. } | Self::PreconditionFailed + | Self::MembershipPreconditionFailed + | Self::MembershipKeyDrift | Self::ProposalTargetChanged | Self::ProposalReviewResultMismatch | Self::Conflict @@ -2917,13 +2977,14 @@ pub(super) async fn capture_external_refresh_rows( Ok(()) } -/// Acquire every existing batch target in canonical UUID order before the +/// Acquire every admitted existing batch target in canonical UUID order before the /// first row is changed. Timer staging takes its shared control lock first, /// so ordinary writers and workers cannot invert control, Record, and /// generation locks when callers submit the same targets in different order. async fn prelock_batch_current_rows( transaction: &Transaction<'_>, request: &BatchMutationRequest<'_>, + membership: Option<&RecordMembership<'_>>, ) -> Result<(), MutationError> { let mut record_ids = BTreeSet::new(); for item in &request.items { @@ -2935,6 +2996,11 @@ async fn prelock_batch_current_rows( if !valid_uuid(record_id) { return Err(MutationError::InvalidRequest); } + if membership + .is_some_and(|membership| membership.authorize_existing(Some(record_id)).is_err()) + { + continue; + } record_ids.insert(Uuid::parse_str(record_id).map_err(|_| MutationError::InvalidRequest)?); } if record_ids.is_empty() { @@ -2964,6 +3030,7 @@ async fn apply_current_row( audit_profile: &AuditProfile, package_revision: &str, field_encryption: Option<&FieldEncryptionService>, + membership: Option<&RecordMembership<'_>>, ) -> Result { if request .plan @@ -2986,6 +3053,18 @@ async fn apply_current_row( return Err(MutationError::InvalidRequest); }; let mut data = data.clone(); + if let Some(membership) = membership { + membership.authorize_proposed(&data)?; + match request.claims.authorizes_record_snapshot_before_allocation( + &request.plan.entity, + &data, + record_uuid, + ) { + Ok(true) => {} + Ok(false) => return Err(MutationError::WriteOutsideBoundary), + Err(_) => return Err(MutationError::Unavailable), + } + } crate::generated_identifiers::reserve_for_create( transaction, &request.plan.entity, @@ -3014,6 +3093,9 @@ async fn apply_current_row( Ok(row) } Operation::Patch => { + if let Some(membership) = membership { + membership.authorize_existing(request.record_id)?; + } let current = load_current_row_for_update(transaction, request).await?; let expected = request .expected_etag @@ -3031,8 +3113,12 @@ async fn apply_current_row( if expected.ct_eq(current_etag.as_bytes()).unwrap_u8() != 1 { return Err(MutationError::PreconditionFailed); } + if let Some(membership) = membership { + membership.verify_locked(¤t)?; + } let before_data = current.data.clone(); - let data = apply_patch_document(transaction, request, ¤t.data).await?; + let data = + apply_patch_document(transaction, request, ¤t.data, membership).await?; let mut admitted_intake = current.data.clone(); admitted_intake.extend(data.clone()); authorize_record_snapshot(request, &admitted_intake, current.record_uuid)?; @@ -3050,6 +3136,9 @@ async fn apply_current_row( Ok(row) } Operation::Tombstone => { + if let Some(membership) = membership { + membership.authorize_existing(request.record_id)?; + } let current = load_tombstone_row_for_update(transaction, request).await?; let expected = request .expected_etag @@ -3067,6 +3156,9 @@ async fn apply_current_row( if expected.ct_eq(current_etag.as_bytes()).unwrap_u8() != 1 { return Err(MutationError::PreconditionFailed); } + if let Some(membership) = membership { + membership.verify_locked(¤t)?; + } match crate::disclosure::plan(&request.plan.entity, request.claims.access_profile()) .refuses_tombstone(¤t.data) { @@ -3136,13 +3228,13 @@ async fn apply_patch_row( ) -> Result { let record_id = request.record_id.ok_or(MutationError::InvalidRequest)?; let profile = selected_profile(request)?; + let disclosure = crate::disclosure::plan(&request.plan.entity, request.claims.access_profile()); + check_update_disclosure(&disclosure, before, &data)?; update_current_row( transaction, &request.plan.entity, - request.claims.access_profile(), record_id, expected_revision, - before, data, field_encryption, Some(ConstraintDisclosure::DeclaredFields { @@ -3188,21 +3280,12 @@ pub(super) async fn write_plan_row( ) .await?; } - // A state a `record` condition withholds from the writer is outside its - // boundary, as for a Patch or a Create, before the restrictive row policy - // can refuse it. A state that cannot be evaluated counts as withheld. - let mut after = before.cloned().unwrap_or_default(); - after.extend( - fields - .iter() - .map(|(field, value)| (field.clone(), value.clone())), - ); - if crate::disclosure::plan(entity, writer) - .withholds_record(&after) - .unwrap_or(true) - { + let disclosure = crate::disclosure::plan(entity, writer); + let PlanWriteDisclosure::RecordVisible { update } = + plan_write_disclosure(&disclosure, before, &fields) + else { return Err(MutationError::WriteOutsideBoundary); - } + }; let record_id = record_uuid.to_string(); let mut current = match expected_revision { None => { @@ -3225,19 +3308,15 @@ pub(super) async fn write_plan_row( .await? } Some(revision) => { - let Some(before) = before else { - return Err(MutationError::InvalidRequest); - }; - if revision < 1 { + if before.is_none() || revision < 1 { return Err(MutationError::InvalidRequest); } + update?; update_current_row( transaction, entity, - writer, &record_id, revision, - before, fields, field_encryption, origin.constraint_disclosure(), @@ -3250,6 +3329,51 @@ pub(super) async fn write_plan_row( Ok(current) } +enum PlanWriteDisclosure { + RecordWithheld, + RecordVisible { update: Result<(), MutationError> }, +} + +fn plan_write_disclosure( + disclosure: &crate::disclosure::DisclosurePlan<'_>, + before: Option<&Map>, + fields: &Map, +) -> PlanWriteDisclosure { + if disclosure.is_empty() { + return PlanWriteDisclosure::RecordVisible { update: Ok(()) }; + } + // A `record` condition withholds the resulting state before the + // restrictive row policy can refuse it. An unevaluable state is withheld. + let mut after = before.cloned().unwrap_or_default(); + after.extend( + fields + .iter() + .map(|(field, value)| (field.clone(), value.clone())), + ); + if disclosure.withholds_record(&after).unwrap_or(true) { + return PlanWriteDisclosure::RecordWithheld; + } + PlanWriteDisclosure::RecordVisible { + update: before.map_or(Ok(()), |before| { + check_update_disclosure(disclosure, before, fields) + }), + } +} + +/// Refuse lifting a disclosure mark or writing a withheld field before +/// persistence can answer with a constraint conflict. +fn check_update_disclosure( + disclosure: &crate::disclosure::DisclosurePlan<'_>, + before: &Map, + data: &Map, +) -> Result<(), MutationError> { + match disclosure.refuses_write(before, data) { + Ok(false) => Ok(()), + Ok(true) => Err(MutationError::WriteOutsideBoundary), + Err(_) => Err(MutationError::Unavailable), + } +} + #[derive(Clone, Copy)] pub(super) enum PlanWriteOrigin { ImmediateAction, @@ -3340,27 +3464,17 @@ async fn insert_current_row( row_to_current(entity, &row) } -/// Write `data` over the current row `before` as the `writer` profile. Every -/// update of an existing record passes here, so a bound writer's attempt to -/// lift a disclosure mark or overwrite a withheld field is refused on each -/// path alike, before the database can answer with a constraint conflict. +/// Persist an update after the caller has checked write disclosure. #[allow(clippy::too_many_arguments)] async fn update_current_row( transaction: &Transaction<'_>, entity: &CompiledEntity, - writer: &str, record_id: &str, expected_revision: i64, - before: &Map, data: Map, field_encryption: Option<&FieldEncryptionService>, constraint_disclosure: Option>, ) -> Result { - match crate::disclosure::plan(entity, writer).refuses_write(before, &data) { - Ok(false) => {} - Ok(true) => return Err(MutationError::WriteOutsideBoundary), - Err(_) => return Err(MutationError::Unavailable), - } let submitted_fields = entity .fields .values() @@ -3764,6 +3878,7 @@ async fn apply_patch_document( transaction: &Transaction<'_>, request: &MutationRequest<'_>, current: &Map, + membership: Option<&RecordMembership<'_>>, ) -> Result, MutationError> { let MutationBody::Patch(operations) = &request.body else { return Err(MutationError::InvalidRequest); @@ -3775,6 +3890,7 @@ async fn apply_patch_document( let mut materialized = current.clone(); let mut changed = Map::new(); let mut mutated = false; + let mut deferred_topology = Vec::new(); for (index, operation) in operations.iter().enumerate() { let at = |member| patch_location(index, member); match operation { @@ -3794,10 +3910,16 @@ async fn apply_patch_document( } written_sql_value(&request.plan.entity, field, value) .map_err(|_| at(PatchMember::Value))?; - validate_polygon_topology(transaction, &field.field_type, value, || { - at(PatchMember::Value) - }) - .await?; + if membership.is_some() + && matches!(field.field_type, FieldTypeSource::Crs84Polygon { .. }) + { + deferred_topology.push((index, &field.field_type, value)); + } else { + validate_polygon_topology(transaction, &field.field_type, value, || { + at(PatchMember::Value) + }) + .await?; + } materialized.insert(field_id.clone(), value.clone()); changed.insert(field_id, value.clone()); mutated = true; @@ -3846,6 +3968,17 @@ async fn apply_patch_document( if !mutated { return Err(MutationError::InvalidRequest); } + if let Some(membership) = membership { + // The patch interpreter has validated the values and run the tests. + // Check its final key before asking PostgreSQL to check topology. + membership.authorize_proposed(&materialized)?; + for (index, field_type, value) in deferred_topology { + validate_polygon_topology(transaction, field_type, value, || { + patch_location(index, PatchMember::Value) + }) + .await?; + } + } Ok(changed) } diff --git a/crates/registry-breg/src/mutation/action.rs b/crates/registry-breg/src/mutation/action.rs index 216bb8761f..95748d961a 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -88,10 +88,21 @@ impl ImmediateActionExecutionOutcome { } } +mod membership; +use membership::ActionMembership; + +#[derive(Clone, Copy, Eq, PartialEq)] +enum TargetRead { + Lock, + MembershipPreRead, + EvidencePreflight, +} + struct LockedActionTargets { guard_failure: Option, rows: BTreeMap<(String, Uuid), CurrentRow>, missing_timer_link: bool, + missing_target: bool, } enum TimerActionPreflight { @@ -270,6 +281,7 @@ impl MutationTransaction { None, Some(authority), &[], + None, ) .await; let definite_refusal = failure_is_refusal(&result) && !fault.is_enabled(); @@ -554,6 +566,7 @@ impl MutationTransaction { pub(crate) async fn execute_immediate_action( &self, client: &mut Client, + pool: &crate::postgres::RuntimePool, registry: &CompiledRegistry, input: ImmediateActionInput<'_>, claims: &ActionClaimContext, @@ -602,8 +615,13 @@ impl MutationTransaction { }, )?; let reserved_creates = reserve_action_create_ids(action)?; - self.stage_action_attachments(client, claims, &attachments, deadline) - .await?; + let staging_pool = if claims.locks_membership() { + Some(pool) + } else { + self.stage_action_attachments(client, claims, &attachments, deadline) + .await?; + None + }; let mut candidate = None; let trusted_now = time::OffsetDateTime::now_utc(); let application_id = Uuid::new_v4(); @@ -632,6 +650,7 @@ impl MutationTransaction { None, None, &attachments, + staging_pool, ) .await; if matches!(attempt, Err(MutationError::RetryableConflict)) @@ -694,20 +713,100 @@ impl MutationTransaction { .set_statement_budget(deadline.saturating_duration_since(tokio::time::Instant::now())) .await .map_err(|_| MutationError::Unavailable)?; + self.stage_attachment_rows(guarded.transaction(), attachments) + .await?; + guarded + .commit() + .await + .map_err(|_| MutationError::Unavailable) + } + + async fn stage_membership_action_attachments( + &self, + pool: &crate::postgres::RuntimePool, + claims: &ActionClaimContext, + attachments: &[ActionRequestAttachment], + deadline: tokio::time::Instant, + ) -> Result<(), MutationError> { + if attachments.is_empty() + || !matches!( + self.attachment_storage, + crate::attachment_storage::AttachmentStorage::S3(_) + ) + { + return Ok(()); + } + // The parent has admitted the package and holds the target and + // membership locks. Holding that package lock across staging also + // avoids joining a queue behind a waiting exclusive activation. + tokio::time::timeout_at(deadline, async { + let mut staging = pool + .attachment_staging_connection() + .await + .map_err(|_| MutationError::Unavailable)?; + let result = async { + let transaction = staging + .client() + .transaction() + .await + .map_err(map_database_error)?; + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + if remaining < Duration::from_millis(1) { + return Err(MutationError::Unavailable); + } + crate::postgres::set_transaction_statement_budget(&transaction, remaining) + .await + .map_err(|_| MutationError::Unavailable)?; + transaction + .execute( + "SELECT set_config('lock_timeout', $1, true), + set_config('registry.principal', $2, true), + set_config('registry.active_package_revision', $3, true)", + &[ + &format!("{}ms", self.lock_timeout.as_millis()), + &claims.principal(), + &self.expected.activation_id, + ], + ) + .await + .map_err(map_database_error)?; + crate::postgres::verify_registry_transaction_identity( + &transaction, + self.lock_key, + &self.expected, + ) + .await + .map_err(|_| MutationError::Unavailable)?; + self.stage_attachment_rows(&transaction, attachments) + .await?; + transaction.commit().await.map_err(map_database_error) + } + .await; + staging.disarm(); + result + }) + .await + .map_err(|_| MutationError::Unavailable)? + } + + async fn stage_attachment_rows( + &self, + transaction: &Transaction<'_>, + attachments: &[ActionRequestAttachment], + ) -> Result<(), MutationError> { + let backend = self.attachment_storage.binding_digest(); + let verification = self.attachment_verification.binding_digest(); for attachment in attachments_in_lock_order(attachments) { crate::attachment_store::stage_external( - guarded.transaction(), + transaction, &attachment.sha256, attachment.content.len() as u64, - &self.attachment_storage.binding_digest(), - &self.attachment_verification.binding_digest(), + &backend, + &verification, ) .await?; } - guarded - .commit() - .await - .map_err(|_| MutationError::Unavailable) + Ok(()) } /// Fill each record slot the Action declares from its file, in the @@ -1176,17 +1275,12 @@ impl MutationTransaction { }; // A hook holds no claims, so a grant that row-boundaries its targets // can never be satisfied by this path and is refused outright. - let mut target_authority = BTreeMap::>::new(); - for target in grant.entity_target_locks() { - if target.row_boundaries.is_empty() { - target_authority.insert(target.entity_id.clone(), Vec::new()); - } else { - return refused_proposal( - "hook.proposal.boundaries-unsatisfiable", - "The declared principal's grant carries row boundaries a hook holds no claims to satisfy.", - ); - } - } + let Some(target_authority) = hook_target_authority(grant) else { + return refused_proposal( + "hook.proposal.boundaries-unsatisfiable", + "The declared principal's grant carries row boundaries a hook holds no claims to satisfy.", + ); + }; if validate_action_claims(action, &claims, Operation::Invoke).is_err() { return refused_proposal( "hook.proposal.unauthorized", @@ -1342,6 +1436,7 @@ impl MutationTransaction { Some(&causation), None, &[], + None, ) .await; if matches!(attempt, Err(MutationError::RetryableConflict)) @@ -1383,7 +1478,11 @@ impl MutationTransaction { // applies again either. return conflicting_hook_answer(); } - Err(MutationError::PreconditionFailed | MutationError::FieldGuardFailed { .. }) => { + Err( + MutationError::PreconditionFailed + | MutationError::MembershipPreconditionFailed + | MutationError::FieldGuardFailed { .. }, + ) => { return refused_proposal( "hook.proposal.precondition-failed", "The proposed mutation found its target in an unexpected state.", @@ -1541,6 +1640,7 @@ impl MutationTransaction { causation: Option<&Causation>, timer_authority: Option<&TimerActionAuthority>, attachments: &[ActionRequestAttachment], + staging_pool: Option<&crate::postgres::RuntimePool>, ) -> Result { if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); @@ -1555,12 +1655,13 @@ impl MutationTransaction { ) .await } else { - begin_action_transaction( + crate::postgres::begin_action_transaction_for_write( client, self.lock_key, self.lock_timeout, &self.expected, claims, + claims.locks_membership(), ) .await } @@ -1635,6 +1736,7 @@ impl MutationTransaction { preconditions, timer_authority, trusted_now, + TargetRead::Lock, ) .await?; let entity = registry @@ -1758,8 +1860,38 @@ impl MutationTransaction { application_id, )?; - let guard_failure = match locked_timer_targets.take() { - Some(locked) => locked.guard_failure, + let mut membership = if claims.locks_membership() { + let observed = self + .lock_existing_action_targets( + transaction.transaction(), + registry, + action, + claims, + target_authority, + input_values, + application_id, + preconditions, + None, + trusted_now, + TargetRead::MembershipPreRead, + ) + .await?; + Some( + ActionMembership::acquire( + transaction.transaction(), + claims, + &observed, + effects, + input_values, + reserved_creates, + ) + .await?, + ) + } else { + None + }; + let locked_targets = match locked_timer_targets.take() { + Some(locked) => locked, None => { self.lock_existing_action_targets( transaction.transaction(), @@ -1772,9 +1904,9 @@ impl MutationTransaction { preconditions, timer_authority, trusted_now, + TargetRead::Lock, ) .await? - .guard_failure } }; @@ -1805,6 +1937,7 @@ impl MutationTransaction { claims, target_authority, input_values, + true, ) .await?; } @@ -1820,8 +1953,12 @@ impl MutationTransaction { preconditions, application_id, timer_authority, + true, ) .await?; + if let Some(membership) = &membership { + membership.verify_current(claims, &locked_targets)?; + } if let Some(timer) = timer_authority { let anchor = locked_timer_anchor .as_ref() @@ -1856,16 +1993,61 @@ impl MutationTransaction { // Before surfacing a failed guard, finish every current-target and // admission precheck above and recheck the grant. Effect application and // proposed-value authorization below run only after guards pass. - if let Some(input) = guard_failure { + if let Some(input) = locked_targets.guard_failure { check_current_action_grant(claims)?; return Err(MutationError::FieldGuardFailed { input }); } let ordered = ordered_action_effects(effects)?; let groups = ordered_action_effect_groups(&ordered, &patch_bases, reserved_creates)?; - let mut rows = BTreeMap::::new(); + if let Some(membership) = &mut membership { + for group in &groups { + let effect = group[0]; + let entity = registry + .entities() + .get(&effect.target.entity_id) + .ok_or(MutationError::InvalidRequest)?; + let (_, id) = action_effect_target_key(effect, &patch_bases, reserved_creates)?; + let base = patch_bases.get(&effect.id); + let target = action_target_group_context( + registry, + action, + group, + claims, + target_authority, + id, + base.map(|row| row.record_revision), + false, + Some(application_id), + &self.expected.activation_id, + None, + )?; + let mut preview = base.map(|row| row.data.clone()).unwrap_or_default(); + preview.extend(action_effect_group_document( + action, + entity, + group, + input_values, + reserved_creates, + )?); + membership.authorize_effect( + claims.access_profile(), + target.membership_boundaries(), + &preview, + )?; + match effect.operation { + Operation::Create => { + target.authorize_create_before_allocation(entity, &preview, id) + } + _ => target.authorize_rows(entity, base.map(|row| &row.data), &preview, id), + } + .map_err(|_| MutationError::PreconditionFailed)?; + } + } + let mut rows = BTreeMap::::new(); let mut timer_rows = BTreeMap::<(String, Uuid), CurrentRow>::new(); let mut results = Vec::::new(); for effects in groups { + let effect = effects[0]; fault.fail_at(MutationFaultPoint::BeforeCurrentRow)?; let current = self .apply_action_effect_group( @@ -1883,7 +2065,15 @@ impl MutationTransaction { timer_authority, ) .await?; - let effect = effects[0]; + if let Some(membership) = &membership { + if claims.is_membership_source(&effect.target.entity_id) { + // The locks fence other transactions. This transaction + // can change its own proof before a later effect uses it. + membership + .recheck_used_authority(transaction.transaction()) + .await?; + } + } let record_reference = record_reference( self.audit.profile(), &self.expected.activation_id, @@ -1968,7 +2158,7 @@ impl MutationTransaction { record_reference: record_reference.clone(), operation: effect.operation, }); - rows.insert(effect.id.clone(), current.clone()); + rows.insert(effect.id.clone(), current.record_uuid); } let timer_key = (entity.id.clone(), current.record_uuid); if let Some(previous) = timer_rows.insert(timer_key, current.clone()) { @@ -2008,6 +2198,24 @@ impl MutationTransaction { ) .await?; + // Like Proposal Apply, finish attachment work before taking the history + // head. Membership staging must also finish before the parent takes + // any attachment hash lock. + if let Some(pool) = staging_pool { + check_current_action_grant(claims)?; + self.stage_membership_action_attachments(pool, claims, attachments, deadline) + .await?; + } + self.write_action_attachments( + transaction.transaction(), + action, + claims, + binding, + &results, + attachments, + ) + .await?; + // Several effects may share one final record revision. Index each // distinct revision once, under the action transaction's one commit, // just as the single-record and batch mutation paths do. @@ -2043,15 +2251,6 @@ impl MutationTransaction { }, ) .await?; - self.write_action_attachments( - transaction.transaction(), - action, - claims, - binding, - &results, - attachments, - ) - .await?; let held = action_held_response(action, claims, application_id, &results)?; let public_result_count = u16::try_from( @@ -2240,7 +2439,7 @@ impl MutationTransaction { input_values: &ActionInputs, patch_bases: &BTreeMap, reserved_creates: &BTreeMap, - prior_results: &BTreeMap, + prior_results: &BTreeMap, application_id: Uuid, timer_authority: Option<&TimerActionAuthority>, ) -> Result { @@ -2297,22 +2496,8 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let mut fields = Map::new(); - for effect in effects { - let effect_fields = action_effect_document( - action, - entity, - effect, - input_values, - prior_results, - before, - )?; - for (field, value) in effect_fields { - if fields.insert(field, value).is_some() { - return Err(MutationError::InvalidRequest); - } - } - } + let mut fields = + action_effect_group_document(action, entity, effects, input_values, prior_results)?; if effect.operation == Operation::Create { crate::generated_identifiers::reserve_for_create(transaction, entity, &mut fields) .await?; @@ -2369,6 +2554,7 @@ impl MutationTransaction { preconditions: &BTreeMap, timer_authority: Option<&TimerActionAuthority>, trusted_now: time::OffsetDateTime, + read: TargetRead, ) -> Result { #[derive(Clone, Copy)] enum Role<'a> { @@ -2384,6 +2570,7 @@ impl MutationTransaction { let mut guard_failure = None; let mut rows = BTreeMap::new(); let mut missing_timer_link = false; + let mut missing_target = false; for effect in &action.effects { if let CompiledPlanTargetBinding::Existing { input } = &effect.target.binding { let record_id = Uuid::parse_str(&input_record_id(input_values, input)?) @@ -2528,17 +2715,27 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let mut current = - match load_action_row(transaction, entity, &record_id.to_string(), true).await { - Ok(current) => current, - Err(MutationError::PreconditionFailed) - if timer_authority.is_some() && matches!(role, Role::Link(_)) => - { - missing_timer_link = true; - continue; - } - Err(error) => return Err(error), - }; + let mut current = match load_action_row( + transaction, + entity, + &record_id.to_string(), + read == TargetRead::Lock, + ) + .await + { + Ok(current) => current, + Err(MutationError::PreconditionFailed) + if timer_authority.is_some() && matches!(role, Role::Link(_)) => + { + missing_timer_link = true; + continue; + } + Err(MutationError::PreconditionFailed) if read == TargetRead::MembershipPreRead => { + missing_target = true; + continue; + } + Err(error) => return Err(error), + }; if let (Role::Link(input), Some(timer)) = (role, timer_authority) { let fields = timer.read_fields_for_input(action, input, entity_id)?; timer.materialize_read_fields( @@ -2548,18 +2745,29 @@ impl MutationTransaction { self.field_encryption.as_deref(), )?; } - verify_action_requirements( - entity, - action, - input_values, - record_id, - ¤t, - self.audit.profile(), - registry, - trusted_now, - preconditions, - &mut guard_failure, - )?; + if read == TargetRead::EvidencePreflight { + probe_action_memberships( + transaction, + claims.access_profile(), + claims.target_membership(entity_id), + ¤t.data, + ) + .await?; + } + if read != TargetRead::MembershipPreRead { + verify_action_requirements( + entity, + action, + input_values, + record_id, + ¤t, + self.audit.profile(), + registry, + trusted_now, + preconditions, + &mut guard_failure, + )?; + } rows.insert((entity_id.to_owned(), record_id), current); } transaction @@ -2574,6 +2782,7 @@ impl MutationTransaction { guard_failure, rows, missing_timer_link, + missing_target, }) } @@ -2589,6 +2798,7 @@ impl MutationTransaction { preconditions: &BTreeMap, application_id: Uuid, timer_authority: Option<&TimerActionAuthority>, + lock: bool, ) -> Result, MutationError> { let mut patch_targets = BTreeMap::<(String, Uuid), Vec<(&str, &CompiledPlanEffect, String)>>::new(); @@ -2635,7 +2845,7 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let current = load_action_row(transaction, entity, &target_effects[0].2, true).await?; + let current = load_action_row(transaction, entity, &target_effects[0].2, lock).await?; // A `current-revision` Action sends no condition: its commit guards // were evaluated against this same locked row. if timer_authority.is_none() && action.concurrency.is_condition_required() { @@ -2678,6 +2888,15 @@ impl MutationTransaction { current.record_uuid, ) .map_err(|_| MutationError::PreconditionFailed)?; + if !lock { + probe_action_memberships( + transaction, + claims.access_profile(), + target_context.membership_boundaries(), + ¤t.data, + ) + .await?; + } for (_, effect, _) in target_effects { bases.insert(effect.id.clone(), current.clone()); } @@ -2760,6 +2979,13 @@ impl MutationTransaction { current.record_uuid, ) .map_err(|_| MutationError::PreconditionFailed)?; + probe_action_memberships( + transaction.transaction(), + claims.access_profile(), + target_context.membership_boundaries(), + ¤t.data, + ) + .await?; current } else { let link_context = action_link_context( @@ -2781,6 +3007,13 @@ impl MutationTransaction { link_context .authorize_row(entity, ¤t.data, current.record_uuid) .map_err(|_| MutationError::PreconditionFailed)?; + probe_action_memberships( + transaction.transaction(), + claims.access_profile(), + link_context.membership_boundaries(), + ¤t.data, + ) + .await?; current }; conditions.insert( @@ -2833,6 +3066,7 @@ impl MutationTransaction { Ok(held) } + #[allow(clippy::too_many_arguments)] // The read mode and authority belong to one Action invocation. async fn verify_action_link_references( &self, transaction: &Transaction<'_>, @@ -2841,6 +3075,7 @@ impl MutationTransaction { claims: &ActionClaimContext, target_authority: &BTreeMap>, input_values: &ActionInputs, + lock: bool, ) -> Result<(), MutationError> { let mut refs = Vec::new(); for target_use in &action.target_uses { @@ -2884,10 +3119,19 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let current = load_action_row(transaction, entity, &record_id, true).await?; + let current = load_action_row(transaction, entity, &record_id, lock).await?; link_context .authorize_row(entity, ¤t.data, current.record_uuid) .map_err(|_| MutationError::PreconditionFailed)?; + if !lock { + probe_action_memberships( + transaction, + claims.access_profile(), + link_context.membership_boundaries(), + ¤t.data, + ) + .await?; + } } Ok(()) } @@ -2983,6 +3227,13 @@ impl MutationTransaction { current.record_uuid, ) .map_err(|_| MutationError::PreconditionFailed)?; + probe_action_memberships( + transaction, + claims.access_profile(), + target_context.membership_boundaries(), + ¤t.data, + ) + .await?; } } Ok(()) @@ -3052,6 +3303,18 @@ fn conflicting_hook_answer() -> Result { ) } +fn hook_target_authority( + grant: &crate::model::CompiledActionPermission, +) -> Option>> { + grant + .entity_target_locks() + .map(|target| { + (target.row_boundaries.is_empty() && target.membership_boundaries.is_empty()) + .then(|| (target.entity_id.clone(), Vec::new())) + }) + .collect() +} + fn hook_change_idempotency_key(event_id: Uuid, compiled_delivery_id: &str) -> String { // The application identity is the hook delivery identity, // domain-separated. No attempt, generation, or answer component enters @@ -3488,12 +3751,32 @@ fn action_effect_target_key( Ok((effect.target.entity_id.clone(), record_uuid)) } +fn action_effect_group_document( + action: &CompiledAction, + entity: &CompiledEntity, + effects: &[&CompiledPlanEffect], + inputs: &ActionInputs, + references: &BTreeMap, +) -> Result, MutationError> { + let mut fields = Map::new(); + for effect in effects { + for (field, value) in + action_effect_document(action, entity, effect, inputs, references, None)? + { + if fields.insert(field, value).is_some() { + return Err(MutationError::InvalidRequest); + } + } + } + Ok(fields) +} + fn action_effect_document( action: &CompiledAction, entity: &CompiledEntity, effect: &CompiledPlanEffect, input_values: &ActionInputs, - prior_results: &BTreeMap, + prior_results: &BTreeMap, _before: Option<&CurrentRow>, ) -> Result, MutationError> { let mut data = Map::new(); @@ -3535,10 +3818,10 @@ fn action_effect_document( if target_entity_id != &source.target.entity_id { return Err(MutationError::InvalidRequest); } - let row = prior_results + let id = prior_results .get(effect) .ok_or(MutationError::InvalidRequest)?; - Value::String(row.record_id.clone()) + Value::String(id.to_string()) } }; if !validate_field_value(FieldValue::Json(&value), &field_source.field_type) @@ -3974,6 +4257,15 @@ impl MutationTransaction { context .authorize_row(entity, ¤t.data, uuid) .map_err(|_| MutationError::PreconditionFailed)?; + // At READ COMMITTED this read can see a different revision from + // the earlier Link check. Authorize the exact selector snapshot. + probe_action_memberships( + transaction, + claims.access_profile(), + context.membership_boundaries(), + ¤t.data, + ) + .await?; let values = fields .into_iter() .map(|field| { @@ -4152,6 +4444,7 @@ impl MutationTransaction { &input.preconditions, None, trusted_now, + TargetRead::EvidencePreflight, ) .await? .guard_failure; @@ -4162,20 +4455,23 @@ impl MutationTransaction { claims, target_authority, &normalized, + false, ) .await?; - self.lock_action_patch_targets( - transaction.transaction(), - registry, - action, - claims, - target_authority, - &normalized, - &input.preconditions, - application_id, - None, - ) - .await?; + let patch_bases = self + .lock_action_patch_targets( + transaction.transaction(), + registry, + action, + claims, + target_authority, + &normalized, + &input.preconditions, + application_id, + None, + false, + ) + .await?; let commit_requests = self .action_commit_evidence_requests( transaction.transaction(), @@ -4193,6 +4489,20 @@ impl MutationTransaction { if let Some(input) = guard_failure { return Err(MutationError::FieldGuardFailed { input }); } + let reserved_creates = reserve_action_create_ids(action)?; + if claims.locks_membership() { + membership::preflight_evidence( + transaction.transaction(), + registry, + action, + claims, + target_authority, + &normalized, + &patch_bases, + &reserved_creates, + ) + .await?; + } transaction .commit() .await @@ -4203,7 +4513,7 @@ impl MutationTransaction { commit_requests, preconditions: input.preconditions, binding, - reserved_creates: reserve_action_create_ids(action)?, + reserved_creates, application_id, trusted_now, attempt: None, @@ -4252,6 +4562,7 @@ impl MutationTransaction { None, None, &[], + None, ) .await; if matches!(result, Err(MutationError::RetryableConflict)) @@ -4392,6 +4703,56 @@ pub(crate) async fn erase_expired_action_evidence( mod tests { use super::*; + #[test] + fn hooks_refuse_claim_and_membership_boundaries_on_the_same_path() { + use crate::model::{ + CompiledActionPermission, CompiledActionTargetPermission, + CompiledActionTargetUseSource, CompiledMembershipBoundary, + }; + let mut grant = CompiledActionPermission { + profile_id: "operator".into(), + default: false, + actor_kind: None, + task_grant: None, + requester_clients: BTreeSet::new(), + principal_claim: Some("sub".into()), + required_scopes: BTreeSet::from(["records:write".into()]), + required_purposes: BTreeSet::new(), + operations: BTreeSet::from([Operation::Invoke]), + targets: vec![CompiledActionTargetPermission { + entity_id: "target".into(), + operation: Operation::Create, + source: CompiledActionTargetUseSource::Effect { + effect: "create".into(), + }, + row_boundaries: Vec::new(), + membership_boundaries: Vec::new(), + }], + results: BTreeSet::from(["create".into()]), + }; + assert!(hook_target_authority(&grant).is_some()); + grant.targets[0] + .row_boundaries + .push(crate::contract::RowBoundarySource { + field: "owner".into(), + claim: "sub".into(), + operator: crate::contract::BoundaryOperator::Equals, + }); + assert!(hook_target_authority(&grant).is_none()); + grant.targets[0].row_boundaries.clear(); + grant.targets[0] + .membership_boundaries + .push(CompiledMembershipBoundary { + field: "owner".into(), + membership_entity: "members".into(), + membership_table: "members".into(), + membership_key_column: "key".into(), + principal_column: "principal".into(), + active_column: "active".into(), + }); + assert!(hook_target_authority(&grant).is_none()); + } + #[test] fn ordinary_action_binding_keeps_the_released_canonical_shape() { let profile = AuditProfile::unkeyed_dev_only(); diff --git a/crates/registry-breg/src/mutation/action/membership.rs b/crates/registry-breg/src/mutation/action/membership.rs new file mode 100644 index 0000000000..76e48675be --- /dev/null +++ b/crates/registry-breg/src/mutation/action/membership.rs @@ -0,0 +1,709 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::action_outcome::{decode_slot_mutations, ProposedValue}; +use crate::membership::target_function_name; +use crate::model::{CompiledMembershipBoundary, CompiledPlanWrite}; +use crate::mutation::membership::{ + json_key, keys_for_row, probe, probe_action_membership, probe_action_memberships, LockKey, + MembershipLocks, +}; +use crate::postgres::snapshot_matches_boundaries; + +pub(super) struct ActionMembership { + keys: BTreeMap<(String, Uuid), Vec>>, + locks: MembershipLocks, + used: BTreeSet, +} + +impl ActionMembership { + pub(super) async fn acquire( + transaction: &Transaction<'_>, + claims: &ActionClaimContext, + observed: &LockedActionTargets, + effects: &[CompiledPlanEffect], + inputs: &ActionInputs, + reserved: &BTreeMap, + ) -> Result { + let profile = claims.access_profile(); + let mut needed = BTreeSet::new(); + let mut keys = BTreeMap::new(); + for ((entity, id), row) in &observed.rows { + let boundaries = claims.target_membership(entity); + if boundaries.is_empty() { + continue; + } + let existing = keys_for_row(boundaries, &row.data); + for (boundary, key) in boundaries.iter().zip(&existing) { + MembershipLocks::collect(&mut needed, profile, boundary, *key); + } + keys.insert((entity.clone(), *id), existing); + } + for effect in effects { + for boundary in claims.target_membership(&effect.target.entity_id) { + for mutation in &effect.mutations { + if let CompiledPlanMutation::Set { field, value } = mutation { + if field == &boundary.field { + let key = match value { + CompiledPlanValue::FromInput { input } => { + json_key(inputs.get(input)) + } + CompiledPlanValue::FromEffect { effect, .. } => { + reserved.get(effect).copied() + } + CompiledPlanValue::Literal { value } => json_key(Some(value)), + }; + MembershipLocks::collect(&mut needed, profile, boundary, key); + } + } + } + } + } + let mut membership = Self { + keys, + locks: MembershipLocks::acquire(transaction, needed).await?, + used: BTreeSet::new(), + }; + if observed.missing_target { + return Err(MutationError::PreconditionFailed); + } + for ((entity, _), keys) in &membership.keys { + for (boundary, key) in claims.target_membership(entity).iter().zip(keys) { + record_admission( + &membership.locks, + &mut membership.used, + profile, + boundary, + *key, + )?; + } + } + Ok(membership) + } + + pub(super) fn verify_current( + &self, + claims: &ActionClaimContext, + current: &LockedActionTargets, + ) -> Result<(), MutationError> { + for ((entity, id), expected) in &self.keys { + let row = current + .rows + .get(&(entity.clone(), *id)) + .ok_or(MutationError::MembershipPreconditionFailed)?; + if keys_for_row(claims.target_membership(entity), &row.data) != *expected { + return Err(MutationError::RetryableConflict); + } + } + Ok(()) + } + + pub(super) fn authorize_effect( + &mut self, + profile: &str, + boundaries: &[CompiledMembershipBoundary], + proposed: &Map, + ) -> Result<(), MutationError> { + for (boundary, key) in boundaries.iter().zip(keys_for_row(boundaries, proposed)) { + record_admission(&self.locks, &mut self.used, profile, boundary, key)?; + } + Ok(()) + } + + pub(super) async fn recheck_used_authority( + &self, + transaction: &Transaction<'_>, + ) -> Result<(), MutationError> { + for (helper, key) in &self.used { + if !probe(transaction, helper, *key).await? { + return Err(MutationError::MembershipPreconditionFailed); + } + } + Ok(()) + } +} + +fn record_admission( + locks: &MembershipLocks, + used: &mut BTreeSet, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, +) -> Result<(), MutationError> { + let key = key + .filter(|key| locks.allows(profile, boundary, Some(*key))) + .ok_or(MutationError::MembershipPreconditionFailed)?; + used.insert(( + target_function_name(profile, &boundary.membership_entity), + key, + )); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +pub(super) async fn preflight_evidence( + transaction: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + claims: &ActionClaimContext, + target_authority: &BTreeMap>, + inputs: &ActionInputs, + patch_bases: &BTreeMap, + reserved: &BTreeMap, +) -> Result<(), MutationError> { + let profile = claims.access_profile(); + if let Some(handler) = &action.handler { + for slot in &handler.writes { + let entity_id = &slot.ceiling.target_entity_id; + let entity = registry + .entities() + .get(entity_id) + .ok_or(MutationError::InvalidRequest)?; + let disclosure = crate::disclosure::plan(entity, profile); + let base = patch_bases.get(&slot.id); + if function_slot_can_write( + &slot.ceiling, + claims.target_membership(entity_id), + base.map(|base| &base.data), + inputs, + |field| { + entity + .fields + .get(field) + .is_some_and(|field| field.encryption.is_some()) + }, + |field, value| { + let (Some(boundaries), Some(base)) = (target_authority.get(entity_id), base) + else { + return false; + }; + permits_patch_value(entity, &disclosure, boundaries, base, field, value) + }, + |boundary, key| probe_action_membership(transaction, profile, boundary, Some(key)), + ) + .await? + { + return Ok(()); + } + } + return Err(MutationError::MembershipPreconditionFailed); + } + let ordered = ordered_action_effects(&action.effects)?; + for group in ordered_action_effect_groups(&ordered, patch_bases, reserved)? { + let effect = group[0]; + let entity = registry + .entities() + .get(&effect.target.entity_id) + .ok_or(MutationError::InvalidRequest)?; + let mut preview = patch_bases + .get(&effect.id) + .map(|base| base.data.clone()) + .unwrap_or_default(); + preview.extend(action_effect_group_document( + action, entity, &group, inputs, reserved, + )?); + probe_action_memberships( + transaction, + profile, + claims.target_membership(&entity.id), + &preview, + ) + .await?; + } + Ok(()) +} + +fn permits_patch_value( + entity: &CompiledEntity, + disclosure: &crate::disclosure::DisclosurePlan<'_>, + boundaries: &[RowBoundaryContext], + base: &CurrentRow, + field: &str, + value: &Value, +) -> bool { + if link_key_refused(entity, field, value) { + return false; + } + // The base row already passed its claim boundaries. Only predicates on + // the emitted field need to be checked against the candidate value. + let changed = Map::from_iter([(field.to_owned(), value.clone())]); + boundaries + .iter() + .filter(|boundary| boundary.field() == field) + .all(|boundary| { + snapshot_matches_boundaries( + entity, + &changed, + base.record_uuid, + std::slice::from_ref(boundary), + ) + .is_ok_and(|matches| matches) + }) + && matches!( + plan_write_disclosure(disclosure, Some(&base.data), &changed), + PlanWriteDisclosure::RecordVisible { update: Ok(()) } + ) +} + +async fn function_slot_can_write<'a, F>( + ceiling: &CompiledPlanWrite, + boundaries: &'a [CompiledMembershipBoundary], + base: Option<&Map>, + inputs: &ActionInputs, + is_encrypted: impl Fn(&str) -> bool, + permits_value: impl Fn(&str, &Value) -> bool, + mut probe_membership: impl FnMut(&'a CompiledMembershipBoundary, Uuid) -> F, +) -> Result +where + F: std::future::Future> + Send, +{ + let patch = ceiling.operation == Operation::Patch; + let mut has_mutation = !patch; + let mut by_field = BTreeMap::<&str, Vec<&CompiledMembershipBoundary>>::new(); + for boundary in boundaries { + by_field.entry(&boundary.field).or_default().push(boundary); + } + for (&field, boundaries) in &by_field { + // A covered field can be set from a declared input or retained by + // omission. A fresh create ID cannot supply current membership. + let mut candidates = reference_input_values(ceiling, field, inputs) + .filter(|value| !patch || permits_value(field, value)) + .filter_map(|value| json_key(Some(value)).map(|key| (key, true))) + .collect::>(); + if let Some(existing) = base.and_then(|base| json_key(base.get(field))) { + candidates.entry(existing).or_insert(false); + } + let mut authorized = false; + for (key, emits_mutation) in candidates { + let mut permitted = true; + for &boundary in boundaries { + if !probe_membership(boundary, key).await? { + permitted = false; + break; + } + } + if permitted { + authorized = true; + has_mutation |= emits_mutation; + if has_mutation { + break; + } + } + } + if !authorized { + return Ok(false); + } + } + // Every membership constraint is satisfiable. A Patch still needs a + // permitted set or clear somewhere in its authored ceiling. + Ok(has_mutation + || base.is_some_and(|base| { + ceiling.fields.iter().any(|field| { + !by_field.contains_key(field.as_str()) + && independent_patch_mutation( + ceiling, + field, + base, + inputs, + is_encrypted(field), + &permits_value, + ) + }) + })) +} + +fn reference_input_values<'a>( + ceiling: &'a CompiledPlanWrite, + field: &str, + inputs: &'a ActionInputs, +) -> impl Iterator { + ceiling + .reference_sources + .get(field) + .filter(|_| ceiling.fields.contains(field)) + .into_iter() + .flat_map(|sources| &sources.inputs) + .filter_map(|input| inputs.get(input)) +} + +fn independent_patch_mutation( + ceiling: &CompiledPlanWrite, + field: &str, + base: &Map, + inputs: &ActionInputs, + encrypted: bool, + permits_value: &impl Fn(&str, &Value) -> bool, +) -> bool { + if !ceiling.required_fields.contains(field) && permits_value(field, &Value::Null) { + return true; + } + if matches!( + ceiling.field_types.get(field), + Some(FieldTypeSource::Reference { .. }) + ) { + // FromEffect requires an emitted Create slot. A permitted Create can + // satisfy preflight itself, independently of this dependent Patch. + return reference_input_values(ceiling, field, inputs) + .any(|value| json_key(Some(value)).is_some() && permits_value(field, value)); + } + let permits_literal = |value: &Value| { + let members = [( + "set".to_owned(), + ProposedValue::Object(vec![(field.to_owned(), json_document(value.clone()))]), + )]; + decode_slot_mutations(ceiling, &members).is_ok() && permits_value(field, value) + }; + // Encrypted members in a stored row are opaque envelopes. Use a fresh + // typed witness when one is available without opening the stored value. + if !encrypted && base.get(field).is_some_and(permits_literal) { + return true; + } + // A previously stored string can exceed the Function ABI's byte bound + // even when a shorter literal of the same field type is representable. + let witness = match ceiling.field_types.get(field) { + Some(FieldTypeSource::String { min_length, .. }) + if *min_length as usize <= crate::rhai_planner::MAXIMUM_STRING_BYTES => + { + "a".repeat((*min_length as usize).max(1)) + } + Some(FieldTypeSource::Text { .. }) => "a".to_owned(), + Some(FieldTypeSource::Date) if encrypted => "2000-01-01".to_owned(), + Some(FieldTypeSource::Decimal { + scale, + minimum, + maximum, + .. + }) if encrypted => minimum + .as_ref() + .or(maximum.as_ref()) + .cloned() + .unwrap_or_else(|| { + if *scale == 0 { + "0".to_owned() + } else { + format!("0.{}", "0".repeat(usize::from(*scale))) + } + }), + _ => return false, + }; + permits_literal(&Value::String(witness)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::CompiledPlanReferenceSources; + + const RETAINED: Uuid = Uuid::from_u128(1); + const ALLOWED: Uuid = Uuid::from_u128(2); + const REFUSED: Uuid = Uuid::from_u128(3); + + fn boundary(field: &str, source: &str) -> CompiledMembershipBoundary { + CompiledMembershipBoundary { + field: field.to_owned(), + membership_entity: source.to_owned(), + membership_table: String::new(), + membership_key_column: String::new(), + principal_column: String::new(), + active_column: String::new(), + } + } + + fn ceiling(fields: &[&str]) -> CompiledPlanWrite { + let reference = FieldTypeSource::Reference { + target: "key".to_owned(), + on_delete: Default::default(), + }; + CompiledPlanWrite { + target_entity_id: "target".to_owned(), + target_from_input: None, + operation: Operation::Patch, + fields: fields.iter().map(|field| (*field).to_owned()).collect(), + field_types: fields + .iter() + .map(|field| ((*field).to_owned(), reference.clone())) + .collect(), + required_fields: fields.iter().map(|field| (*field).to_owned()).collect(), + reference_sources: fields + .iter() + .map(|field| { + ( + (*field).to_owned(), + CompiledPlanReferenceSources { + inputs: BTreeSet::from([format!("{field}-input")]), + create_entities: BTreeSet::new(), + }, + ) + }) + .collect(), + } + } + + fn references(fields: &[(&str, Uuid)]) -> Map { + fields + .iter() + .map(|(field, key)| ((*field).to_owned(), Value::String(key.to_string()))) + .collect() + } + + async fn admits( + ceiling: &CompiledPlanWrite, + boundaries: &[CompiledMembershipBoundary], + base: &Map, + inputs: &ActionInputs, + ) -> bool { + function_slot_can_write( + ceiling, + boundaries, + Some(base), + inputs, + |_| false, + |_, _| true, + |boundary, key| { + std::future::ready(Ok( + key != REFUSED && !(boundary.membership_entity == "other" && key == ALLOWED) + )) + }, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn omitting_covered_fields_cannot_supply_the_only_mutation() { + let ceiling = ceiling(&["first", "second"]); + let boundaries = [boundary("first", "source"), boundary("second", "source")]; + let base = references(&[("first", RETAINED), ("second", RETAINED)]); + let inputs = references(&[("first-input", REFUSED), ("second-input", REFUSED)]); + + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn one_covered_field_can_be_emitted_while_another_is_retained() { + let ceiling = ceiling(&["first", "second"]); + let boundaries = [boundary("first", "source"), boundary("second", "source")]; + let base = references(&[("first", RETAINED), ("second", RETAINED)]); + let inputs = references(&[("first-input", REFUSED), ("second-input", ALLOWED)]); + + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn a_covered_field_must_satisfy_all_its_boundaries() { + let ceiling = ceiling(&["first", "second"]); + let boundaries = [ + boundary("first", "source"), + boundary("first", "other"), + boundary("second", "source"), + ]; + let base = references(&[("first", RETAINED), ("second", RETAINED)]); + let inputs = references(&[("first-input", ALLOWED), ("second-input", REFUSED)]); + + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn an_independently_writable_literal_allows_membership_keys_to_be_retained() { + let mut ceiling = ceiling(&["first", "second", "flag"]); + ceiling + .field_types + .insert("flag".to_owned(), FieldTypeSource::Boolean); + ceiling.reference_sources.remove("flag"); + let boundaries = [boundary("first", "source"), boundary("second", "source")]; + let mut base = references(&[("first", RETAINED), ("second", RETAINED)]); + base.insert("flag".to_owned(), Value::Bool(true)); + let inputs = references(&[("first-input", REFUSED), ("second-input", REFUSED)]); + + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + base.remove("second"); + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn an_independent_reference_requires_an_available_source_or_a_permitted_clear() { + let mut ceiling = ceiling(&["first", "other"]); + let boundaries = [boundary("first", "source")]; + let base = references(&[("first", RETAINED), ("other", RETAINED)]); + let mut inputs = references(&[("first-input", REFUSED)]); + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + + inputs.extend(references(&[("other-input", ALLOWED)])); + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + + inputs.remove("other-input"); + ceiling.required_fields.remove("other"); + assert!(!independent_patch_mutation( + &ceiling, + "other", + &base, + &inputs, + false, + &|_, _| false, + )); + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn a_single_covered_field_can_set_an_authorized_reference_input() { + let ceiling = ceiling(&["first"]); + let boundaries = [boundary("first", "source")]; + let base = references(&[("first", RETAINED)]); + + for key in [ALLOWED, RETAINED] { + let inputs = references(&[("first-input", key)]); + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + } + let inputs = references(&[("first-input", REFUSED)]); + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[test] + fn a_patch_candidate_obeys_the_selected_profiles_write_disclosure() { + let source = json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", + "kind":"BRegProject", + "project":{"id":"write-disclosure","version":"1","defaultLanguage":"en", + "canonicalBaseIri":"https://unit.example.test"}, + "datasets":{"example":{}}, + "recordTypes":{"entry":{"primaryDataset":"example","route":"entries", + "mutationMode":"mutable","fields":[ + {"id":"mark","type":"string","maximumLength":20,"classification":"internal"}, + {"id":"note","type":"string","maximumLength":20,"classification":"internal"}, + {"id":"flag","type":"boolean","classification":"internal"} + ], + "disclosureConditions":{ + "hide-row":{"when":[{"type":"field-equals","field":"mark","value":"closed"}], + "withhold":"record","exemptProfiles":["officer"]}, + "hide-note":{"when":[{"type":"field-equals","field":"mark","value":"marked"}], + "withhold":"fields","fields":["note"],"exemptProfiles":["officer"]} + } + }}, + "accessProfiles":{ + "clerk":{"default":true,"principalClaim":"sub","requiredScopes":["records:write"], + "permissions":{"records":[{"recordType":"entry","operations":["get"], + "rowBoundaries":"unrestricted","readableFields":["mark","note","flag"]}]}}, + "officer":{"principalClaim":"sub","requiredScopes":["records:write"], + "permissions":{"records":[{"recordType":"entry","operations":["get"], + "rowBoundaries":"unrestricted","readableFields":["mark","note","flag"]}]}} + } + }); + let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect("write disclosure project parses"); + let registry = crate::compiler::compile_project( + &project, + &[], + crate::compiler::CompileProfile::Authoring, + ) + .expect("write disclosure project compiles"); + let entity = ®istry.entities()["entry"]; + let mut base = CurrentRow { + record_uuid: RETAINED, + record_id: RETAINED.to_string(), + record_revision: 1, + predecessor_revision: None, + record_lifecycle: "active".to_owned(), + before_data: None, + data: Map::from_iter([ + ("mark".to_owned(), json!("marked")), + ("note".to_owned(), json!("retained")), + ("flag".to_owned(), json!(false)), + ]), + }; + let permits = |profile, base: &CurrentRow, field, value: Value| { + permits_patch_value( + entity, + &crate::disclosure::plan(entity, profile), + &[], + base, + field, + &value, + ) + }; + assert!(permits("clerk", &base, "flag", json!(true))); + for (field, value) in [ + ("note", json!("retained")), + ("note", Value::Null), + ("mark", json!("open")), + ] { + assert!(permits("officer", &base, field, value.clone())); + assert!(!permits("clerk", &base, field, value)); + } + base.data.insert("mark".to_owned(), json!("open")); + assert!(permits("officer", &base, "mark", json!("closed"))); + assert!(!permits("clerk", &base, "mark", json!("closed"))); + base.data.insert("mark".to_owned(), json!(false)); + assert!(!permits("clerk", &base, "flag", json!(true))); + } + + #[test] + fn required_encrypted_scalars_have_typed_plaintext_witnesses() { + let mut ceiling = ceiling(&["value"]); + let stored = registry_platform_crypto::field_encryption::envelope_member_json(&[1; 40]); + let base = Map::from_iter([("value".to_owned(), stored)]); + for (field_type, expected) in [ + (FieldTypeSource::Date, "2000-01-01"), + ( + FieldTypeSource::Decimal { + precision: 4, + scale: 2, + minimum: Some("1.25".to_owned()), + maximum: Some("3.00".to_owned()), + }, + "1.25", + ), + ( + FieldTypeSource::Decimal { + precision: 3, + scale: 3, + minimum: None, + maximum: Some("-0.125".to_owned()), + }, + "-0.125", + ), + ( + FieldTypeSource::Decimal { + precision: 2, + scale: 2, + minimum: None, + maximum: None, + }, + "0.00", + ), + ] { + ceiling.field_types.insert("value".to_owned(), field_type); + assert!(independent_patch_mutation( + &ceiling, + "value", + &base, + &ActionInputs::new(), + true, + &|_, value| value.as_str() == Some(expected), + )); + } + } + + #[test] + fn a_stored_envelope_cannot_supply_a_structured_literal() { + let mut ceiling = ceiling(&["value"]); + ceiling.field_types.insert( + "value".to_owned(), + FieldTypeSource::Structured { + max_bytes: 1024, + schema: json!({"type":"object", "additionalProperties":true}), + }, + ); + let stored = registry_platform_crypto::field_encryption::envelope_member_json(&[1; 40]); + let base = Map::from_iter([("value".to_owned(), stored)]); + let inputs = ActionInputs::new(); + + assert!(!independent_patch_mutation( + &ceiling, + "value", + &base, + &inputs, + true, + &|_, _| true, + )); + } +} diff --git a/crates/registry-breg/src/mutation/membership.rs b/crates/registry-breg/src/mutation/membership.rs new file mode 100644 index 0000000000..2d8e3e7b29 --- /dev/null +++ b/crates/registry-breg/src/mutation/membership.rs @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::membership::lock_function_name; +use crate::model::CompiledMembershipBoundary; + +pub(super) type LockKey = (String, Uuid); + +#[derive(Default)] +pub(super) struct MembershipLocks(BTreeMap); + +impl MembershipLocks { + pub(super) fn collect( + keys: &mut BTreeSet, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, + ) { + if let Some(key) = key { + keys.insert(( + lock_function_name(profile, &boundary.membership_entity), + key, + )); + } + } + + pub(super) async fn acquire( + transaction: &Transaction<'_>, + keys: BTreeSet, + ) -> Result { + let mut answers = BTreeMap::new(); + for (helper, key) in keys { + let answer = probe(transaction, &helper, key).await?; + answers.insert((helper, key), answer); + } + Ok(Self(answers)) + } + + pub(super) fn allows( + &self, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, + ) -> bool { + key.is_some_and(|key| { + self.0.get(&( + lock_function_name(profile, &boundary.membership_entity), + key, + )) == Some(&true) + }) + } +} + +pub(super) async fn probe( + transaction: &Transaction<'_>, + helper: &str, + key: Uuid, +) -> Result { + transaction + .query_one( + &format!("SELECT registry_context.{}($1)", quote_identifier(helper)), + &[&key], + ) + .await + .map_err(map_database_error)? + .try_get(0) + .map_err(map_database_error) +} + +pub(crate) async fn probe_action_memberships( + transaction: &Transaction<'_>, + profile: &str, + boundaries: &[CompiledMembershipBoundary], + snapshot: &Map, +) -> Result<(), MutationError> { + for boundary in boundaries { + if !probe_action_membership( + transaction, + profile, + boundary, + json_key(snapshot.get(&boundary.field)), + ) + .await? + { + return Err(MutationError::MembershipPreconditionFailed); + } + } + Ok(()) +} + +pub(super) async fn probe_action_membership( + transaction: &Transaction<'_>, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, +) -> Result { + let Some(key) = key else { + return Ok(false); + }; + probe( + transaction, + &crate::membership::target_function_name(profile, &boundary.membership_entity), + key, + ) + .await +} + +pub(super) fn json_key(value: Option<&Value>) -> Option { + value + .and_then(Value::as_str) + .and_then(|value| Uuid::parse_str(value).ok()) +} + +pub(super) fn keys_for_row( + boundaries: &[CompiledMembershipBoundary], + row: &Map, +) -> Vec> { + boundaries + .iter() + .map(|boundary| json_key(row.get(&boundary.field))) + .collect() +} + +pub(super) struct RecordMembership<'a> { + profile: &'a str, + boundaries: &'a [CompiledMembershipBoundary], + observed: BTreeMap>>, + locks: MembershipLocks, +} + +impl<'a> RecordMembership<'a> { + pub(super) async fn prepare( + transaction: &Transaction<'_>, + entity: &'a CompiledEntity, + profile: &'a str, + items: impl IntoIterator, MutationBody)>, + ) -> Result, MutationError> { + let boundaries = crate::membership::boundaries(entity, profile); + if boundaries.is_empty() { + return Ok(None); + } + let mut record_ids = BTreeSet::new(); + let mut keys = BTreeSet::new(); + for (id, body) in items { + if let Some(id) = id { + record_ids.insert(Uuid::parse_str(id).map_err(|_| MutationError::InvalidRequest)?); + } + for boundary in boundaries { + match &body { + MutationBody::Create(data) => MembershipLocks::collect( + &mut keys, + profile, + boundary, + json_key(data.get(&boundary.field)), + ), + MutationBody::Patch(operations) => { + for operation in operations { + if let PatchOperation::Add { path, value } + | PatchOperation::Replace { path, value } = operation + { + if patch_field(path)? == boundary.field { + MembershipLocks::collect( + &mut keys, + profile, + boundary, + json_key(Some(value)), + ); + } + } + } + } + MutationBody::Tombstone => {} + } + } + } + let mut observed = BTreeMap::new(); + if !record_ids.is_empty() { + let columns = boundaries + .iter() + .map(|boundary| quote_identifier(&entity.fields[&boundary.field].physical_name)) + .collect::>() + .join(", "); + let table = quote_identifier(&entity.physical_table); + let ids = record_ids.into_iter().collect::>(); + let rows = transaction + .query( + &format!( + "SELECT record_id, {columns} FROM registry_data.{table} + WHERE record_id = ANY($1::uuid[]) AND record_lifecycle = 'active'" + ), + &[&ids], + ) + .await + .map_err(map_database_error)?; + for row in rows { + let current = boundaries + .iter() + .enumerate() + .map(|(index, boundary)| { + let key = row.try_get(index + 1).map_err(map_database_error)?; + MembershipLocks::collect(&mut keys, profile, boundary, key); + Ok(key) + }) + .collect::, MutationError>>()?; + observed.insert(row.try_get(0).map_err(map_database_error)?, current); + } + } + Ok(Some(Self { + profile, + boundaries, + observed, + locks: MembershipLocks::acquire(transaction, keys).await?, + })) + } + + pub(super) fn authorize_existing(&self, id: Option<&str>) -> Result<(), MutationError> { + let id = Uuid::parse_str(id.ok_or(MutationError::InvalidRequest)?) + .map_err(|_| MutationError::InvalidRequest)?; + let keys = self + .observed + .get(&id) + .ok_or(MutationError::PreconditionFailed)?; + if self.allows(keys) { + Ok(()) + } else { + Err(MutationError::MembershipPreconditionFailed) + } + } + + pub(super) fn verify_locked(&self, current: &CurrentRow) -> Result<(), MutationError> { + let keys = keys_for_row(self.boundaries, ¤t.data); + if self.observed.get(¤t.record_uuid) != Some(&keys) { + return Err(MutationError::MembershipKeyDrift); + } + if !self.allows(&keys) { + return Err(MutationError::MembershipPreconditionFailed); + } + Ok(()) + } + + pub(super) fn record_batch_write(&mut self, current: &CurrentRow) { + if let Some(keys) = self.observed.get_mut(¤t.record_uuid) { + *keys = keys_for_row(self.boundaries, ¤t.data); + } + } + + pub(super) fn authorize_proposed( + &self, + data: &Map, + ) -> Result<(), MutationError> { + if self.allows(&keys_for_row(self.boundaries, data)) { + Ok(()) + } else { + Err(MutationError::MembershipWriteOutsideBoundary) + } + } + + fn allows(&self, keys: &[Option]) -> bool { + self.boundaries + .iter() + .zip(keys) + .all(|(boundary, key)| self.locks.allows(self.profile, boundary, *key)) + } +} diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index 3dfb4a13cd..f5cee94bbb 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -92,6 +92,45 @@ fn check_current_proposal_grant(authority: &ProposalAuthority) -> Result<(), Mut Ok(()) } +async fn require_proposal_target_snapshot( + tx: &Transaction<'_>, + authority: &ProposalAuthority, + entity: &CompiledEntity, + id: Uuid, + snapshot: &Map, +) -> Result<(), MutationError> { + if !authority + .authorizes_snapshot(entity, id, snapshot) + .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::PreconditionFailed); + } + super::membership::probe_action_memberships( + tx, + authority.common.access_profile(), + authority.target_membership(&entity.id), + snapshot, + ) + .await +} + +fn proposal_mutation_target_error( + operation: ProposalAuthorityOperation, + error: MutationError, +) -> MutationError { + match (operation, error) { + ( + ProposalAuthorityOperation::Lifecycle( + ProposalOperation::Answer | ProposalOperation::Add, + ), + MutationError::PreconditionFailed, + ) => MutationError::AuthorizationRefused( + registry_platform_authcommon::FailedCheck::Visibility, + ), + (_, error) => error, + } +} + /// The answer to a target context the database refused to install. A context /// `install_target` rejects means the caller may not read that target. A /// store failure means nobody knows yet, so it answers 503 instead of being @@ -103,6 +142,25 @@ fn target_install_error(error: crate::postgres::PostgresKernelError) -> Mutation } } +struct ProposalMembershipLocks { + document_revision: i64, + observed: BTreeMap<(String, Uuid), Vec>>, + candidate_refusal: Option, + proofs: BTreeSet, + sources: BTreeSet, +} + +impl ProposalMembershipLocks { + async fn recheck(&self, tx: &Transaction<'_>) -> Result<(), MutationError> { + for (helper, key) in &self.proofs { + if !super::membership::probe(tx, helper, *key).await? { + return Err(MutationError::MembershipPreconditionFailed); + } + } + Ok(()) + } +} + fn validate_attachment_authority( action: &CompiledAction, authority: &ProposalAuthority, @@ -471,7 +529,8 @@ impl MutationTransaction { let document = proposal_store::load_document(tx, id, proposal_store::DocumentLock::Update).await?; self.authorize_proposal_document(tx, registry, &document, input.authority) - .await?; + .await + .map_err(|error| proposal_mutation_target_error(input.operation, error))?; let (binding, _) = self .proposal_document_binding(tx, registry, input, Some(&document)) .await?; @@ -927,7 +986,6 @@ impl MutationTransaction { authority: &ProposalAuthority, lock_targets: bool, ) -> Result<(), MutationError> { - let action = proposal_action(registry, &document.action_id)?; if let Some(check) = proposal_document_refusal( &document.action_id, authority.common.action_id(), @@ -939,6 +997,19 @@ impl MutationTransaction { ) { return Err(MutationError::AuthorizationRefused(check)); } + self.check_proposal_targets(tx, registry, document, authority, lock_targets) + .await + } + + async fn check_proposal_targets( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + authority: &ProposalAuthority, + lock_targets: bool, + ) -> Result<(), MutationError> { + let action = proposal_action(registry, &document.action_id)?; for (entity_id, id) in &document.input_targets { let entity = registry .entities() @@ -1017,12 +1088,7 @@ impl MutationTransaction { ) ); let row = load_proposal_row(tx, entity, *id, lock).await?; - if !authority - .authorizes_snapshot(entity, *id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, *id, &row.data).await?; } if document.header.state == "submitted" && !document.header.current_proposal_erased { let workflow = @@ -1061,12 +1127,14 @@ impl MutationTransaction { .entities() .get(&target.entity_id) .ok_or(MutationError::PreconditionFailed)?; - if !authority - .authorizes_snapshot(entity, target.record_id, &target.after) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot( + tx, + authority, + entity, + target.record_id, + &target.after, + ) + .await?; } } if document.header.state == "applied" { @@ -1104,12 +1172,7 @@ impl MutationTransaction { .await .map_err(target_install_error)?; let current = load_proposal_row(tx, entity, id, false).await?; - if !authority - .authorizes_snapshot(entity, id, ¤t.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, id, ¤t.data).await?; } } Ok(()) @@ -1136,8 +1199,14 @@ impl MutationTransaction { let tx = guarded.transaction(); let document = proposal_store::load_document(tx, id, proposal_store::DocumentLock::None).await?; - self.authorize_proposal_document(tx, registry, &document, input.authority) - .await?; + self.check_proposal_document( + tx, + registry, + &document, + input.authority, + !input.authority.locks_membership(), + ) + .await?; let (binding, _) = self .proposal_document_binding(tx, registry, input, Some(&document)) .await?; @@ -1321,28 +1390,39 @@ impl MutationTransaction { } else { None }; + let membership = if input.authority.locks_membership() { + self.lock_apply_memberships( + tx, + registry, + action, + input.authority, + input.proposal_id.ok_or(MutationError::InvalidRequest)?, + ) + .await? + } else { + None + }; let existing = if let Some(id) = input.proposal_id { let document = proposal_store::load_document(tx, id, proposal_store::DocumentLock::Update).await?; - if let Err(error) = self - .authorize_proposal_document(tx, registry, &document, input.authority) - .await + if membership + .as_ref() + .is_some_and(|locks| locks.document_revision != document.header.workflow_revision) + || (input.authority.locks_membership() + && document.header.state == "submitted" + && membership.is_none()) { - if matches!( - (&error, input.operation), - ( - MutationError::PreconditionFailed, - ProposalAuthorityOperation::Lifecycle( - ProposalOperation::Answer | ProposalOperation::Add - ) - ) - ) { - return Err(MutationError::AuthorizationRefused( - registry_platform_authcommon::FailedCheck::Visibility, - )); - } - return Err(error); + return Err(MutationError::PreconditionFailed); } + self.check_proposal_document( + tx, + registry, + &document, + input.authority, + !input.authority.locks_membership(), + ) + .await + .map_err(|error| proposal_mutation_target_error(input.operation, error))?; Some(document) } else { None @@ -1677,6 +1757,16 @@ impl MutationTransaction { let mut create_fields = proposal_prepare::materialize_create_fields( registry, &values, &resolved, )?; + proposal_prepare::authorize_candidates_before_allocation( + tx, + registry, + input.authority, + &values, + &resolved, + &create_fields, + &bases, + ) + .await?; for effect in resolved .effects .iter() @@ -2079,6 +2169,8 @@ impl MutationTransaction { document, input.authority, frozen, + membership.as_ref(), + &targets, ) .await?; self.verify_frozen_guards( @@ -2090,6 +2182,12 @@ impl MutationTransaction { frozen, ) .await?; + if let Some(error) = membership + .as_ref() + .and_then(|locks| locks.candidate_refusal.as_ref()) + { + return Err(error.clone()); + } self.apply_frozen_proposal( tx, registry, @@ -2100,6 +2198,7 @@ impl MutationTransaction { &binding, application_id, timer_staging.as_ref(), + membership.as_ref(), ) .await } @@ -2502,14 +2601,8 @@ impl MutationTransaction { .await .map_err(|_| MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, *id, true).await?; - if !authority - .authorizes_snapshot(entity, *id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, *id, &row.data).await?; } - let _ = action; Ok(()) } @@ -2527,7 +2620,7 @@ impl MutationTransaction { trusted_now: time::OffsetDateTime, ) -> Result< ( - BTreeMap<(String, Uuid), (i64, Map)>, + proposal_prepare::ProposalPatchBases, BTreeMap)>, ), MutationError, @@ -2573,12 +2666,7 @@ impl MutationTransaction { .await .map_err(|_| MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, id, true).await?; - if !authority - .authorizes_snapshot(entity, id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, id, &row.data).await?; rows.insert((entity_id, id), (row.record_revision, row.data)); } for ((entity, id), operation) in &resolved.records { @@ -2632,48 +2720,143 @@ impl MutationTransaction { Ok((bases, guards)) } - async fn lock_frozen_scope( + async fn lock_apply_memberships( &self, tx: &Transaction<'_>, registry: &CompiledRegistry, action: &CompiledAction, - document: &ProposalDocument, authority: &ProposalAuthority, - frozen: &crate::proposal_workflow::ProposalSnapshot, - ) -> Result<(), MutationError> { - let mut targets = BTreeMap::new(); - for target in frozen.input_targets() { - let id = Uuid::parse_str(target.record_id.as_str()) - .map_err(|_| MutationError::PreconditionFailed)?; - targets.insert((target.record_type.clone(), id), None); + id: Uuid, + ) -> Result, MutationError> { + use super::membership::{keys_for_row, MembershipLocks}; + + let document = + proposal_store::load_document(tx, id, proposal_store::DocumentLock::None).await?; + self.check_proposal_visibility(tx, registry, &document, authority) + .await?; + if document.header.state != "submitted" || document.header.current_proposal_erased { + return Ok(None); } - for effect in frozen.effects() { - if let Some(id) = effect.target().existing_record_id() { - targets.insert( - ( - effect.target().entity_id().as_str().to_owned(), - Uuid::parse_str(id.as_str()) - .map_err(|_| MutationError::PreconditionFailed)?, - ), - effect - .target() - .base_revision() - .map(|revision| revision.get()), - ); + let workflow = proposal_store::load(tx, &document.action_id, id, false).await?; + let frozen = workflow + .current_proposal() + .ok_or(MutationError::PreconditionFailed)?; + let targets = proposal_store::load_targets( + tx, + &document.action_id, + id, + document.header.submission_version, + ) + .await?; + proposal_prepare::validate_frozen_targets(frozen, &targets)?; + + let profile = authority.common.access_profile(); + let mut needed = BTreeSet::new(); + let mut observed = BTreeMap::new(); + let mut proofs = BTreeSet::new(); + let mut sources = BTreeSet::new(); + for ((entity_id, record_id), revision) in frozen_scope(frozen)? { + let boundaries = authority.target_membership(&entity_id); + if boundaries.is_empty() { + continue; + } + let entity = ®istry.entities()[&entity_id]; + authority + .install_target( + tx, + registry, + id, + frozen.version().get(), + ProposalTargetPhase::Application, + &entity_id, + record_id, + Operation::Get, + &proposal_read_fields(action, &entity_id), + revision, + Some(frozen.effect_digest().as_str()), + ) + .await + .map_err(target_install_error)?; + let row = load_proposal_row(tx, entity, record_id, false).await?; + let keys = keys_for_row(boundaries, &row.data); + for (boundary, key) in boundaries.iter().zip(&keys) { + MembershipLocks::collect(&mut needed, profile, boundary, *key); } + observed.insert((entity_id, record_id), keys); } - if let Some(guards) = frozen.application_preconditions() { - for target in &guards.targets { - targets.insert( - ( - target.entity_id.clone(), - Uuid::parse_str(target.record_id.as_str()) - .map_err(|_| MutationError::PreconditionFailed)?, - ), - Some(target.expected_revision), - ); + for target in &targets { + let boundaries = authority.target_membership(&target.entity_id); + for (boundary, key) in boundaries + .iter() + .zip(keys_for_row(boundaries, &target.after)) + { + MembershipLocks::collect(&mut needed, profile, boundary, key); + } + } + // The shared package lock is already held. Take source locks before + // locking the Proposal state or any target row. + let locks = MembershipLocks::acquire(tx, needed).await?; + let mut admit = |entity: &str, keys: &[Option]| { + let boundaries = authority.target_membership(entity); + if !boundaries + .iter() + .zip(keys) + .all(|(boundary, key)| locks.allows(profile, boundary, *key)) + { + return false; + } + for (boundary, key) in boundaries.iter().zip(keys.iter().flatten()) { + proofs.insert(( + crate::membership::target_function_name(profile, &boundary.membership_entity), + *key, + )); + sources.insert(boundary.membership_entity.clone()); + } + true + }; + for ((entity, _), keys) in &observed { + if !admit(entity, keys) { + return Err(MutationError::MembershipPreconditionFailed); } } + let mut candidate_refusal = None; + for target in &targets { + if !admit( + &target.entity_id, + &keys_for_row( + authority.target_membership(&target.entity_id), + &target.after, + ), + ) { + if target.operation != Operation::Patch { + candidate_refusal = Some(MutationError::MembershipPreconditionFailed); + } else if candidate_refusal.is_none() { + candidate_refusal = Some(MutationError::MembershipWriteOutsideBoundary); + } + } + } + Ok(Some(ProposalMembershipLocks { + document_revision: document.header.workflow_revision, + observed, + candidate_refusal, + proofs, + sources, + })) + } + + #[allow(clippy::too_many_arguments)] + async fn lock_frozen_scope( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + authority: &ProposalAuthority, + frozen: &crate::proposal_workflow::ProposalSnapshot, + membership: Option<&ProposalMembershipLocks>, + snapshots: &[ProposalTargetSnapshot], + ) -> Result<(), MutationError> { + let targets = frozen_scope(frozen)?; for ((entity_id, id), revision) in targets { let entity = registry .entities() @@ -2696,12 +2879,37 @@ impl MutationTransaction { .await .map_err(|_| MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, id, true).await?; + if let Some(expected) = + membership.and_then(|locks| locks.observed.get(&(entity_id.clone(), id))) + { + if super::membership::keys_for_row( + authority.target_membership(&entity_id), + &row.data, + ) != *expected + { + return Err(MutationError::PreconditionFailed); + } + } if !authority .authorizes_snapshot(entity, id, &row.data) .map_err(|_| MutationError::PreconditionFailed)? { return Err(MutationError::PreconditionFailed); } + // A known candidate refusal prevents all writes. Check the frozen + // Patch bases here because the effect loop will never reach them. + if membership.is_some_and(|locks| locks.candidate_refusal.is_some()) + && snapshots.iter().any(|snapshot| { + snapshot.entity_id == entity_id + && snapshot.record_id == id + && snapshot.expected_revision.is_some_and(|revision| { + revision != row.record_revision + || snapshot.before.as_ref() != Some(&row.data) + }) + }) + { + return Err(MutationError::ProposalTargetChanged); + } } Ok(()) } @@ -2852,6 +3060,7 @@ impl MutationTransaction { binding: &crate::idempotency::ResolvedIdempotencyBinding, application_id: Uuid, timer_staging: Option<&RecordTimerStaging>, + membership: Option<&ProposalMembershipLocks>, ) -> Result<(Vec, Vec), MutationError> { let action = proposal_action(registry, &document.action_id)?; let mut observed = Vec::new(); @@ -3007,6 +3216,9 @@ impl MutationTransaction { PlanWriteOrigin::ProposalApplication, ) .await?; + if let Some(locks) = membership.filter(|locks| locks.sources.contains(&entity.id)) { + locks.recheck(tx).await?; + } let reference = record_reference( self.audit.profile(), &self.expected.activation_id, @@ -3576,6 +3788,8 @@ impl MutationTransaction { if accepted.request_id != request.request_id || accepted.policy != request.policy { return Err(MutationError::PreconditionFailed); } + self.check_proposal_targets(tx, registry, document, authority, false) + .await?; value["policy"] = json!(accepted.policy); } match authority.operation { @@ -4424,6 +4638,44 @@ fn public_application( value } +fn frozen_scope( + frozen: &crate::proposal_workflow::ProposalSnapshot, +) -> Result>, MutationError> { + let mut targets = BTreeMap::new(); + for target in frozen.input_targets() { + let id = Uuid::parse_str(target.record_id.as_str()) + .map_err(|_| MutationError::PreconditionFailed)?; + targets.insert((target.record_type.clone(), id), None); + } + for effect in frozen.effects() { + if let Some(id) = effect.target().existing_record_id() { + targets.insert( + ( + effect.target().entity_id().as_str().to_owned(), + Uuid::parse_str(id.as_str()).map_err(|_| MutationError::PreconditionFailed)?, + ), + effect + .target() + .base_revision() + .map(|revision| revision.get()), + ); + } + } + if let Some(guards) = frozen.application_preconditions() { + for target in &guards.targets { + targets.insert( + ( + target.entity_id.clone(), + Uuid::parse_str(target.record_id.as_str()) + .map_err(|_| MutationError::PreconditionFailed)?, + ), + Some(target.expected_revision), + ); + } + } + Ok(targets) +} + fn proposal_action<'a>( registry: &'a CompiledRegistry, id: &str, @@ -4604,17 +4856,17 @@ fn proposal_turn_context( pub(crate) const PUBLIC_REASON_REFERENCE: &str = "proposal-review-public-reason"; pub(crate) const REVIEW_PROGRESS_REFERENCE: &str = "proposal-review-progress"; -/// Whether a Get-authority document check lets the caller read the Proposal. -/// Only the two refusals a Proposal read gives a caller who may not read it -/// withhold what Get serves. A conflict, a retryable conflict or any other -/// failure stays an error, so nobody takes a failure for a refusal that would -/// silently omit what the caller may read. +/// Whether the document check lets the caller see a Proposal in a projection. +/// A refusal omits the candidate from a collection or a link. A store failure +/// still fails the request, since the caller may be entitled to the candidate. pub(crate) fn link_readable(outcome: Result<(), MutationError>) -> Result { match outcome { Ok(()) => Ok(true), - Err(MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed) => { - Ok(false) - } + Err( + MutationError::AuthorizationRefused(_) + | MutationError::PreconditionFailed + | MutationError::MembershipPreconditionFailed, + ) => Ok(false), Err(error) => Err(error), } } @@ -4917,6 +5169,36 @@ async fn load_proposal_row( #[cfg(test)] mod disclosure_tests { use super::*; + + #[test] + fn attachment_and_answer_target_concealment_keeps_the_observed_cause() { + use registry_platform_authcommon::FailedCheck; + + for operation in [ProposalOperation::Answer, ProposalOperation::Add] { + let operation = ProposalAuthorityOperation::Lifecycle(operation); + assert_eq!( + proposal_mutation_target_error(operation, MutationError::PreconditionFailed), + MutationError::AuthorizationRefused(FailedCheck::Visibility), + ); + for error in [ + MutationError::MembershipPreconditionFailed, + MutationError::Unavailable, + ] { + assert_eq!( + proposal_mutation_target_error(operation, error.clone()), + error + ); + } + } + assert_eq!( + proposal_mutation_target_error( + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit), + MutationError::PreconditionFailed, + ), + MutationError::PreconditionFailed, + ); + } + fn coordinator(database: &str, activation: &str, key: u8, issuer: &str) -> MutationTransaction { let (audit, _capture) = crate::audit::test_support::capturing( registry_platform_audit::AuditProfile::production_from_secret_bytes( @@ -5397,7 +5679,7 @@ mod input_write_tests { {"id":"value","type":"string","required":true,"maximumLength":64,"classification":"internal"}, {"id":"licence-number","type":"string","required":false,"maximumLength":64,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"name","target":{"fromInput":"target"},"operation":"patch","set":{"name":{"fromInput":"value"}}}]}}}, - "accessProfiles":{"clerk": {"default":true,"principalClaim":"sub","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"clerk": {"default":true,"principalClaim":"sub","requiredScopes":["records:write"],"permissions":{ "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}]}}}}); let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); diff --git a/crates/registry-breg/src/mutation/proposal/context_projection.rs b/crates/registry-breg/src/mutation/proposal/context_projection.rs index 489b642fcd..c8c55e8cee 100644 --- a/crates/registry-breg/src/mutation/proposal/context_projection.rs +++ b/crates/registry-breg/src/mutation/proposal/context_projection.rs @@ -33,18 +33,23 @@ pub(super) async fn fields( }) }) .ok_or(MutationError::PreconditionFailed)?; - let document_contract = if mapping + let fields = mapping .fields .iter() - .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))) - .map(|(_, source)| source) - .any(|source| { - matches!( - source, - ProposalContextValueSource::Document { .. } - | ProposalContextValueSource::Additions { .. } - ) - }) { + .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))); + if fields + .clone() + .any(|(field, _)| !permission.readable_context_fields.contains(field)) + { + return Err(MutationError::PreconditionFailed); + } + let document_contract = if fields.clone().any(|(_, source)| { + matches!( + source, + ProposalContextValueSource::Document { .. } + | ProposalContextValueSource::Additions { .. } + ) + }) { Some( crate::compiler::review_context::compile_schema(registry, action) .map_err(|_| MutationError::Unavailable)? @@ -64,12 +69,9 @@ pub(super) async fn fields( { return Err(MutationError::PreconditionFailed); } - let targets = if mapping - .fields - .iter() - .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))) - .map(|(_, source)| source) - .any(|source| matches!(source, ProposalContextValueSource::Changes { .. })) + let targets = if fields + .clone() + .any(|(_, source)| matches!(source, ProposalContextValueSource::Changes { .. })) { frozen .verify_digest(&crate::proposal_workflow::ProposalKey::new( @@ -89,14 +91,20 @@ pub(super) async fn fields( } else { Vec::new() }; - let mut projected = Map::new(); - for (field, source) in &mapping.fields { - if selected_fields.is_some_and(|selected| !selected.contains(field)) { - continue; - } - if !permission.readable_context_fields.contains(field) { - return Err(MutationError::PreconditionFailed); - } + // Resolve the selected Record scopes before acquiring document metadata. + // Keep the canonical field order independently of acquisition order. + let record_source = |source: &ProposalContextValueSource| { + matches!( + source, + ProposalContextValueSource::Record { .. } | ProposalContextValueSource::Changes { .. } + ) + }; + let mut projected = BTreeMap::new(); + for (field, source) in fields + .clone() + .filter(|(_, source)| record_source(source)) + .chain(fields.filter(|(_, source)| !record_source(source))) + { let resolved = match source { ProposalContextValueSource::Additions { slot } => { let schema = document_contract @@ -192,12 +200,7 @@ pub(super) async fn fields( .and_then(|id| Uuid::parse_str(id).ok()) .ok_or(MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, id, false).await?; - if !authority - .authorizes_snapshot(entity, id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_snapshot(tx, entity, record, authority, id, &row.data).await?; let optional = !entity .fields .get(field) @@ -293,7 +296,7 @@ pub(super) async fn fields( }; projected.insert(field.clone(), resolved); } - Ok(projected) + Ok(projected.into_iter().collect()) } /// Prepare refuses a submission that omits a required input, so the frozen @@ -345,13 +348,10 @@ async fn require_snapshot( id: Uuid, snapshot: &Map, ) -> Result<(), MutationError> { - if !authority - .authorizes_snapshot(entity, id, snapshot) + if !record + .context + .authorizes_record_snapshot(entity, snapshot, id) .map_err(|_| MutationError::PreconditionFailed)? - || !record - .context - .authorizes_record_snapshot(entity, snapshot, id) - .map_err(|_| MutationError::PreconditionFailed)? { return Err(MutationError::PreconditionFailed); } @@ -379,7 +379,7 @@ async fn require_snapshot( return Err(MutationError::PreconditionFailed); } } - Ok(()) + require_proposal_target_snapshot(tx, authority, entity, id, snapshot).await } /// The members the profile may not see on `state`. A record the profile diff --git a/crates/registry-breg/src/package.rs b/crates/registry-breg/src/package.rs index 5a5d9b4649..7cc70369ab 100644 --- a/crates/registry-breg/src/package.rs +++ b/crates/registry-breg/src/package.rs @@ -2347,7 +2347,9 @@ fn additive_migration_plan( .map(|statement| (statement.id.as_str(), statement)) .collect::>(); for (id, statement) in &candidate_probe_functions { - if previous_probe_functions.get(id) != Some(statement) { + if previous_probe_functions.get(id) != Some(statement) + || (refresh_compiler_owned_ddl && id.starts_with("registry_context.membership_")) + { new_statement_ids.insert((*id).to_owned()); if previous_probe_functions.contains_key(id) { replacement_statement_ids.insert((*id).to_owned()); @@ -2767,6 +2769,26 @@ fn additive_migration_plan( new_statement_ids.insert(id.clone()); } } + let previous_index = crate::membership::index_statement(previous_entity); + let candidate_index = crate::membership::index_statement(candidate_entity); + // A baseline compiled without the index still projects it when + // regenerated here. Refresh it on compiler drift even if the model + // declares the same membership columns. + if refresh_compiler_owned_ddl || previous_index != candidate_index { + if let Some((id, name, _)) = previous_index { + removed_dependency_statements.push(DdlStatement { + id: format!("{id}.drop"), + kind: DdlStatementKind::Index, + sql: format!( + "DROP INDEX IF EXISTS registry_data.{}", + quote_identifier(&name) + ), + }); + } + if let Some((id, _, _)) = candidate_index { + new_statement_ids.insert(id); + } + } } let mut statements = removed_dependency_statements; diff --git a/crates/registry-breg/src/package/tests/immediate_actions.rs b/crates/registry-breg/src/package/tests/immediate_actions.rs index 06b50dd014..21e106dc0b 100644 --- a/crates/registry-breg/src/package/tests/immediate_actions.rs +++ b/crates/registry-breg/src/package/tests/immediate_actions.rs @@ -151,7 +151,7 @@ fn ordinary_policy_source(auditor_operations: Option<&[&str]>) -> Value { {"id":"person-code", "type":"string", "maximumLength":40, "required":true, "classification":"internal"}, {"id":"sensitive-note", "type":"string", "maximumLength":120, "classification":"internal"} ]}}, - "accessProfiles":{"operator": { "default":true, "principalClaim":"principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": { "default":true, "principalClaim":"principal","requiredScopes":["records:write"], "permissions":{"records":[{"recordType":"person", "operations":["create","get","list"], "readableFields":["person-code","sensitive-note"], "writableFields":["person-code","sensitive-note"], "rowBoundaries":"unrestricted"}]}}} @@ -599,7 +599,7 @@ fn reviewed_successor_does_not_duplicate_action_policies_for_new_entity() { candidate["accessProfiles"] = json!({"task-operator": { "default":true, "principalClaim":"principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "permissions":{"actions":[{"action":"create-task", "operations":["invoke"], "targets":[{"recordType":"task", "rowBoundaries":"unrestricted"}], "results":["task"]}]} }}); let after = compile(&candidate); diff --git a/crates/registry-breg/src/postgres/cancellation.rs b/crates/registry-breg/src/postgres/cancellation.rs index d60add4206..f538c31823 100644 --- a/crates/registry-breg/src/postgres/cancellation.rs +++ b/crates/registry-breg/src/postgres/cancellation.rs @@ -19,6 +19,10 @@ use std::time::Duration; +use deadpool_postgres::ClientWrapper; +use tokio::sync::OwnedSemaphorePermit; +use tokio_postgres::{CancelToken, Client}; + use super::RuntimePool; /// How long a guard waits for the cancel request and then for the cancelled @@ -123,11 +127,62 @@ impl Drop for Discarded { /// travels on its own connection and may land on whatever the session runs /// next, so a cancelled session is never reused. async fn stop_and_discard(session: Discarded, token: tokio_postgres::CancelToken) { - let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, session.pool.cancel_query(token)).await; if let Some(client) = &session.client { - // The empty query is answered only after every request queued before - // it, including the cancelled statement and the rollback its dropped - // transaction queued, so its answer means the backend is idle. - let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, client.simple_query("")).await; + cancel_and_drain(&session.pool, token, client).await; + } +} + +async fn cancel_and_drain(pool: &RuntimePool, token: CancelToken, client: &Client) { + let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, pool.cancel_query(token)).await; + // The empty query is answered only after every request queued before + // it, including the cancelled statement and the rollback its dropped + // transaction queued, so its answer means the backend is idle. + let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, client.simple_query("")).await; +} + +/// The dedicated staging session retains its permit while cancellation drains it. +pub(crate) struct AttachmentStagingGuard { + pool: RuntimePool, + session: Option<(ClientWrapper, OwnedSemaphorePermit)>, +} + +impl AttachmentStagingGuard { + pub(super) fn new( + pool: RuntimePool, + client: ClientWrapper, + permit: OwnedSemaphorePermit, + ) -> Self { + Self { + pool, + session: Some((client, permit)), + } + } + + pub(crate) fn client(&mut self) -> &mut ClientWrapper { + &mut self + .session + .as_mut() + .expect("the staging session is guarded") + .0 + } + + pub(crate) fn disarm(mut self) { + drop(self.session.take()); + } +} + +impl Drop for AttachmentStagingGuard { + fn drop(&mut self) { + if let Some((client, permit)) = self.session.take() { + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return; + }; + let pool = self.pool.clone(); + runtime.spawn(async move { + cancel_and_drain(&pool, client.cancel_token(), &client).await; + drop(client); + drop(permit); + }); + } } } diff --git a/crates/registry-breg/src/postgres/catalog.rs b/crates/registry-breg/src/postgres/catalog.rs index f66111969c..cc9f19ac42 100644 --- a/crates/registry-breg/src/postgres/catalog.rs +++ b/crates/registry-breg/src/postgres/catalog.rs @@ -1574,6 +1574,15 @@ async fn verify_closed_ambient_catalog( projection_definers.push(*security_definer); } } + let membership_identities: Vec<_> = expected_catalog + .objects + .iter() + .filter(|object| { + object.kind == ManagedObjectKind::Function + && object.name.starts_with("registry_context.membership_") + }) + .map(|object| object.name.as_str()) + .collect(); let row = client .query_one( "SELECT @@ -1617,12 +1626,17 @@ async fn verify_closed_ambient_catalog( AND p.proisstrict AND p.provolatile = 'i' AND p.proconfig = ARRAY['search_path=pg_catalog']) - OR (p.proname ~ '^membership_[0-9a-f]{24}$' + OR (p.proname ~ '^membership_(target_|lock_)?[0-9a-f]{24}$' + AND ('registry_context.' || p.proname || '(uuid)') = ANY($6::text[]) AND pg_catalog.pg_get_function_identity_arguments(p.oid) = 'uuid' AND p.prorettype = 'boolean'::regtype AND NOT p.proretset AND NOT p.prosecdef - AND p.provolatile = 's') + AND p.provolatile::text = CASE WHEN p.proname ~ '^membership_lock_' THEN 'v' ELSE 's' END + AND p.prokind = 'f' + AND p.proisstrict AND NOT p.proleakproof + AND p.prolang = (SELECT oid FROM pg_catalog.pg_language WHERE lanname = 'plpgsql') + AND p.proconfig = ARRAY['search_path=pg_catalog']) OR (p.proname ~ '^consent_[0-9a-f]{24}$' AND pg_catalog.pg_get_function_identity_arguments(p.oid) = '' AND p.prorettype = 'uuid'::regtype @@ -1695,7 +1709,7 @@ async fn verify_closed_ambient_catalog( ) OR EXISTS ( SELECT 1 FROM pg_catalog.pg_publication WHERE puballtables )", - &[&MANAGED_SCHEMAS, &projection_identities, &projection_returns, &projection_sets, &projection_definers], + &[&MANAGED_SCHEMAS, &projection_identities, &projection_returns, &projection_sets, &projection_definers, &membership_identities], ) .await?; if (0..5).any(|index| row.get::<_, bool>(index)) { diff --git a/crates/registry-breg/src/postgres/config.rs b/crates/registry-breg/src/postgres/config.rs index 19f2c69bbc..2f4b35e9a8 100644 --- a/crates/registry-breg/src/postgres/config.rs +++ b/crates/registry-breg/src/postgres/config.rs @@ -1,12 +1,22 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{error::Error as _, fmt, str::FromStr, sync::OnceLock, time::Duration}; - -use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; +use std::{ + error::Error as _, + fmt, + str::FromStr, + sync::{Arc, OnceLock}, + time::Duration, +}; + +use deadpool_postgres::{ + ClientWrapper, ConfigConnectImpl, Connect, Manager, ManagerConfig, Pool, RecyclingMethod, + Runtime, +}; use tokio_postgres::NoTls; use tokio_postgres::{config::SslMode, CancelToken, Config}; use tokio_postgres_rustls::MakeRustlsConnect; +use super::cancellation::AttachmentStagingGuard; use super::{PostgresKernelError, Result}; const MAX_POOL_SIZE: usize = 128; @@ -348,6 +358,8 @@ impl ConnectionConfig { Ok(RuntimePool { pool, transport: self.transport.clone(), + postgres: self.postgres.clone(), + attachment_staging: Arc::new(tokio::sync::Semaphore::new(1)), }) } } @@ -435,6 +447,8 @@ fn connector_from_roots(roots: rustls::RootCertStore) -> Result, } /// Value-free causes that operator tooling may report for a refused database @@ -587,6 +601,43 @@ impl RuntimePool { self.pool.get().await.map_err(|_| PostgresKernelError::Pool) } + /// Durable S3 staging while the caller's primary transaction holds its + /// membership and target locks. One separate session per pool prevents + /// pool exhaustion when every ordinary connection is in use. + pub(crate) async fn attachment_staging_connection(&self) -> Result { + let permit = Arc::clone(&self.attachment_staging) + .acquire_owned() + .await + .map_err(|_| PostgresKernelError::Pool)?; + let connect = async { + match &self.transport { + Transport::Tls { connector, .. } => { + ConfigConnectImpl { + tls: connector.clone(), + } + .connect(&self.postgres) + .await + } + Transport::Plaintext(_) => { + ConfigConnectImpl { tls: NoTls } + .connect(&self.postgres) + .await + } + } + }; + let (client, task) = match self.pool.timeouts().create { + Some(timeout) => tokio::time::timeout(timeout, connect) + .await + .map_err(|_| PostgresKernelError::Pool)??, + None => connect.await?, + }; + Ok(AttachmentStagingGuard::new( + self.clone(), + ClientWrapper::new(client, task), + permit, + )) + } + pub(crate) async fn get_for_startup( &self, ) -> std::result::Result { diff --git a/crates/registry-breg/src/postgres/context.rs b/crates/registry-breg/src/postgres/context.rs index a1136086f9..4eb5f6601e 100644 --- a/crates/registry-breg/src/postgres/context.rs +++ b/crates/registry-breg/src/postgres/context.rs @@ -9,6 +9,7 @@ use registry_platform_canonical_json::canonicalize_json; use serde_json::{json, Value}; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use tokio_postgres::types::Type; +use tokio_postgres::IsolationLevel; use uuid::Uuid; use crate::contract::{BoundaryOperator, Operation}; @@ -56,6 +57,7 @@ pub(crate) struct ActionClaimContext { principal: String, access_profile: String, purpose: Option, + target_memberships: BTreeMap>, result_effects: BTreeSet, audit_context: Option, task_grant: Option, @@ -75,6 +77,7 @@ impl ActionClaimContext { principal, access_profile, purpose, + target_memberships: BTreeMap::new(), result_effects, audit_context: None, task_grant: None, @@ -84,6 +87,35 @@ impl ActionClaimContext { Ok(context) } + pub(crate) fn with_target_memberships( + mut self, + memberships: BTreeMap>, + ) -> Self { + self.target_memberships = memberships; + self + } + + pub(crate) fn locks_membership(&self) -> bool { + !self.target_memberships.is_empty() + } + + pub(crate) fn is_membership_source(&self, entity: &str) -> bool { + self.target_memberships + .values() + .flatten() + .any(|boundary| boundary.membership_entity == entity) + } + + pub(crate) fn target_membership( + &self, + entity: &str, + ) -> &[crate::model::CompiledMembershipBoundary] { + self.target_memberships + .get(entity) + .map(Vec::as_slice) + .unwrap_or_default() + } + /// Name the issuer that verified the caller. Its keys and proposals are /// recorded under it. An issuer in the engine's reserved namespace is /// refused. @@ -617,6 +649,25 @@ impl ClaimContext { entity: &crate::model::CompiledEntity, row: &serde_json::Map, record_id: Uuid, + ) -> Result { + self.authorizes_record_snapshot_at(entity, row, record_id, false) + } + + pub(crate) fn authorizes_record_snapshot_before_allocation( + &self, + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + ) -> Result { + self.authorizes_record_snapshot_at(entity, row, record_id, true) + } + + fn authorizes_record_snapshot_at( + &self, + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + before_allocation: bool, ) -> Result { self.validate()?; if entity.id != self.entity_id { @@ -625,13 +676,23 @@ impl ClaimContext { // A state the profile may not see is outside its boundary, as the // restrictive disclosure policies would refuse it. A state that // cannot be evaluated counts as withheld. - if crate::disclosure::plan(entity, &self.access_profile) - .withholds_record(row) - .unwrap_or(true) - { + let disclosure = crate::disclosure::plan(entity, &self.access_profile); + let withheld = if before_allocation { + disclosure.withholds_record_before_allocation(row) + } else { + disclosure.withholds_record(row) + }; + if withheld.unwrap_or(true) { return Ok(false); } - snapshot_matches_boundaries(entity, row, record_id, &self.row_boundaries) + snapshot_matches_selected_boundaries( + entity, + row, + record_id, + self.row_boundaries + .iter() + .filter(|boundary| !before_allocation || !is_allocated_field(entity, boundary)), + ) } } @@ -727,6 +788,7 @@ pub(crate) struct ImmediateActionTargetContext { lock_only: bool, application_id: Option, target_row_boundaries: Vec, + membership_boundaries: Vec, timer: Option, canonical_context: String, } @@ -801,6 +863,10 @@ impl ImmediateActionTargetContext { &target_boundaries, &target_grant.row_boundaries, )?; + let membership_boundaries = action_claims.target_membership(&binding.target_entity_id); + if membership_boundaries != target_grant.membership_boundaries { + return Err(invalid_context()); + } let mut context = Self { action_id: binding.action_id, contract_fingerprint: binding.contract_fingerprint, @@ -817,6 +883,7 @@ impl ImmediateActionTargetContext { lock_only: binding.lock_only, application_id: binding.application_id, target_row_boundaries: target_boundaries, + membership_boundaries: membership_boundaries.to_vec(), timer: None, canonical_context: String::new(), }; @@ -925,6 +992,7 @@ impl ImmediateActionTargetContext { lock_only: binding.lock_only, application_id: binding.application_id, target_row_boundaries: Vec::new(), + membership_boundaries: Vec::new(), timer: Some(TimerActionTargetAuthority { timer_id: timer.id.clone(), target_input_id: None, @@ -1041,6 +1109,7 @@ impl ImmediateActionTargetContext { lock_only: binding.lock_only, application_id: binding.application_id, target_row_boundaries: Vec::new(), + membership_boundaries: Vec::new(), timer: Some(TimerActionTargetAuthority { timer_id: timer.id.clone(), target_input_id: target_input_id.map(str::to_owned), @@ -1061,11 +1130,41 @@ impl ImmediateActionTargetContext { Ok(context) } + pub(crate) fn membership_boundaries(&self) -> &[crate::model::CompiledMembershipBoundary] { + &self.membership_boundaries + } + #[must_use] pub(crate) fn canonical_context(&self) -> &str { &self.canonical_context } + pub(crate) fn authorize_create_before_allocation( + &self, + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + ) -> Result<()> { + self.validate()?; + if self.operation != Operation::Create + || entity.id != self.target_entity_id + || record_id != self.target_record_id + { + return Err(invalid_context()); + } + if !snapshot_matches_selected_boundaries( + entity, + row, + record_id, + self.target_row_boundaries + .iter() + .filter(|boundary| !is_allocated_field(entity, boundary)), + )? { + return Err(invalid_context()); + } + Ok(()) + } + pub(crate) fn authorize_rows( &self, target_entity: &crate::model::CompiledEntity, @@ -1311,6 +1410,7 @@ pub(crate) struct ImmediateActionLinkContext { target_entity_id: String, target_record_id: Uuid, target_row_boundaries: Vec, + membership_boundaries: Vec, canonical_context: String, } @@ -1383,6 +1483,10 @@ impl ImmediateActionLinkContext { &target_boundaries, &target_grant.row_boundaries, )?; + let membership_boundaries = action_claims.target_membership(&binding.target_entity_id); + if membership_boundaries != target_grant.membership_boundaries { + return Err(invalid_context()); + } let mut context = Self { action_id: binding.action_id, contract_fingerprint: binding.contract_fingerprint, @@ -1395,6 +1499,7 @@ impl ImmediateActionLinkContext { target_entity_id: binding.target_entity_id, target_record_id: binding.target_record_id, target_row_boundaries: target_boundaries, + membership_boundaries: membership_boundaries.to_vec(), canonical_context: String::new(), }; context.canonical_context = Self::canonicalize(&context)?; @@ -1402,6 +1507,10 @@ impl ImmediateActionLinkContext { Ok(context) } + pub(crate) fn membership_boundaries(&self) -> &[crate::model::CompiledMembershipBoundary] { + &self.membership_boundaries + } + #[must_use] pub(crate) fn canonical_context(&self) -> &str { &self.canonical_context @@ -1653,6 +1762,25 @@ pub(crate) fn snapshot_matches_boundaries( row: &serde_json::Map, record_id: Uuid, boundaries: &[RowBoundaryContext], +) -> Result { + snapshot_matches_selected_boundaries(entity, row, record_id, boundaries) +} + +fn is_allocated_field( + entity: &crate::model::CompiledEntity, + boundary: &RowBoundaryContext, +) -> bool { + entity + .fields + .get(boundary.field()) + .is_some_and(|field| field.generate.is_some()) +} + +fn snapshot_matches_selected_boundaries<'a>( + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + boundaries: impl IntoIterator, ) -> Result { for boundary in boundaries { let (actual, field_type) = if boundary.field() == entity.canonical_id.id { @@ -1874,21 +2002,7 @@ impl GuardedTransaction<'_> { /// outruns the budget fails its read instead of holding the shared /// Registry lock and a pooled connection for an unbounded time. pub(crate) async fn set_statement_budget(&self, budget: Duration) -> Result<()> { - if budget.is_zero() || budget > Duration::from_secs(30) { - return Err(PostgresKernelError::Configuration( - "statement budget must be between 1 millisecond and 30 seconds", - )); - } - let budget_millis = i32::try_from(budget.as_millis()).map_err(|_| { - PostgresKernelError::Configuration("statement budget is outside PostgreSQL bounds") - })?; - self.transaction - .execute( - "SELECT set_config('statement_timeout', $1::text, true)", - &[&format!("{budget_millis}ms")], - ) - .await?; - Ok(()) + set_transaction_statement_budget(&self.transaction, budget).await } pub async fn commit(self) -> Result<()> { @@ -1934,6 +2048,27 @@ impl GuardedTransaction<'_> { } } +pub(crate) async fn set_transaction_statement_budget( + transaction: &Transaction<'_>, + budget: Duration, +) -> Result<()> { + if budget.is_zero() || budget > Duration::from_secs(30) { + return Err(PostgresKernelError::Configuration( + "statement budget must be between 1 millisecond and 30 seconds", + )); + } + let budget_millis = i32::try_from(budget.as_millis()).map_err(|_| { + PostgresKernelError::Configuration("statement budget is outside PostgreSQL bounds") + })?; + transaction + .execute( + "SELECT set_config('statement_timeout', $1::text, true)", + &[&format!("{budget_millis}ms")], + ) + .await?; + Ok(()) +} + #[derive(Debug)] pub(crate) enum RegistryLockFailure { Timeout, @@ -1966,7 +2101,17 @@ pub(crate) async fn begin_registry_transaction<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, ) -> Result> { - begin_registry_transaction_with_reason(client, lock_key, lock_timeout, expected) + begin_registry_transaction_at_isolation(client, lock_key, lock_timeout, expected, None).await +} + +async fn begin_registry_transaction_at_isolation<'a>( + client: &'a mut Client, + lock_key: RegistryLockKey, + lock_timeout: Duration, + expected: &ExpectedRegistryIdentity, + isolation: Option, +) -> Result> { + begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, false, isolation) .await .map_err(|error| match error { RegistryTransactionError::Kernel(error) => error, @@ -1987,7 +2132,7 @@ pub(crate) async fn begin_registry_transaction_with_reason<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, ) -> std::result::Result, RegistryTransactionError> { - begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, false).await + begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, false, None).await } pub(crate) async fn begin_registry_read_transaction_with_reason<'a>( @@ -1996,7 +2141,7 @@ pub(crate) async fn begin_registry_read_transaction_with_reason<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, ) -> std::result::Result, RegistryTransactionError> { - begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, true).await + begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, true, None).await } async fn begin_registry_transaction_inner<'a>( @@ -2005,6 +2150,7 @@ async fn begin_registry_transaction_inner<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, read_only: bool, + isolation: Option, ) -> std::result::Result, RegistryTransactionError> { expected.validate()?; if lock_timeout.is_zero() || lock_timeout > Duration::from_secs(30) { @@ -2013,7 +2159,16 @@ async fn begin_registry_transaction_inner<'a>( ) .into()); } - let transaction = client.transaction().await?; + let transaction = match isolation { + Some(level) => { + client + .build_transaction() + .isolation_level(level) + .start() + .await? + } + None => client.transaction().await?, + }; if read_only { transaction .batch_execute("SET TRANSACTION READ ONLY") @@ -2050,6 +2205,15 @@ async fn begin_registry_transaction_inner<'a>( _ => RegistryLockFailure::Database, }) })?; + verify_registry_transaction_identity(&transaction, lock_key, expected).await?; + Ok(GuardedTransaction { transaction }) +} + +pub(crate) async fn verify_registry_transaction_identity( + transaction: &tokio_postgres::Transaction<'_>, + lock_key: RegistryLockKey, + expected: &ExpectedRegistryIdentity, +) -> std::result::Result<(), RegistryTransactionError> { let state = transaction .query_typed_opt( "SELECT package_id, database_id, active_package_digest, @@ -2071,11 +2235,11 @@ async fn begin_registry_transaction_inner<'a>( if !ready { return Err(PostgresKernelError::RegistryUnavailable.into()); } - let timer_protocol = super::timer::read_timer_protocol(&*transaction).await?; + let timer_protocol = super::timer::read_timer_protocol(transaction).await?; if timer_protocol.protocol_version != super::timer::SUPPORTED_TIMER_PROTOCOL_VERSION { return Err(RegistryTransactionError::TimerProtocolUnsupported); } - Ok(GuardedTransaction { transaction }) + Ok(()) } /// Starts a record transaction and installs authority only after the shared @@ -2086,9 +2250,29 @@ pub async fn begin_record_transaction<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, claims: &ClaimContext, +) -> Result> { + begin_record_transaction_for_write(client, lock_key, lock_timeout, expected, claims, false) + .await +} + +pub(crate) async fn begin_record_transaction_for_write<'a>( + client: &'a mut Client, + lock_key: RegistryLockKey, + lock_timeout: Duration, + expected: &ExpectedRegistryIdentity, + claims: &ClaimContext, + locks_membership: bool, ) -> Result> { claims.validate()?; - let guarded = begin_registry_transaction(client, lock_key, lock_timeout, expected).await?; + let isolation = locks_membership.then_some(IsolationLevel::ReadCommitted); + let guarded = begin_registry_transaction_at_isolation( + client, + lock_key, + lock_timeout, + expected, + isolation, + ) + .await?; let transaction = guarded.transaction(); // A JSON array of strings; `[]` for a client no organization lists. let recipients = serde_json::to_string(&claims.recipients).map_err(|_| invalid_context())?; @@ -2122,9 +2306,29 @@ pub async fn begin_action_transaction<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, claims: &ActionClaimContext, +) -> Result> { + begin_action_transaction_for_write(client, lock_key, lock_timeout, expected, claims, false) + .await +} + +pub(crate) async fn begin_action_transaction_for_write<'a>( + client: &'a mut Client, + lock_key: RegistryLockKey, + lock_timeout: Duration, + expected: &ExpectedRegistryIdentity, + claims: &ActionClaimContext, + locks_membership: bool, ) -> Result> { claims.validate()?; - let guarded = begin_registry_transaction(client, lock_key, lock_timeout, expected).await?; + let isolation = locks_membership.then_some(IsolationLevel::ReadCommitted); + let guarded = begin_registry_transaction_at_isolation( + client, + lock_key, + lock_timeout, + expected, + isolation, + ) + .await?; let transaction = guarded.transaction(); transaction .execute( @@ -2643,10 +2847,10 @@ mod tests { "disclosureConditions":{"hide": {"when":[{"type":"field-equals","field":"level","value":"secret"}], "withhold":"record","exemptProfiles":["officer"]}}}}, "accessProfiles":{ - "clerk": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "clerk": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{"recordType":"entry","operations":["get","create"], "rowBoundaries":"unrestricted","readableFields":["level"],"writableFields":["level"]}]}}, - "officer": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "officer": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{"recordType":"entry","operations":["get","create"], "rowBoundaries":"unrestricted","readableFields":["level"],"writableFields":["level"]}]}}}}); let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) @@ -3105,7 +3309,7 @@ mod tests { "accessProfiles":{"contact-registrar": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["contact-registration"], "permissions":{"actions":[{ "action":"rename-household-local", diff --git a/crates/registry-breg/src/postgres/interlock.rs b/crates/registry-breg/src/postgres/interlock.rs index 23a1a5c55d..714364d6b4 100644 --- a/crates/registry-breg/src/postgres/interlock.rs +++ b/crates/registry-breg/src/postgres/interlock.rs @@ -5171,7 +5171,7 @@ mod tests { "accessProfiles": {"caseworker": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "case", "rowBoundaries": "unrestricted", diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index 85d0e9d571..73c838c427 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -56,9 +56,10 @@ pub use config::{ TlsPolicy, }; pub(crate) use context::{ - begin_action_transaction, begin_timer_action_transaction, snapshot_matches_boundaries, - ActionClaimContext, ImmediateActionLinkBinding, ImmediateActionLinkContext, - ImmediateActionTargetBinding, ImmediateActionTargetContext, + begin_action_transaction, begin_action_transaction_for_write, + begin_record_transaction_for_write, begin_timer_action_transaction, + snapshot_matches_boundaries, ActionClaimContext, ImmediateActionLinkBinding, + ImmediateActionLinkContext, ImmediateActionTargetBinding, ImmediateActionTargetContext, }; pub(crate) use context::{ begin_proposal_transaction, ProposalAuthority, ProposalAuthorityOperation, ProposalTargetPhase, @@ -69,7 +70,8 @@ pub use context::{ }; pub(crate) use context::{ begin_registry_read_transaction_with_reason, begin_registry_transaction, - begin_registry_transaction_with_reason, RegistryLockFailure, RegistryTransactionError, + begin_registry_transaction_with_reason, set_transaction_statement_budget, + verify_registry_transaction_identity, RegistryLockFailure, RegistryTransactionError, }; pub(crate) use context::{install_spatial_bbox_context, validate_field_value, SpatialBboxContext}; pub use failure::PostgresFailure; @@ -102,7 +104,7 @@ pub(crate) use migration_ledger::{ MigrationLedgerEntry, MigrationLedgerStep, MigrationLedgerStepKind, }; pub use migration_ledger::{ActivationPlanKind, RoleMode}; -pub(crate) use mutation::api_boundary; +pub(crate) use mutation::{api_boundary, ActionTargetMembershipObservation}; pub use mutation::{ IngestionChunkSubmitInput, IngestionRunCreateInput, IngestionRunListQuery, IngestionServiceError, PostgresRecordMutationService, diff --git a/crates/registry-breg/src/postgres/mutation.rs b/crates/registry-breg/src/postgres/mutation.rs index 137268056e..5581e71731 100644 --- a/crates/registry-breg/src/postgres/mutation.rs +++ b/crates/registry-breg/src/postgres/mutation.rs @@ -37,6 +37,13 @@ use super::{ pub(super) const REQUEST_ACTION_TIMEOUT: Duration = Duration::from_secs(30); +pub(crate) enum ActionTargetMembershipObservation { + Authorized, + OutsideBoundary, + Withheld, + Missing, +} + fn action_timeout_for_http_deadline(http_request_timeout: Duration) -> Duration { REQUEST_ACTION_TIMEOUT.min(http_request_timeout) } @@ -434,6 +441,7 @@ impl PostgresRecordMutationService { deadline, self.coordinator.execute_immediate_action( guard.client(), + &self.pool, &self.registry, input, &claims, @@ -561,6 +569,92 @@ impl PostgresRecordMutationService { result } + pub(crate) async fn observe_action_target_membership( + &self, + context: &AuthorizedRequestContext, + entity: &crate::model::CompiledEntity, + record: uuid::Uuid, + revision: i64, + memberships: &[crate::model::CompiledMembershipBoundary], + disclosed_fields: &std::collections::BTreeSet, + ) -> Result { + let claims = strict_claim_context(&self.registry, context, &entity.id)?; + let client = self + .pool + .get() + .await + .map_err(|_| MutationError::Unavailable)?; + let mut guard = QueryCancellationGuard::new(self.pool.clone(), client); + let guarded = super::begin_record_transaction( + guard.client(), + self.lock_key, + self.lock_timeout, + &self.expected, + &claims, + ) + .await + .map_err(|_| MutationError::Unavailable)?; + let predicates = memberships + .iter() + .map(|boundary| { + let probe = crate::membership::RowProbe { + function: crate::membership::target_function_name( + claims.access_profile(), + &boundary.membership_entity, + ), + field: boundary.field.clone(), + form: crate::membership::RowProbeForm::PerKey, + }; + probe.sql(&format!( + "\"{}\"", + entity.fields[&probe.field].physical_name + )) + }) + .collect::>() + .join(" AND "); + let disclosure = crate::disclosure::plan(entity, claims.access_profile()); + let mut withholds = disclosure + .conditions() + .iter() + .filter_map(|condition| { + let crate::model::DisclosureWithhold::Fields(fields) = &condition.withhold else { + return None; + }; + (!fields.is_disjoint(disclosed_fields)).then(|| { + crate::disclosure::when_sql(entity, &condition.when, &|field| { + format!("\"{}\"", entity.fields[field].physical_name) + }) + }) + }) + .collect::>(); + withholds.push("false".into()); + let withheld = withholds.join(" OR "); + // Check the Action's boundary on the same revision as the ordinary + // GET. Evaluate field withholding only for an admitted target. + let sql = format!( + "SELECT CASE WHEN ({predicates}) IS NOT TRUE THEN false + WHEN ({withheld}) IS TRUE THEN NULL + ELSE true END + FROM registry_data.\"{}\" WHERE record_id=$1 AND record_revision=$2 AND record_lifecycle='active'", + entity.physical_table, + ); + let row = guarded + .transaction() + .query_opt(&sql, &[&record, &revision]) + .await + .map_err(|_| MutationError::Unavailable)?; + drop(guarded); + guard.disarm(); + let Some(row) = row else { + return Ok(ActionTargetMembershipObservation::Missing); + }; + match row.try_get(0).map_err(|_| MutationError::Unavailable)? { + Some(true) => Ok(ActionTargetMembershipObservation::Authorized), + Some(false) => Ok(ActionTargetMembershipObservation::OutsideBoundary), + None => Ok(ActionTargetMembershipObservation::Withheld), + } + } + pub async fn action_target_conditions( &self, input: ActionTargetConditionsInput<'_>, @@ -1904,6 +1998,7 @@ impl PostgresRecordMutationService { return self .finish_ingestion_submission( context, + correlation, &input, self.coordinator .execute_batch_with_fault(&mut writer, request, fault) @@ -1913,6 +2008,7 @@ impl PostgresRecordMutationService { } self.finish_ingestion_submission( context, + correlation, &input, self.coordinator.execute_batch(&mut writer, request).await, ) @@ -2010,6 +2106,7 @@ impl PostgresRecordMutationService { async fn finish_ingestion_submission( &self, context: &AuthorizedRequestContext, + correlation: &RequestCorrelation, input: &IngestionChunkSubmitInput, outcome: Result, ) -> Result { @@ -2054,6 +2151,13 @@ impl PostgresRecordMutationService { IngestionAttemptOutcome::InvalidItem, Some(IngestionServiceError::RequestInvalid), ), + MutationError::MembershipPreconditionFailed + | MutationError::MembershipWriteOutsideBoundary => { + crate::correlation::record_refusal_check( + registry_platform_authcommon::FailedCheck::Membership, correlation, + ); + (IngestionAttemptOutcome::Refused, Some(IngestionServiceError::PreconditionFailed)) + } MutationError::PreconditionFailed | MutationError::ProposalTargetChanged | MutationError::FieldGuardFailed { .. } @@ -2076,6 +2180,7 @@ impl PostgresRecordMutationService { | MutationError::IdempotencyExpired | MutationError::Unavailable | MutationError::RetryableConflict + | MutationError::MembershipKeyDrift | MutationError::CommitUnresolved | MutationError::MigrationLockHeld | MutationError::PostureMismatch { .. } @@ -2447,7 +2552,11 @@ fn strict_action_context( context.purpose().map(str::to_owned), context.result_effects().clone(), ) - .map(|claims| claims.with_audit_context(context.audit_context().cloned())) + .map(|claims| { + claims + .with_target_memberships(context.target_memberships().clone()) + .with_audit_context(context.audit_context().cloned()) + }) .and_then(|claims| claims.with_verified_issuer(context.caller_issuer())) .and_then(|claims| match context.task_grant() { Some(binding) => claims.with_task_grant(binding.clone()), diff --git a/crates/registry-breg/src/postgres/proposal.rs b/crates/registry-breg/src/postgres/proposal.rs index 2d658246c1..9a804233f2 100644 --- a/crates/registry-breg/src/postgres/proposal.rs +++ b/crates/registry-breg/src/postgres/proposal.rs @@ -1646,27 +1646,21 @@ impl PostgresRecordMutationService { .await?; #[cfg(feature = "postgres-test")] self.pause_proposal_read_for_test().await; - match self - .coordinator - .authorize_proposal_document( - guarded.transaction(), - &self.registry, - &document, - authority, - ) - .await - { - Ok(()) => {} - Err( - MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed, - ) => { - guarded - .rollback() - .await - .map_err(|_| MutationError::Unavailable)?; - continue; - } - Err(error) => return Err(error), + if !link_readable( + self.coordinator + .authorize_proposal_document( + guarded.transaction(), + &self.registry, + &document, + authority, + ) + .await, + )? { + guarded + .rollback() + .await + .map_err(|_| MutationError::Unavailable)?; + continue; } // Only an authorized UUID may become a continuation. An extra // authorized candidate proves another bounded page is useful. @@ -1826,6 +1820,7 @@ mod tests { registry_platform_authcommon::FailedCheck::Ownership, ), MutationError::PreconditionFailed, + MutationError::MembershipPreconditionFailed, ] { assert_eq!(link_readable(Err(refusal)), Ok(false)); } diff --git a/crates/registry-breg/src/postgres/proposal_context.rs b/crates/registry-breg/src/postgres/proposal_context.rs index 54b88f1d9d..6e9f790e5e 100644 --- a/crates/registry-breg/src/postgres/proposal_context.rs +++ b/crates/registry-breg/src/postgres/proposal_context.rs @@ -3,7 +3,9 @@ //! Proposal grants are independent from Action start and record CRUD grants. use super::*; -use crate::model::{CompiledActionExecution, ProposalOperation, ProposalOwnership}; +use crate::model::{ + CompiledActionExecution, CompiledMembershipBoundary, ProposalOperation, ProposalOwnership, +}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ProposalAuthorityOperation { @@ -27,6 +29,7 @@ pub(crate) struct ProposalAuthority { pub(crate) ownership: Option, pub(crate) readable_review_progress: bool, pub(crate) targets: BTreeMap>, + target_memberships: BTreeMap>, pub(crate) task_grant: Option, pub(crate) proposal_scope: Option>, /// Whether this caller may receive applicant answers to review asks and @@ -80,9 +83,13 @@ impl ProposalAuthority { ownership = None; readable_review_progress = false; permission - .targets - .iter() - .map(|t| (t.entity_id.as_str(), &t.row_boundaries)) + .entity_target_locks() + .map(|t| { + ( + t.entity_id.as_str(), + (&t.row_boundaries, &t.membership_boundaries), + ) + }) .collect::>() } ProposalAuthorityOperation::Lifecycle(operation) => { @@ -96,7 +103,12 @@ impl ProposalAuthority { permission .targets .iter() - .map(|t| (t.entity_id.as_str(), &t.row_boundaries)) + .map(|t| { + ( + t.entity_id.as_str(), + (&t.row_boundaries, &t.membership_boundaries), + ) + }) .collect::>() } }; @@ -110,9 +122,15 @@ impl ProposalAuthority { boundaries, expected .get(entity_id.as_str()) - .ok_or_else(invalid_context)?, + .ok_or_else(invalid_context)? + .0, )?; } + let target_memberships = expected + .into_iter() + .filter(|(_, (_, memberships))| !memberships.is_empty()) + .map(|(id, (_, memberships))| (id.to_owned(), memberships.clone())) + .collect(); Ok(Self { common: ActionClaimContext::new( action_id.to_owned(), @@ -125,6 +143,7 @@ impl ProposalAuthority { ownership, readable_review_progress, targets, + target_memberships, task_grant: None, proposal_scope: None, receives_review_answers: false, @@ -250,6 +269,7 @@ impl ProposalAuthority { ownership: None, readable_review_progress: false, targets, + target_memberships: BTreeMap::new(), task_grant: None, proposal_scope: Some(BTreeSet::from([proposal_id])), receives_review_answers: false, @@ -269,6 +289,17 @@ impl ProposalAuthority { }) } + pub(crate) fn target_membership(&self, entity_id: &str) -> &[CompiledMembershipBoundary] { + self.target_memberships + .get(entity_id) + .map_or(&[], Vec::as_slice) + } + + pub(crate) fn locks_membership(&self) -> bool { + self.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Apply) + && !self.target_memberships.is_empty() + } + pub(crate) fn is_system(&self) -> bool { self.system.is_some() } @@ -295,6 +326,23 @@ impl ProposalAuthority { snapshot_matches_boundaries(entity, snapshot, id, boundaries) } + pub(crate) fn authorizes_create_before_allocation( + &self, + entity: &crate::model::CompiledEntity, + id: Uuid, + snapshot: &serde_json::Map, + ) -> Result { + let boundaries = self.targets.get(&entity.id).ok_or_else(invalid_context)?; + snapshot_matches_selected_boundaries( + entity, + snapshot, + id, + boundaries + .iter() + .filter(|boundary| !is_allocated_field(entity, boundary)), + ) + } + #[allow(clippy::too_many_arguments)] pub(crate) async fn install_target( &self, @@ -492,5 +540,13 @@ pub(crate) async fn begin_proposal_transaction<'a>( expected: &ExpectedRegistryIdentity, authority: &ProposalAuthority, ) -> Result> { - begin_action_transaction(client, lock_key, lock_timeout, expected, &authority.common).await + begin_action_transaction_for_write( + client, + lock_key, + lock_timeout, + expected, + &authority.common, + authority.locks_membership(), + ) + .await } diff --git a/crates/registry-breg/src/proposal_ddl.rs b/crates/registry-breg/src/proposal_ddl.rs index 8b70753088..46025c4b62 100644 --- a/crates/registry-breg/src/proposal_ddl.rs +++ b/crates/registry-breg/src/proposal_ddl.rs @@ -28,6 +28,7 @@ pub(super) fn target_policies( else { continue; }; + let first_policy = result.len(); add_read_policies( &mut result, entity, @@ -38,6 +39,12 @@ pub(super) fn target_policies( "preparation", "start", ); + crate::membership::append_target_probes( + entity, + &grant.profile_id, + &target.membership_boundaries, + &mut result[first_policy..], + ); } for grant in &proposal.permissions { let Some(target) = grant @@ -47,6 +54,7 @@ pub(super) fn target_policies( else { continue; }; + let first_policy = result.len(); for operation in &grant.operations { let name = match operation { ProposalOperation::Get => "get", @@ -101,6 +109,12 @@ pub(super) fn target_policies( ); } } + crate::membership::append_target_probes( + entity, + &grant.profile_id, + &target.membership_boundaries, + &mut result[first_policy..], + ); } if let Some(grant) = &proposal.system_apply_grant { add_system_policies(&mut result, entity, action, grant); diff --git a/crates/registry-breg/src/proposal_hooks.rs b/crates/registry-breg/src/proposal_hooks.rs index ccc015add8..49badf3851 100644 --- a/crates/registry-breg/src/proposal_hooks.rs +++ b/crates/registry-breg/src/proposal_hooks.rs @@ -263,9 +263,10 @@ fn exact_inventory(expected: &[CompiledEventDelivery], actual: &[&CompiledEventD }) } -#[cfg(all(test, feature = "runtime"))] +#[cfg(test)] #[path = "../tests/support/proposal_hooks_model.rs"] -mod test_model; +#[cfg_attr(not(feature = "runtime"), allow(dead_code))] +pub(crate) mod test_model; #[cfg(all(test, feature = "runtime"))] #[test] diff --git a/crates/registry-breg/src/proposal_prepare.rs b/crates/registry-breg/src/proposal_prepare.rs index de8392fccb..8de1d383a5 100644 --- a/crates/registry-breg/src/proposal_prepare.rs +++ b/crates/registry-breg/src/proposal_prepare.rs @@ -26,6 +26,8 @@ pub(crate) struct ResolvedProposalTargets { pub records: BTreeMap<(String, Uuid), Operation>, } +pub(crate) type ProposalPatchBases = BTreeMap<(String, Uuid), (i64, Map)>; + type ProposalCreateFields = BTreeMap<(String, Uuid), Map>; #[derive(Clone, Debug)] @@ -226,6 +228,65 @@ pub(crate) fn materialize_create_fields( Ok(creates) } +/// Check candidate boundaries before reserving generated identifiers. +pub(crate) async fn authorize_candidates_before_allocation( + tx: &tokio_postgres::Transaction<'_>, + registry: &CompiledRegistry, + authority: &crate::postgres::ProposalAuthority, + input: &Map, + resolved: &ResolvedProposalTargets, + creates: &ProposalCreateFields, + bases: &ProposalPatchBases, +) -> Result<(), MutationError> { + use crate::mutation::probe_action_memberships; + + let profile = authority.common.access_profile(); + for ((entity, id), snapshot) in creates { + let compiled = ®istry.entities()[entity]; + if !authority + .authorizes_create_before_allocation(compiled, *id, snapshot) + .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::PreconditionFailed); + } + probe_action_memberships(tx, profile, authority.target_membership(entity), snapshot) + .await?; + } + let mut patches = BTreeMap::new(); + for effect in resolved + .effects + .iter() + .filter(|effect| effect.operation == Operation::Patch) + { + let entity = &effect.target.entity_id; + let key = (entity.clone(), resolved.effect_records[&effect.id]); + let after = patches + .entry(key.clone()) + .or_insert_with(|| bases[&key].1.clone()); + for mutation in &effect.mutations { + match mutation { + CompiledPlanMutation::Set { field, value } => { + after.insert(field.clone(), resolve_plan_value(input, resolved, value)?); + } + CompiledPlanMutation::Clear { field } => { + after.insert(field.clone(), Value::Null); + } + } + } + } + for ((entity, id), snapshot) in patches { + if !authority + .authorizes_snapshot(®istry.entities()[&entity], id, &snapshot) + .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::PreconditionFailed); + } + probe_action_memberships(tx, profile, authority.target_membership(&entity), &snapshot) + .await?; + } + Ok(()) +} + fn resolve_plan_value( input: &Map, resolved: &ResolvedProposalTargets, @@ -269,7 +330,7 @@ pub(crate) fn prepare( input_revision: i64, package_fingerprint: &str, resolved: &ResolvedProposalTargets, - bases: BTreeMap<(String, Uuid), (i64, Map)>, + bases: ProposalPatchBases, guard_bases: BTreeMap)>, ) -> Result { let create_fields = materialize_create_fields(registry, input, resolved)?; @@ -295,7 +356,7 @@ pub(crate) fn prepare_with_reserved_create_fields( package_fingerprint: &str, resolved: &ResolvedProposalTargets, reserved_create_fields: BTreeMap<(String, Uuid), Map>, - bases: BTreeMap<(String, Uuid), (i64, Map)>, + bases: ProposalPatchBases, guard_bases: BTreeMap)>, ) -> Result { let CompiledActionExecution::Proposal { proposal: policy } = &action.execution else { diff --git a/crates/registry-breg/src/proposal_prepare/tests.rs b/crates/registry-breg/src/proposal_prepare/tests.rs index 554f1d1888..a50275c1ce 100644 --- a/crates/registry-breg/src/proposal_prepare/tests.rs +++ b/crates/registry-breg/src/proposal_prepare/tests.rs @@ -33,7 +33,7 @@ fn source(effects: Value) -> Value { {"id":"two","type":"reference","target":"target","classification":"internal"}, {"id":"value","type":"string","maximumLength":64,"required":true,"classification":"internal"} ],"plan":{"type":"fixed","effects":effects}}}, - "accessProfiles":{"submitter": {"default":true,"principalClaim":"sub","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"submitter": {"default":true,"principalClaim":"sub","requiredScopes":["proposals:write"],"permissions":{ "actions":[{"action":"change-target","operations":["start"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}], "proposals":[{"action":"change-target","operations":["get","submit","apply"],"ownership":"caller","targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}] }}} diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index 9adc280ea2..92756e7d6e 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -5477,6 +5477,80 @@ mod tests { use super::RuntimeConfigError; use crate::attachment_verification_worker::ATTEMPT_BUDGET; + fn open_membership_registry() -> crate::CompiledRegistry { + use serde_json::{json, Value}; + let mut source: Value = serde_json::from_str(include_str!( + "../../../products/breg/fixtures/organization-membership-access/registry.yaml" + )) + .unwrap(); + source["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + source["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("steward"); + source["accessProfiles"]["member"]["principalClaim"] = json!("sub"); + source["accessProfiles"]["member"]["requiredScopes"] = json!("unrestricted"); + let project = crate::parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + crate::compile_project(&project, &[], crate::CompileProfile::Authoring).unwrap() + } + + fn membership_runtime(two_issuers: bool) -> super::RuntimeConfig { + use registry_platform_config::{DeclaredPosture, Posture, PostureSource}; + let example = include_str!("../../../products/breg/examples/minimal/runtime.example.yaml"); + let mut runtime = example.replace("principal: registry_principal", "principal: sub"); + let first = runtime.find(" primary:\n").unwrap(); + let end = runtime.find(" authorityClaims:\n").unwrap(); + let definition = format!("{} actorKind: human\n", &runtime[first..end]); + let mut issuers = definition.clone(); + if two_issuers { + issuers.push_str( + &definition + .replace("primary:", "second:") + .replace( + "https://issuer.example.com", + "https://other-issuer.example.com", + ) + .replace("directory-client", "second-directory-client"), + ); + } + runtime.replace_range(first..end, &issuers); + super::parse_runtime_config( + &runtime, + DeclaredPosture { + posture: Posture::Development, + source: PostureSource::Flag, + }, + ) + .unwrap() + } + + #[test] + fn a_membership_bounded_profile_reachable_from_two_issuers_refuses_at_startup() { + let runtime = membership_runtime(true); + let diagnostics = runtime.authentication().access_profile_diagnostics( + &open_membership_registry(), + None, + None, + ); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].code, "breg.runtime.principal-across-issuers"); + } + + #[test] + fn an_open_profile_bounded_by_membership_is_not_listed_as_scopeless_without_subject_rule() { + let runtime = membership_runtime(false); + let registry = open_membership_registry(); + let settings = runtime + .authentication() + .combination_posture_settings(®istry); + assert!(!settings + .iter() + .any(|found| found.setting.code == "breg.posture.scopeless-without-subject-rule")); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping diff --git a/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs b/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs index 69254954a5..466a93b59b 100644 --- a/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs +++ b/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs @@ -51,7 +51,7 @@ fn acceptance_action() -> CompiledAction { "plan":{"type":"function","function":"register-plan","inputs":["identifier","given-name","family-name"], "refusals":[{"code":"blank-name","label":"At least one name part is required."}], "writes":[{"id":"person","target":{"recordType":"person"},"operation":"create","fields":["identifier","display-name"]}]}}}, - "accessProfiles":{"writer": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[ + "accessProfiles":{"writer": {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[ {"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); @@ -105,7 +105,7 @@ fn characterization_action(script: &str) -> CompiledAction { "refusals":[{"code":"blank-label","label":"A label is required."}], "writes":[{"id":"record","target":{"recordType":"record"},"operation":"create","fields":["label","count","amount"]}] }}}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "actions":[ {"action":"register-record","operations":["invoke"],"targets":[{"recordType":"record","rowBoundaries":"unrestricted"}],"results":["record"]} ] diff --git a/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs b/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs index 0060e78f8f..d6cf199550 100644 --- a/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs +++ b/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs @@ -57,7 +57,7 @@ fn person_action(script: &str) -> CompiledAction { {"id":"friend","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]}, {"id":"existing","target":{"fromInput":"person"},"operation":"patch","fields":["name","friend"]} ]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); compile_project_with_assets( @@ -101,7 +101,7 @@ fn record_action(script: &str) -> CompiledAction { ],"plan":{"type":"function","function":"record-plan","inputs":["label","count","amount"],"refusals":[{"code":"blank-label","label":"A label is required."}], "writes":[{"id":"record","target":{"recordType":"record"},"operation":"create","fields":["label","count","amount"]}] }}}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "actions":[ {"action":"register-record","operations":["invoke"],"targets":[{"recordType":"record","rowBoundaries":"unrestricted"}],"results":["record"]} ] diff --git a/crates/registry-breg/src/tests/wasm_runtime_tests.rs b/crates/registry-breg/src/tests/wasm_runtime_tests.rs index 792fdb73c2..603ad24374 100644 --- a/crates/registry-breg/src/tests/wasm_runtime_tests.rs +++ b/crates/registry-breg/src/tests/wasm_runtime_tests.rs @@ -153,7 +153,7 @@ fn wasm_person_action(module_bytes: &[u8]) -> CompiledAction { ],"plan":{"type":"function","function":"person-plan","inputs":["given-name","family-name","person"],"refusals":[{"code":"blank-name","label":"A name is required."}],"writes":[ {"id":"person","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]} ]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); compile_project_with_assets( diff --git a/crates/registry-breg/src/tooling.rs b/crates/registry-breg/src/tooling.rs index 5ef0f2222a..80b0984c83 100644 --- a/crates/registry-breg/src/tooling.rs +++ b/crates/registry-breg/src/tooling.rs @@ -587,6 +587,7 @@ fn action_details( let Some(before) = before else { return details; }; + details.extend(target_boundary_details(&before, &after)); let codes = |input: &crate::model::CompiledActionInput| match &input.field_type { crate::contract::FieldTypeSource::VocabularyCode { values, .. } => json!(values), _ => Value::Null, @@ -620,6 +621,84 @@ fn action_details( details } +fn target_boundary_details( + before: &crate::model::CompiledAction, + after: &crate::model::CompiledAction, +) -> Vec { + use crate::model::CompiledActionExecution; + use serde_json::json; + + let mut details = Vec::new(); + let mut compare = |profile: &str, entity: &str, surface: &str, before, after| { + details.extend( + object_details(&before, &after, |field, left, right| { + (access_direction(field, left, right), None) + }) + .into_iter() + .map(|mut detail| { + detail.reason = Some(format!("{surface} target {entity} in profile {profile}")); + detail + }), + ); + }; + for grant in &before.permissions { + let Some(next) = after + .permissions + .iter() + .find(|next| next.profile_id == grant.profile_id) + else { + continue; + }; + for target in grant.entity_target_locks() { + let Some(other) = next + .entity_target_locks() + .find(|other| other.entity_id == target.entity_id) + else { + continue; + }; + compare( + &grant.profile_id, + &target.entity_id, + "Action", + json!({"rowBoundaries": target.row_boundaries, "membershipBoundaries": target.membership_boundaries}), + json!({"rowBoundaries": other.row_boundaries, "membershipBoundaries": other.membership_boundaries}), + ); + } + } + if let ( + CompiledActionExecution::Proposal { proposal: before }, + CompiledActionExecution::Proposal { proposal: after }, + ) = (&before.execution, &after.execution) + { + for grant in &before.permissions { + let Some(next) = after + .permissions + .iter() + .find(|next| next.profile_id == grant.profile_id) + else { + continue; + }; + for target in &grant.targets { + let Some(other) = next + .targets + .iter() + .find(|other| other.entity_id == target.entity_id) + else { + continue; + }; + compare( + &grant.profile_id, + &target.entity_id, + "Proposal", + json!({"rowBoundaries": target.row_boundaries, "membershipBoundaries": target.membership_boundaries}), + json!({"rowBoundaries": other.row_boundaries, "membershipBoundaries": other.membership_boundaries}), + ); + } + } + } + details +} + fn access_direction( field: &str, before: &serde_json::Value, diff --git a/crates/registry-breg/tests/access_explanation.rs b/crates/registry-breg/tests/access_explanation.rs index 297fe26786..10fae86c02 100644 --- a/crates/registry-breg/tests/access_explanation.rs +++ b/crates/registry-breg/tests/access_explanation.rs @@ -150,11 +150,9 @@ fn membership_source() -> Value { let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["records"][0]; grant["operations"] = json!(["get", "list"]); grant["writableFields"] = json!([]); - grant["rowBoundaries"] = json!("unrestricted"); - grant["membershipBoundaries"] = json!([{ - "field":"organization", "membershipRecordType":"membership", - "membershipKeyField":"organization", "principalField":"principal", "activeField":"active" - }]); + grant["rowBoundaries"] = json!([{"field":"organization","membership":"membership"}]); + source["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); source } @@ -501,7 +499,7 @@ fn function_action_target_authority_uses_the_compiled_write_ceiling() { #[test] fn membership_row_reach_is_explicit_and_uses_the_selected_principal() { for (boundaries, rows, direct_claims) in [ - (json!("unrestricted"), "membership_bound", 0), + (json!([]), "membership_bound", 0), ( json!([{"field":"district", "claim":"districts", "operator":"in"}]), "claim_and_membership_bound", @@ -509,8 +507,11 @@ fn membership_row_reach_is_explicit_and_uses_the_selected_principal() { ), ] { let mut source = membership_source(); - source["accessProfiles"]["clerk"]["permissions"]["records"][0]["rowBoundaries"] = - boundaries.clone(); + let authored = + &mut source["accessProfiles"]["clerk"]["permissions"]["records"][0]["rowBoundaries"]; + if let Some(claims) = boundaries.as_array() { + authored.as_array_mut().unwrap().extend_from_slice(claims); + } let registry = compile(&source); let explanation = registry_breg::access::explain_access(®istry); let inspected = serde_json::to_value(&explanation).unwrap(); @@ -529,7 +530,10 @@ fn membership_row_reach_is_explicit_and_uses_the_selected_principal() { .unwrap(); assert_eq!(reach.rows, rows); assert_eq!(reach.membership_boundaries.len(), 1); - assert_eq!(reach.membership_boundaries[0].principal_field, "principal"); + assert_eq!( + serde_json::to_value(&reach.membership_boundaries[0]).unwrap()["principalField"], + "principal" + ); assert!(!registry.findings().iter().any(|finding| matches!( finding.code.as_str(), "breg.access.profile-unrestricted-rows" | "breg.access.profile-unrestricted-collection" @@ -546,24 +550,28 @@ fn membership_changes_report_authority_narrowing_and_widening() { use registry_breg::tooling::{classify_registry_diff, AccessChangeDirection}; let mut source = membership_source(); - source["recordTypes"]["membership"]["fields"] + let mut additional = source["recordTypes"]["membership"].clone(); + additional["route"] = json!("additional-memberships"); + additional["fields"] .as_array_mut() .unwrap() .push(json!({"id":"approved", "type":"boolean", "classification":"internal"})); - let mut additional = source["accessProfiles"]["clerk"]["permissions"]["records"][0] - ["membershipBoundaries"][0] - .clone(); - additional["activeField"] = json!("approved"); + additional["membership"]["active"] = json!("approved"); + source["recordTypes"]["additional-membership"] = additional; let mut boundaries = source["accessProfiles"]["clerk"]["permissions"]["records"][0] - ["membershipBoundaries"] + ["rowBoundaries"] .as_array() .unwrap() .clone(); - boundaries.push(additional); + boundaries.push(json!({"field":"organization","membership":"additional-membership"})); let registries = (0..=2) .map(|count| { - source["accessProfiles"]["clerk"]["permissions"]["records"][0] - ["membershipBoundaries"] = json!(&boundaries[..count]); + source["accessProfiles"]["clerk"]["permissions"]["records"][0]["rowBoundaries"] = + if count == 0 { + json!("unrestricted") + } else { + json!(&boundaries[..count]) + }; compile(&source) }) .collect::>(); @@ -615,3 +623,96 @@ fn synthetic_own_record_preview_reuses_principal_and_refuses_identity_override() ) .is_err()); } + +#[allow(dead_code)] +#[path = "support/proposal_hooks_model.rs"] +mod proposal_hooks_model; + +fn compiled_with_target_membership( + mut registry: Value, + targets: &str, +) -> registry_breg::CompiledRegistry { + let member_registry = compile(&membership_source()); + let boundary = &member_registry.entities()["entry"].membership_boundaries["clerk"][0]; + registry["entities"]["membership"] = json!(member_registry.entities()["membership"]); + for target in registry + .pointer_mut(targets) + .unwrap() + .as_array_mut() + .unwrap() + { + target["membershipBoundaries"] = json!([boundary]); + } + serde_json::from_value(registry).unwrap() +} + +const ACTION_TARGETS: &str = "/actionInventory/actions/0/permissions/0/targets"; +const PROPOSAL_TARGETS: &str = + "/actionInventory/actions/0/execution/proposal/permissions/0/targets"; + +#[test] +fn explain_access_lists_membership_entries_on_action_targets() { + let baseline = compile(&repeated_action_target_source()); + let candidate = compiled_with_target_membership(json!(baseline), ACTION_TARGETS); + let explanation = registry_breg::access::explain_access(&candidate); + let target = explanation + .row_reach + .iter() + .find(|reach| reach.surface == "action_target") + .unwrap(); + assert_eq!(target.rows, "claim_and_membership_bound"); + assert_eq!(target.membership_boundaries.len(), 1); + assert_eq!( + json!(target.membership_boundaries[0]), + json!({ + "field":"organization", "membershipRecordType":"membership", + "membershipKeyField":"organization","principalField":"principal","activeField":"active" + }) + ); +} + +#[test] +fn explain_access_lists_membership_entries_on_proposal_targets() { + let baseline = compile(&proposal_hooks_model::source(json!([]))); + let candidate = compiled_with_target_membership(json!(baseline), PROPOSAL_TARGETS); + let explanation = registry_breg::access::explain_access(&candidate); + let target = explanation + .row_reach + .iter() + .find(|reach| reach.surface == "proposal_target") + .unwrap(); + assert_eq!(target.rows, "membership_bound"); + assert_eq!(target.membership_boundaries.len(), 1); + assert_eq!( + json!(target.membership_boundaries[0]), + json!({ + "field":"organization", "membershipRecordType":"membership", + "membershipKeyField":"organization","principalField":"principal","activeField":"active" + }) + ); +} + +#[cfg(all(feature = "runtime", feature = "tooling"))] +#[test] +fn adding_a_membership_entry_to_an_action_target_reads_as_narrowing() { + use registry_breg::tooling::{classify_registry_diff, AccessChangeDirection}; + let baseline = compile(&repeated_action_target_source()); + let candidate = compiled_with_target_membership(json!(baseline), ACTION_TARGETS); + for (before, after, expected) in [ + (&baseline, &candidate, AccessChangeDirection::Narrowing), + (&candidate, &baseline, AccessChangeDirection::Widening), + ] { + let diff = classify_registry_diff(before, after, "baseline"); + let details = diff + .changes + .iter() + .flat_map(|change| &change.access_details); + assert_eq!( + details + .filter(|detail| detail.field == "membershipBoundaries") + .map(|detail| detail.direction) + .collect::>(), + [expected], + ); + } +} diff --git a/crates/registry-breg/tests/access_log.rs b/crates/registry-breg/tests/access_log.rs index bf4e9c4d4e..9a19dc5ccf 100644 --- a/crates/registry-breg/tests/access_log.rs +++ b/crates/registry-breg/tests/access_log.rs @@ -73,7 +73,7 @@ fn source() -> Value { }, "writer": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "person", "operations": ["create"], diff --git a/crates/registry-breg/tests/action_evidence_compiler.rs b/crates/registry-breg/tests/action_evidence_compiler.rs index 97e7ffed1a..4f31df198a 100644 --- a/crates/registry-breg/tests/action_evidence_compiler.rs +++ b/crates/registry-breg/tests/action_evidence_compiler.rs @@ -28,7 +28,7 @@ fn project() -> Value { {"id":"friend","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]}, {"id":"existing","target":{"fromInput":"person"},"operation":"patch","fields":["name","friend"]} ]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} }) } diff --git a/crates/registry-breg/tests/action_handler_declaration.rs b/crates/registry-breg/tests/action_handler_declaration.rs index 8aba14a877..78a308ac22 100644 --- a/crates/registry-breg/tests/action_handler_declaration.rs +++ b/crates/registry-breg/tests/action_handler_declaration.rs @@ -18,7 +18,7 @@ fn project() -> Value { {"id":"unbound","type":"string","maximumLength":64,"classification":"restricted"}], "plan":{"type":"function","function":"person-plan","inputs":["code"], "writes":[{"id":"person","target":{"recordType":"person"},"operation":"create","fields":["code"]}]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} }) } diff --git a/crates/registry-breg/tests/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index c9ae286944..f5da8a3060 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -119,8 +119,8 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/organization-membership-access/registry.yaml" ), module: None, - ddl_sha256: "6d6431e3e4fb3eb254ef8f3b2e895aed2c09ed4ee7ca506627e1d063359f4578", - revision: "sha256:bae0a8d7f49ab9959743b39c1dacee918540abde36cfbabf065657d2cf13c1e4", + ddl_sha256: include_str!("golden/membership-ddl.sha256"), + revision: include_str!("golden/membership-revision.txt"), }, Fixture { name: "asset-registration-actions", @@ -168,6 +168,10 @@ fn compile(fixture: &Fixture) -> CompiledRegistry { fn ddl_sha256(registry: &CompiledRegistry) -> String { let bytes = serde_json::to_vec(registry.ddl()).expect("DDL inventory serializes"); + sha256(&bytes) +} + +fn sha256(bytes: &[u8]) -> String { Sha256::digest(bytes) .iter() .map(|byte| format!("{byte:02x}")) @@ -180,7 +184,9 @@ fn fixtures_without_consent_keep_their_exact_ddl_and_revision() { for fixture in FIXTURES { let registry = compile(fixture); let ddl = ddl_sha256(®istry); - if ddl != fixture.ddl_sha256 || registry.revision() != fixture.revision { + if ddl != fixture.ddl_sha256.trim_end() + || registry.revision() != fixture.revision.trim_end() + { drift.push(format!( "{}: ddl_sha256 {ddl}, revision {}", fixture.name, @@ -216,3 +222,131 @@ const ACTION_FINGERPRINTS: &[&str] = &[ "facility-registry-actions/transfer-facility: sha256:5f346eabb7d4a8f9bf959432ae47de3aaecaa07962d6fec954452848a31e84d4", "household-contact-actions/register-household-contact: sha256:cb90f8518169dafc15d6d66ca467e9f1093b5d04afe68c970d91b966e7f7c905", ]; + +#[test] +fn membership_fixture_compiles_to_the_recorded_ddl_and_access_inventory() { + let fixture = FIXTURES + .iter() + .find(|fixture| fixture.name == "organization-membership-access") + .expect("membership fixture is listed"); + let registry = compile(fixture); + let ddl = serde_json::to_string_pretty(registry.ddl()).expect("DDL serializes") + "\n"; + let access = serde_json::to_string_pretty(registry.access()) + .expect("access inventory serializes") + + "\n"; + if std::env::var("REGISTRY_BREG_WRITE_DDL_GOLDEN").as_deref() == Ok("1") { + let golden = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden"); + for (name, contents) in [ + ("membership-ddl.json", ddl), + ( + "membership-ddl.sha256", + format!("{}\n", ddl_sha256(®istry)), + ), + ( + "membership-revision.txt", + format!("{}\n", registry.revision()), + ), + ] { + std::fs::write(golden.join(name), contents).expect("membership golden writes"); + } + } else { + assert_eq!(ddl, include_str!("golden/membership-ddl.json")); + } + assert_eq!(access, include_str!("golden/membership-access.json")); +} + +#[test] +fn a_record_type_without_membership_compiles_to_the_same_bytes() { + let fixture = &FIXTURES[1]; + let registry = compile(fixture); + assert_eq!(registry.revision(), fixture.revision); + for entity in registry.entities().values() { + assert!(serde_json::to_value(entity) + .unwrap() + .get("membership") + .is_none()); + } +} + +#[test] +fn targets_without_membership_entries_generate_the_same_policies() { + for fixture in &FIXTURES[1..] { + let registry = compile(fixture); + assert_eq!(registry.revision(), fixture.revision); + assert_eq!(ddl_sha256(®istry), fixture.ddl_sha256); + let actions = serde_json::to_value(registry.actions()).unwrap(); + assert!(!actions.to_string().contains("membershipBoundaries")); + } +} + +const MEMBERSHIP_INDEX_ID: &str = "entity.membership.membership.key-index"; + +#[test] +fn a_membership_record_type_generates_its_partial_index() { + let registry = compile(&FIXTURES[0]); + let index = registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == MEMBERSHIP_INDEX_ID) + .unwrap(); + assert_eq!(index.sql, concat!( + "CREATE INDEX \"breg_membership_key_b9ee6c3037\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ", + "(\"breg_f_membership_organization_bfa076d486640343\", \"breg_f_membership_principal_dbfb37e169be4783\") ", + "WHERE \"breg_f_membership_active_6e662651da1918d2\" IS TRUE AND record_lifecycle = 'active'" + )); + assert!(registry + .ddl() + .statements + .iter() + .any(|statement| statement.id == "entity.membership.index.reference:organization")); +} + +#[test] +fn a_record_type_without_membership_generates_no_membership_index() { + for fixture in &FIXTURES[1..] { + let registry = compile(fixture); + assert!(registry + .ddl() + .statements + .iter() + .all(|statement| !statement.id.ends_with(".membership.key-index"))); + } +} + +#[cfg(feature = "runtime")] +#[test] +fn an_unchanged_membership_declaration_acquires_its_index_over_a_pre_index_baseline() { + use registry_breg::package::{ + change_set_to_applicable_migration_plan, compiled_registry_change_set_from_baseline, + CompiledRegistryMigrationBaseline, + }; + let registry = compile(&FIXTURES[0]); + let mut baseline = CompiledRegistryMigrationBaseline::from_compiled("prior", ®istry); + let mut old_ddl = registry.ddl().clone(); + old_ddl + .statements + .retain(|statement| statement.id != MEMBERSHIP_INDEX_ID); + let old_digest = format!("sha256:{}", sha256(old_ddl.script().as_bytes())); + assert_eq!( + old_digest, + "sha256:345e560f7390867c94444d031fd5d231bb55e720f3f14a1ede9bd215f98245b4" + ); + baseline.generated_ddl_sha256 = Some(old_digest); + let changes = compiled_registry_change_set_from_baseline(&baseline, ®istry, "prior"); + assert!(changes.changes.is_empty()); + let plan = change_set_to_applicable_migration_plan(&changes).unwrap(); + let statement = registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == MEMBERSHIP_INDEX_ID) + .unwrap(); + assert!(plan.statements.contains(statement)); + let probe = plan + .statements + .iter() + .find(|statement| statement.id.starts_with("registry_context.membership_")) + .unwrap(); + assert!(probe.sql.starts_with("CREATE OR REPLACE FUNCTION")); +} diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index a5f3d54153..819d1936ca 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -2146,7 +2146,7 @@ fn batch_route_requires_explicit_bounds_and_compiles_bounded_openapi() { "recordTypes":{{"record":{{"primaryDataset":"test-dataset","route":"records","mutationMode":"mutable"{batch}, "fields":[{{"id":"label","type":"string","maximumLength":32,"required":true,"classification":"internal"}}] }}}}, - "accessProfiles":{{"writer":{{"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{{"records":[{{ + "accessProfiles":{{"writer":{{"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{{"records":[{{ "rowBoundaries": "unrestricted", "recordType":"record","operations":{operations}, "readableFields":["label"],"writableFields":["label"] }}]}} @@ -3891,7 +3891,7 @@ fn independent_additive_modules_are_order_independent() { "recordTypes":{"object": {"primaryDataset":"test-dataset","route":"objects","mutationMode":"mutable", "fields":[{"id":"code","type":"string","maximumLength":32,"required":true,"classification":"internal"}] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"object","operations":["create","get","list","patch"], "readableFields":["code"],"writableFields":["code"], "rowBoundaries": "unrestricted" @@ -4760,7 +4760,7 @@ fn generic_decimal_crs84_point_and_structured_fields_compile_to_deterministic_dd }} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"reading","operations":["create","get","list","patch"], "readableFields":["amount","location","payload"], "writableFields":["amount","location","payload"], @@ -5292,7 +5292,7 @@ fn action_decimal_bound_diagnostic_names_capacity_and_preserves_valid_bounds() { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-entry", "operations": ["invoke"], @@ -6730,7 +6730,7 @@ fn generated_openapi_separates_security_and_mutation_input_from_read_schema() { }]} },"business": { "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["business"], "permissions":{"records":[{ "recordType":"business-record", @@ -7897,7 +7897,7 @@ fn revision_schemas_declare_the_proposal_link_only_for_a_registry_with_proposal_ "inputs":[{"id":"target","type":"reference","target":"target","required":true,"classification":"internal"}, {"id":"value","type":"string","required":true,"maximumLength":64,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"name","target":{"fromInput":"target"},"operation":"patch","set":{"name":{"fromInput":"value"}}}]}}}, - "accessProfiles":{"historian": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"historian": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "records":[{"recordType":"target","operations":["get","revisions"],"revisionAccess":true, "readableFields":["name"],"rowBoundaries":"unrestricted"}], "actions":[{"action":"correct-name","operations":[operation],"targets":targets}], diff --git a/crates/registry-breg/tests/compiler_statistics.rs b/crates/registry-breg/tests/compiler_statistics.rs index 5251512561..5fa3898b22 100644 --- a/crates/registry-breg/tests/compiler_statistics.rs +++ b/crates/registry-breg/tests/compiler_statistics.rs @@ -819,17 +819,16 @@ fn statistical_disclosure_bounds_are_refused_when_the_project_is_read() { } #[test] -fn statistical_dataset_refuses_caller_dependent_publisher_authority() { - assert_refused( - |value| { - value["recordTypes"]["record"]["fields"] - .as_array_mut() - .unwrap() - .push(json!({ - "id":"organization","type":"reference","target":"organization", - "required":true,"classification":"internal" - })); - value["recordTypes"].as_object_mut().unwrap().extend([ +fn the_statistics_dependency_diagnostic_names_row_boundaries_for_a_membership_entry() { + let mut value = source(); + value["recordTypes"]["record"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({ + "id":"organization","type":"reference","target":"organization", + "required":true,"classification":"internal" + })); + value["recordTypes"].as_object_mut().unwrap().extend([ ("organization".to_owned(), json!({"primaryDataset":"statistics-test","route":"organizations", "mutationMode":"mutable","fields":[ {"id":"name","type":"string","maximumLength":80,"classification":"internal"} @@ -846,16 +845,25 @@ fn statistical_dataset_refuses_caller_dependent_publisher_authority() { "accessRequirements":{"requiredScopes":["membership:use"]} })) ]); - value["accessProfiles"]["publisher"]["requiredScopes"] = json!(["membership:use"]); - value["accessProfiles"]["publisher"]["permissions"]["records"][0] - ["membershipBoundaries"] = json!([{ - "field":"organization","membershipRecordType":"membership", - "membershipKeyField":"organization","principalField":"principal","activeField":"active" - }]); - }, - "breg.statistical-dataset.publisher-caller-dependent", + value["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + value["accessProfiles"]["publisher"]["requiredScopes"] = json!(["membership:use"]); + value["accessProfiles"]["publisher"]["permissions"]["records"][0]["rowBoundaries"] = + json!([{"field":"organization","membership":"membership"}]); + let refusal = compile(&value).unwrap_err(); + let diagnostic = refusal + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "breg.statistical-dataset.publisher-caller-dependent") + .unwrap(); + assert!( + diagnostic.message.contains("rowBoundaries"), + "{diagnostic:?}" ); +} +#[test] +fn statistical_dataset_refuses_caller_dependent_publisher_authority() { assert_refused( |value| { let boundary = json!({"field":"category","claim":"categories","operator":"in"}); @@ -2046,6 +2054,7 @@ fn without_publisher_derived_read(value: &mut Value) { #[test] fn derived_dimension_records_entity_and_evaluation_date_dependencies() { let mut value = source(); + value["accessProfiles"][PUBLISHER]["requiredScopes"] = json!(["statistics:publish"]); value["recordTypes"]["record"]["derived"] = json!([{ "id":"statistics","sql":"sql/statistics.sql","key":"id", "fields":[{"id":"evaluated-category","type":"vocabulary-code","vocabulary":"category","values":["a","b"],"classification":"internal"}] diff --git a/crates/registry-breg/tests/data_operations.rs b/crates/registry-breg/tests/data_operations.rs index 3b217e3d10..5f5e5476e4 100644 --- a/crates/registry-breg/tests/data_operations.rs +++ b/crates/registry-breg/tests/data_operations.rs @@ -50,7 +50,7 @@ fn compiled(allow_data_export: bool) -> registry_breg::CompiledRegistry { }}, "accessProfiles": {PROFILE: { "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": ENTITY, "operations": ["create", "patch", "batch", "list"], @@ -336,7 +336,7 @@ fn data_validate_and_chunk_plan_reuse_runtime_rules_and_compiled_batch_bounds() "batch":{"maximumItems":2,"maximumBytes":100}, "fields":[{"id":"code","type":"text","maximumLength":1000,"required":true, "classification":"internal"}]}}, - "accessProfiles":{PROFILE: {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{PROFILE: {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":ENTITY, "operations":["create","batch"],"readableFields":["code"], "writableFields":["code"], "rowBoundaries": "unrestricted"}]}}} @@ -385,7 +385,7 @@ fn data_lifecycle_uses_exact_compiled_api_names() { }}, "accessProfiles": {PROFILE: { "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": ENTITY, "operations": ["create", "patch", "batch", "list"], diff --git a/crates/registry-breg/tests/disclosure/fields.rs b/crates/registry-breg/tests/disclosure/fields.rs index 009c6c06f4..5cc111f585 100644 --- a/crates/registry-breg/tests/disclosure/fields.rs +++ b/crates/registry-breg/tests/disclosure/fields.rs @@ -72,6 +72,7 @@ fn writable_project() -> registry_breg::CompiledRegistry { .unwrap() .values_mut() { + profile["requiredScopes"] = json!(["records:write"]); let grant = &mut profile["permissions"]["records"][0]; assert_eq!(grant["recordType"], "person"); grant["operations"] = json!(["create", "get", "list", "patch", "batch"]); @@ -200,7 +201,7 @@ async fn send( let claims = VerifiedRequestClaims::authenticated( "registry_principal", "canary-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, std::collections::BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/disclosure/history.rs b/crates/registry-breg/tests/disclosure/history.rs index 8d319bc5b0..9a9f68ef2a 100644 --- a/crates/registry-breg/tests/disclosure/history.rs +++ b/crates/registry-breg/tests/disclosure/history.rs @@ -79,7 +79,7 @@ fn history_source() -> Value { }; let person_target = json!([{"recordType": "person", "rowBoundaries": "unrestricted"}]); source["accessProfiles"][WRITER] = json!({ - "principalClaim": "registry_principal", "requiredScopes": "unrestricted", + "principalClaim": "registry_principal", "requiredScopes": ["records:write"], "permissions": { "records": [ writable("person", &PERSON_FIELDS), @@ -131,7 +131,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated_with_actor_kind( "registry_principal", "history-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::::new(), registry_platform_oidc::ActorKind::Human, diff --git a/crates/registry-breg/tests/disclosure/proposals.rs b/crates/registry-breg/tests/disclosure/proposals.rs index 285aa26542..462521a0b0 100644 --- a/crates/registry-breg/tests/disclosure/proposals.rs +++ b/crates/registry-breg/tests/disclosure/proposals.rs @@ -38,7 +38,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated_with_actor_kind( "sub", "reviewer", - BTreeSet::new(), + BTreeSet::from(["proposals:write".to_owned()]), None, BTreeMap::new(), registry_platform_oidc::ActorKind::Human, @@ -111,6 +111,7 @@ fn proposal_project() -> Value { .values_mut() { profile["principalClaim"] = json!("sub"); + profile["requiredScopes"] = json!(["proposals:write"]); let records = profile["permissions"]["records"].as_array_mut().unwrap(); for grant in records.iter_mut() { let writable: &[&str] = match grant["recordType"].as_str().unwrap() { diff --git a/crates/registry-breg/tests/disclosure/writes.rs b/crates/registry-breg/tests/disclosure/writes.rs index b05d4341a3..b7c1464ece 100644 --- a/crates/registry-breg/tests/disclosure/writes.rs +++ b/crates/registry-breg/tests/disclosure/writes.rs @@ -51,6 +51,7 @@ fn writes_source() -> Value { let lifecycle = proposal_lifecycle(); for (id, profile) in source["accessProfiles"].as_object_mut().unwrap() { let writer = id == WRITER; + profile["requiredScopes"] = json!(["records:write"]); let permissions = &mut profile["permissions"]; if !writer { let grant = &mut permissions["records"][0]; @@ -619,7 +620,7 @@ const ACTION_CLERK: &str = "action-clerk"; fn action_clerk_source(exempt: bool) -> Value { let mut source = writes_source(); source["accessProfiles"][ACTION_CLERK] = json!({ - "principalClaim": "registry_principal", "requiredScopes": "unrestricted", + "principalClaim": "registry_principal", "requiredScopes": ["records:write"], "permissions": {"actions": [ {"action": "set-person-email", "operations": ["invoke"], "targets": [{"recordType": "person", "rowBoundaries": "unrestricted"}]}]}}); diff --git a/crates/registry-breg/tests/disclosure_compile.rs b/crates/registry-breg/tests/disclosure_compile.rs index 6ea24a82e0..074d04c3a1 100644 --- a/crates/registry-breg/tests/disclosure_compile.rs +++ b/crates/registry-breg/tests/disclosure_compile.rs @@ -313,9 +313,10 @@ fn workflow_source() -> Value { let targets = |record_type: &str| json!([{"recordType":record_type,"rowBoundaries":"unrestricted"}]); let clerk = |permissions: Value| { - json!({"principalClaim":"registry_principal","requiredScopes":"unrestricted", + json!({"principalClaim":"registry_principal","requiredScopes":["registry:workflow"], "permissions":permissions}) }; + value["accessProfiles"]["protection-officer"]["requiredScopes"] = json!(["registry:workflow"]); value["accessProfiles"]["protection-officer"]["permissions"]["actions"] = json!([ {"action":"propose-person-name","operations":["start"],"targets":targets("person")}]); let profiles = value["accessProfiles"].as_object_mut().unwrap(); @@ -1597,8 +1598,7 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { value["recordTypes"]["facility"]["derived"] = json!([{"id":"inspection-state","sql":"sql/derived.sql","key":"id", "fields":[{"id":"has-passed-inspection","type":"boolean","classification":"internal"}]}]); let sql = "SELECT f.id AS id, (count(i.id) FILTER (WHERE i.passed IS TRUE) > 0) AS has_passed_inspection FROM registry_source.facility f LEFT JOIN registry_source.inspection i ON i.facility = f.id GROUP BY f.id"; - let membership = json!([{"field":"organization","membershipRecordType":"membership", - "membershipKeyField":"organization","principalField":"principal","activeField":"active"}]); + let membership = json!([{"field":"organization","membership":"membership"}]); let grant = |profile: &str, value: &mut Value, membership: Option<&Value>| { let records = value["accessProfiles"][profile]["permissions"]["records"] .as_array_mut() @@ -1614,7 +1614,7 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { let mut inspection = json!({"recordType":"inspection","operations":["get"], "rowBoundaries":"unrestricted","readableFields":["facility"]}); if let Some(membership) = membership { - inspection["membershipBoundaries"] = membership.clone(); + inspection["rowBoundaries"] = membership.clone(); } records.push(inspection); }; @@ -1623,13 +1623,53 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { grant("member", &mut member, None); assert!(withheld_source_rows(compile_with_sql(&member, sql)).is_empty()); + let mut missing = member.clone(); + missing["accessProfiles"]["member"]["permissions"]["records"] + .as_array_mut() + .unwrap() + .pop(); + let unreadable = compile_with_sql(&missing, sql).unwrap_err(); + let message = &unreadable + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == UNREADABLE_SOURCE) + .unwrap() + .message; + assert!( + message.contains("requires membership through `membership`"), + "{message}" + ); + assert!(!message.contains("`unrestricted`"), "{message}"); + + let mut different = member.clone(); + different["recordTypes"]["inspection"]["fields"] + .as_array_mut() + .unwrap() + .push( + json!({"id":"region","type":"string","maximumLength":16,"classification":"internal"}), + ); + different["accessProfiles"]["member"]["permissions"]["records"][1]["rowBoundaries"] = + json!([{"field":"region","claim":"region","operator":"equals"}]); + let mismatch = compile_with_sql(&different, sql).unwrap_err(); + let message = &mismatch + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == SOURCE_BOUNDARY) + .unwrap() + .message; + assert!( + message.contains("retaining the required membership restrictions"), + "{message}" + ); + assert!(!message.contains("`unrestricted`"), "{message}"); + // The reader's grant on the facility carries the same membership. let mut member = value.clone(); grant("member", &mut member, Some(&membership)); let found = withheld_source_rows(compile_with_sql(&member, sql)); assert_eq!( finding_paths(&found), - ["recordTypes[id=inspection].accessProfiles[id=member].membershipBoundaries"] + ["recordTypes[id=inspection].accessProfiles[id=member].rowBoundaries"] ); for named in [ "`member`", @@ -1647,14 +1687,14 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { grant("member", &mut member, Some(&other_field)); assert_eq!( finding_paths(&withheld_source_rows(compile_with_sql(&member, sql))), - ["recordTypes[id=inspection].accessProfiles[id=member].membershipBoundaries"] + ["recordTypes[id=inspection].accessProfiles[id=member].rowBoundaries"] ); - // The steward's grant on the facility carries none. + // The membership writer's grant on the facility carries none. grant("steward", &mut value, Some(&membership)); assert_eq!( finding_paths(&withheld_source_rows(compile_with_sql(&value, sql))), - ["recordTypes[id=inspection].accessProfiles[id=steward].membershipBoundaries"] + ["recordTypes[id=inspection].accessProfiles[id=steward].rowBoundaries"] ); } diff --git a/crates/registry-breg/tests/disclosure_exposure.rs b/crates/registry-breg/tests/disclosure_exposure.rs index c71be4ef56..2dd4b76501 100644 --- a/crates/registry-breg/tests/disclosure_exposure.rs +++ b/crates/registry-breg/tests/disclosure_exposure.rs @@ -5,6 +5,7 @@ //! caller, but the author surfaces list the conditions in full. use registry_breg::access::explain_access; +#[cfg(all(feature = "runtime", feature = "tooling"))] use registry_breg::access_preview::{preview_access, AccessScenario}; use registry_breg::artifacts::inspect_registry; use registry_breg::odrl_export::export_odrl; @@ -67,6 +68,7 @@ fn author_inspection_lists_the_conditions_in_full() { ); } +#[cfg(all(feature = "runtime", feature = "tooling"))] fn scenario(profile: &str) -> AccessScenario { serde_json::from_value( json!({"recordType":"person","accessProfile":profile,"operation":"get", @@ -76,6 +78,7 @@ fn scenario(profile: &str) -> AccessScenario { .unwrap() } +#[cfg(all(feature = "runtime", feature = "tooling"))] #[test] fn the_access_preview_names_the_conditions_that_bind_the_profile() { let registry = compiled(); diff --git a/crates/registry-breg/tests/explicit_row_authority.rs b/crates/registry-breg/tests/explicit_row_authority.rs index e57c8ecf39..3e706921e2 100644 --- a/crates/registry-breg/tests/explicit_row_authority.rs +++ b/crates/registry-breg/tests/explicit_row_authority.rs @@ -66,25 +66,22 @@ fn invocation_and_mandatory_requirements_do_not_invent_row_grants() { #[test] fn membership_preserves_explicit_row_declarations_and_round_trips() { - let boundaries = json!([{ - "field":"organization", "membershipRecordType":"membership", - "membershipKeyField":"organization", "principalField":"principal", - "activeField":"active" - }]); - let mut grant = json!({ - "recordType":"record", "operations":["get"], "membershipBoundaries": boundaries - }); + let entry = json!([{"field":"organization", "membership":"membership"}]); + let mut grant = json!({"recordType":"record", "operations":["get"]}); requires_explicit_rows::(grant.clone()); - grant["rowBoundaries"] = json!("unrestricted"); + grant["rowBoundaries"] = entry.clone(); let parsed: EntityPermissionSource = serde_json::from_value(grant).unwrap(); - assert_eq!(parsed.membership_boundaries.len(), 1); + assert_eq!(parsed.membership_row_boundaries.len(), 1); assert_eq!( - serde_json::to_value(parsed).unwrap()["membershipBoundaries"], - boundaries + serde_json::to_value(parsed).unwrap()["rowBoundaries"], + entry ); carries_compiled_rows::(json!({ "id":"member", "principalClaim":"sub", "operations":["get"], - "membershipBoundaries": boundaries + "membershipBoundaries": [{ + "field":"organization", "membershipRecordType":"membership", + "membershipKeyField":"organization", "principalField":"principal", "activeField":"active" + }] })); } diff --git a/crates/registry-breg/tests/field_encryption_contract.rs b/crates/registry-breg/tests/field_encryption_contract.rs index 149b03beb6..d07c51cba3 100644 --- a/crates/registry-breg/tests/field_encryption_contract.rs +++ b/crates/registry-breg/tests/field_encryption_contract.rs @@ -34,7 +34,7 @@ fn encrypted_project() -> Value { "lookup":{"normalization":["trim","uppercase"],"unique":true}} ] }}, - "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"case","rowBoundaries":"unrestricted","operations":["get","list","create","patch"], "readableFields":["label","secret"],"writableFields":["label","secret"] }]}}} diff --git a/crates/registry-breg/tests/fixture_tooling.rs b/crates/registry-breg/tests/fixture_tooling.rs index c89d286d26..158a4e8f69 100644 --- a/crates/registry-breg/tests/fixture_tooling.rs +++ b/crates/registry-breg/tests/fixture_tooling.rs @@ -154,6 +154,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {{jurisdiction: {value}}} request: {{type: query, select: [personCode]}} @@ -227,8 +228,8 @@ journeys: ); let unknown_scope = journey("[zone-a, zone-b]").replace( - "purpose: case-management", - "purpose: case-management\n scopes: [registry:extra]", + "scopes: [person:write]", + "scopes: [person:write, registry:extra]", ); let error = validate_fixture_journeys(unknown_scope.as_bytes(), ®istry) .expect_err("sets do not permit undeclared scopes"); @@ -251,6 +252,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -266,6 +268,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: query, select: [personCode, legalName], count: true} @@ -275,6 +278,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -349,6 +353,7 @@ journeys: accessProfile: household-seed claims: principal: fixture-seed + scopes: [household:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -800,7 +805,7 @@ fn compiled_crud_alias_fixture() -> registry_breg::CompiledRegistry { ], "constraints":[{"type":"unique","fields":["person-code"]}] }}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["person:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"person","operations":["create","get","list","patch"], "readableFields":["jurisdiction","person-code","legal-name"], @@ -859,7 +864,7 @@ fn compiled_action_fixture() -> registry_breg::CompiledRegistry { "set":{"contact-person":{"fromEffect":"person"}}} ]} }}, - "accessProfiles":{"household-seed": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + "accessProfiles":{"household-seed": {"default":true,"principalClaim":"registry_principal","requiredScopes":["household:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"household","operations":["create","get"],"readableFields":["jurisdiction","household-code","contact-person"], "writableFields":["jurisdiction","household-code"],"rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] @@ -1013,7 +1018,7 @@ fn fixture_journey_reader_reports_every_unknown_removed_and_anchored_key_with_it (source.line, source.column) }) .collect::>(); - assert_eq!(positions, [(Some(8), Some(9)), (Some(16), Some(11))]); + assert_eq!(positions, [(Some(8), Some(9)), (Some(17), Some(11))]); assert!( !format!("{error:?}").contains("canary"), "the refusal carries no authored value: {error:?}" @@ -1500,6 +1505,7 @@ journeys: accessProfile: registrar claims: principal: private-principal-canary + scopes: [person:write] purpose: case-management directClaims: {direct_claims} request: {{type: list}} diff --git a/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml b/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml index f2534634fe..90d2461489 100644 --- a/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml +++ b/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml @@ -46,7 +46,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [registry:contact:register] permissions: actions: - action: create-entry diff --git a/crates/registry-breg/tests/fixtures/authority-mapping.yaml b/crates/registry-breg/tests/fixtures/authority-mapping.yaml index e6ea50048c..67b0dd6fc8 100644 --- a/crates/registry-breg/tests/fixtures/authority-mapping.yaml +++ b/crates/registry-breg/tests/fixtures/authority-mapping.yaml @@ -52,7 +52,7 @@ accessProfiles: reviewer: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [proposals:write] permissions: actions: - action: correction diff --git a/crates/registry-breg/tests/fixtures/event-record/shapes.yaml b/crates/registry-breg/tests/fixtures/event-record/shapes.yaml index 3a79eaba91..600fde00f5 100644 --- a/crates/registry-breg/tests/fixtures/event-record/shapes.yaml +++ b/crates/registry-breg/tests/fixtures/event-record/shapes.yaml @@ -196,7 +196,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] permissions: actions: - action: record-grant-pause diff --git a/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml b/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml index f8233e7a78..15cba4f6bb 100644 --- a/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml +++ b/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml @@ -25,7 +25,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] permissions: actions: - action: create-entry diff --git a/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml b/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml index 9e5302129b..918a59864a 100644 --- a/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml +++ b/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -23,6 +24,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: get, recordCapture: first-widget} @@ -35,6 +37,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: list} @@ -50,6 +53,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -68,6 +72,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -81,6 +86,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] directClaims: {jurisdiction: zone-a} request: {type: get, recordCapture: revised-widget} expect: diff --git a/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml b/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml index 41ca3ca45f..f24f127afe 100644 --- a/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml +++ b/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml @@ -52,7 +52,7 @@ accessProfiles: operator: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [fixture:write] requiredPurposes: [case-management] permissions: records: diff --git a/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml b/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml index e3c1de6a7b..07dee6db7a 100644 --- a/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml +++ b/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -22,6 +23,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: diff --git a/crates/registry-breg/tests/generated_identifier_compiler.rs b/crates/registry-breg/tests/generated_identifier_compiler.rs index 0764511d1c..51059389cb 100644 --- a/crates/registry-breg/tests/generated_identifier_compiler.rs +++ b/crates/registry-breg/tests/generated_identifier_compiler.rs @@ -62,7 +62,7 @@ fn project_value() -> Value { }}, "accessProfiles": {"editor": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "record", "operations": ["create", "get"], @@ -409,7 +409,7 @@ fn fixed_actions_cannot_supply_server_generated_identifiers() { project["accessProfiles"] = json!({"operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-record", "operations": ["invoke"], @@ -479,7 +479,7 @@ fn create_effect_bounds_include_server_generated_fields() { project["accessProfiles"] = json!({"operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-record", "operations": [operation], diff --git a/crates/registry-breg/tests/golden/membership-access.json b/crates/registry-breg/tests/golden/membership-access.json new file mode 100644 index 0000000000..11ba0cd603 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-access.json @@ -0,0 +1,113 @@ +{ + "entries": [ + { + "routeId": "records.facility.create", + "recordType": "facility", + "operation": "create", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.facility.get", + "recordType": "facility", + "operation": "get", + "profileIds": [ + "member", + "steward" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.lookup", + "recordType": "facility", + "operation": "lookup", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.list", + "recordType": "facility", + "operation": "list", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.patch", + "recordType": "facility", + "operation": "patch", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.facility.revisions", + "recordType": "facility", + "operation": "revisions", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.snapshot", + "recordType": "facility", + "operation": "snapshot", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.membership.create", + "recordType": "membership", + "operation": "create", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.membership.get", + "recordType": "membership", + "operation": "get", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.membership.patch", + "recordType": "membership", + "operation": "patch", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.organization.create", + "recordType": "organization", + "operation": "create", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.organization.get", + "recordType": "organization", + "operation": "get", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + } + ] +} diff --git a/crates/registry-breg/tests/golden/membership-ddl.json b/crates/registry-breg/tests/golden/membership-ddl.json new file mode 100644 index 0000000000..eef62f1734 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-ddl.json @@ -0,0 +1,334 @@ +{ + "requiresBtreeGist": false, + "statements": [ + { + "id": "schema.registry_data", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_data" + }, + { + "id": "schema.registry_source", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_source" + }, + { + "id": "schema.registry_derived", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_derived" + }, + { + "id": "schema.registry_context", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_context" + }, + { + "id": "function.registry_context.evaluation_date", + "kind": "function", + "sql": "CREATE OR REPLACE FUNCTION registry_context.evaluation_date()\n RETURNS date\n LANGUAGE sql\n STABLE\n SECURITY INVOKER\n AS $breg_function$\n SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date\n $breg_function$" + }, + { + "id": "entity.facility.table", + "kind": "table", + "sql": "CREATE TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_facility_label_49700f8f0b0d4a57\" varchar(80) COLLATE pg_catalog.pg_c_utf8 NOT NULL, \"breg_f_facility_organization_c72e96e6196479cc\" uuid NOT NULL)" + }, + { + "id": "entity.membership.table", + "kind": "table", + "sql": "CREATE TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_membership_active_6e662651da1918d2\" boolean NOT NULL, \"breg_f_membership_organization_bfa076d486640343\" uuid NOT NULL, \"breg_f_membership_principal_dbfb37e169be4783\" varchar(80) COLLATE pg_catalog.pg_c_utf8 NOT NULL, \"breg_f_membership_private_note_5a8d02ceb53dd0bd\" varchar(80) COLLATE pg_catalog.pg_c_utf8)" + }, + { + "id": "entity.organization.table", + "kind": "table", + "sql": "CREATE TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_organization_name_39e5047e3f964468\" varchar(80) COLLATE pg_catalog.pg_c_utf8)" + }, + { + "id": "entity.facility.reference-lifecycle.column", + "kind": "column", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8\n GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED" + }, + { + "id": "entity.membership.reference-lifecycle.column", + "kind": "column", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8\n GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED" + }, + { + "id": "entity.organization.reference-lifecycle.key", + "kind": "constraint", + "sql": "ALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" ADD CONSTRAINT \"breg_rk_organization_1a9958900e5456b0\" UNIQUE (record_id, record_lifecycle)" + }, + { + "id": "entity.facility.field.organization.reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ADD CONSTRAINT \"breg_r_facility_organization_d6e2e76fcb68e418\" FOREIGN KEY (\"breg_f_facility_organization_c72e96e6196479cc\") REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id) ON DELETE RESTRICT" + }, + { + "id": "entity.facility.field.organization.active-reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ADD CONSTRAINT \"breg_ar_facility_organization_c2ee3822a6f70011\" FOREIGN KEY (\"breg_f_facility_organization_c72e96e6196479cc\", record_reference_lifecycle) REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT;\nALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.facility.index.reference:organization", + "kind": "index", + "sql": "CREATE INDEX \"breg_ri_facility_organization_a21122438500a54c\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" (\"breg_f_facility_organization_c72e96e6196479cc\")" + }, + { + "id": "entity.membership.field.organization.reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ADD CONSTRAINT \"breg_r_membership_organization_faa70a2468df1cb1\" FOREIGN KEY (\"breg_f_membership_organization_bfa076d486640343\") REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id) ON DELETE RESTRICT" + }, + { + "id": "entity.membership.field.organization.active-reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ADD CONSTRAINT \"breg_ar_membership_organization_09291f896d3ebb10\" FOREIGN KEY (\"breg_f_membership_organization_bfa076d486640343\", record_reference_lifecycle) REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT;\nALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.membership.index.membership-principal-key", + "kind": "index", + "sql": "CREATE INDEX \"breg_i_membership_membership_principal_key_71354dc018b3a225\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (\"breg_f_membership_principal_dbfb37e169be4783\", \"breg_f_membership_organization_bfa076d486640343\", \"breg_f_membership_active_6e662651da1918d2\", record_id)" + }, + { + "id": "entity.membership.index.reference:organization", + "kind": "index", + "sql": "CREATE INDEX \"breg_ri_membership_organization_d0fbd830aaf560b4\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (\"breg_f_membership_organization_bfa076d486640343\")" + }, + { + "id": "entity.membership.membership.key-index", + "kind": "index", + "sql": "CREATE INDEX \"breg_membership_key_b9ee6c3037\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (\"breg_f_membership_organization_bfa076d486640343\", \"breg_f_membership_principal_dbfb37e169be4783\") WHERE \"breg_f_membership_active_6e662651da1918d2\" IS TRUE AND record_lifecycle = 'active'" + }, + { + "id": "registry_context.membership_7b967b5ec89a5c63ab8056cd", + "kind": "function", + "sql": "CREATE FUNCTION registry_context.\"membership_7b967b5ec89a5c63ab8056cd\"(uuid) RETURNS boolean LANGUAGE plpgsql STABLE STRICT SECURITY INVOKER SET search_path = pg_catalog AS 'DECLARE prior_marker text := current_setting(''registry.membership_probe'', true); authorized boolean; BEGIN PERFORM set_config(''registry.membership_probe'', ''membership_7b967b5ec89a5c63ab8056cd'', true); SELECT EXISTS (SELECT 1 FROM registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" AS membership WHERE membership.record_lifecycle = ''active'' AND membership.\"breg_f_membership_principal_dbfb37e169be4783\" = NULLIF(current_setting(''registry.principal'', true), '''') AND membership.\"breg_f_membership_active_6e662651da1918d2\" IS TRUE AND membership.\"breg_f_membership_organization_bfa076d486640343\" = $1) INTO authorized; PERFORM set_config(''registry.membership_probe'', COALESCE(prior_marker, ''''), true); RETURN authorized; EXCEPTION WHEN OTHERS THEN RAISE; END'" + }, + { + "id": "entity.facility.rls.enable", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ENABLE ROW LEVEL SECURITY" + }, + { + "id": "entity.facility.rls.force", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.facility.policy.registry_rls_select_b56c984fa34e60b58e32e7d3", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_b56c984fa34e60b58e32e7d3\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'member' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0 AND registry_context.\"membership_7b967b5ec89a5c63ab8056cd\"(\"breg_f_facility_organization_c72e96e6196479cc\")) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_b56c984fa34e60b58e32e7d3\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/1ff0fa085876122e11f4c5a802c2e8e4e900a21cbc448d1624bf307fe49fae5f'" + }, + { + "id": "entity.facility.policy.registry_rls_select_bd688fd36cf3a53a01382a56", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_bd688fd36cf3a53a01382a56\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_bd688fd36cf3a53a01382a56\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/c63db1bfd0fa09289779ea867bf5407db8ce9ae4d09bc56efa120a2aab40c367'" + }, + { + "id": "entity.facility.policy.registry_rls_insert_77687d5ac1f8badf901ee933", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_insert_77687d5ac1f8badf901ee933\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_77687d5ac1f8badf901ee933\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/e16b1d51effd9575d791229c843740a5bdbbb37c5697398cafa369f021e6539e'" + }, + { + "id": "entity.facility.policy.registry_rls_update_f6e327e7ea9457483f3eabeb", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_update_f6e327e7ea9457483f3eabeb\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR UPDATE USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active') WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_update_f6e327e7ea9457483f3eabeb\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/6202ed55d51b18cee0233559fbbab14f840ad223c4986048cb2e213d8c851643'" + }, + { + "id": "entity.membership.rls.enable", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ENABLE ROW LEVEL SECURITY" + }, + { + "id": "entity.membership.rls.force", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.membership.policy.registry_rls_select_2c193a25886b5ebec5bba2e5", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_2c193a25886b5ebec5bba2e5\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_2c193a25886b5ebec5bba2e5\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" IS 'breg/policy/v1/97e2451b6e98fd3dbebea85516fc4ad69ffcacddd4fe013feb4ca0f4afbe6e39'" + }, + { + "id": "entity.membership.policy.registry_rls_insert_edd73113291f3d42ac72c32f", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_insert_edd73113291f3d42ac72c32f\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_edd73113291f3d42ac72c32f\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" IS 'breg/policy/v1/8a1b6e5748d1e2d6fb068e08a6a3bf0d3d2d00be5f52c15c632e11ae6067410c'" + }, + { + "id": "entity.membership.policy.registry_rls_update_f37197225c94dab6ad410cc1", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_update_f37197225c94dab6ad410cc1\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FOR UPDATE USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active') WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_update_f37197225c94dab6ad410cc1\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" IS 'breg/policy/v1/82cba119d6cb474654f121cd266efc52f8c8f1d75d40721fc25f8ca0876108ca'" + }, + { + "id": "entity.organization.rls.enable", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" ENABLE ROW LEVEL SECURITY" + }, + { + "id": "entity.organization.rls.force", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.organization.policy.registry_rls_select_fc68ada80db4374538d917df", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_fc68ada80db4374538d917df\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_fc68ada80db4374538d917df\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" IS 'breg/policy/v1/ab8ebf2e79f6bd405b4c210d480892f7895ccf717411fb87bec5c0fd031a6e53'" + }, + { + "id": "entity.organization.policy.registry_rls_insert_de59d694cebbb215bd3f6b9b", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_insert_de59d694cebbb215bd3f6b9b\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_de59d694cebbb215bd3f6b9b\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" IS 'breg/policy/v1/62a79ddf5f7342a15d6ac20c38128d9ca52aae7bc7f215733a964bd0f3b7c9be'" + }, + { + "id": "entity.facility.source-view", + "kind": "view", + "sql": "CREATE VIEW registry_source.\"facility\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_facility_organization_c72e96e6196479cc\" AS \"organization\", \"breg_f_facility_label_49700f8f0b0d4a57\" AS \"label\"\n FROM registry_data.\"breg_e_facility_675cdbdae206c49c\"\n WHERE record_lifecycle = 'active'" + }, + { + "id": "entity.membership.source-view", + "kind": "view", + "sql": "CREATE VIEW registry_source.\"membership\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_membership_organization_bfa076d486640343\" AS \"organization\", \"breg_f_membership_principal_dbfb37e169be4783\" AS \"principal\", \"breg_f_membership_active_6e662651da1918d2\" AS \"active\", \"breg_f_membership_private_note_5a8d02ceb53dd0bd\" AS \"private_note\"\n FROM registry_data.\"breg_e_membership_a36e7273b8ef4eb1\"\n WHERE record_lifecycle = 'active'" + }, + { + "id": "entity.organization.source-view", + "kind": "view", + "sql": "CREATE VIEW registry_source.\"organization\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_organization_name_39e5047e3f964468\" AS \"name\"\n FROM registry_data.\"breg_e_organization_6ccb51e3b2202a71\"\n WHERE record_lifecycle = 'active'" + } + ], + "tables": [ + { + "entityId": "facility", + "physicalName": "breg_e_facility_675cdbdae206c49c", + "runtimePrivileges": [ + "select", + "insert", + "update" + ], + "policies": [ + { + "name": "registry_rls_select_b56c984fa34e60b58e32e7d3", + "command": "select", + "accessProfile": "member", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'member' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0 AND registry_context.\"membership_7b967b5ec89a5c63ab8056cd\"(\"breg_f_facility_organization_c72e96e6196479cc\")) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_select_bd688fd36cf3a53a01382a56", + "command": "select", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_insert_77687d5ac1f8badf901ee933", + "command": "insert", + "accessProfile": "steward", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + }, + { + "name": "registry_rls_update_f6e327e7ea9457483f3eabeb", + "command": "update", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + } + ] + }, + { + "entityId": "membership", + "physicalName": "breg_e_membership_a36e7273b8ef4eb1", + "runtimePrivileges": [ + "select", + "insert", + "update" + ], + "policies": [ + { + "name": "registry_rls_select_2c193a25886b5ebec5bba2e5", + "command": "select", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_insert_edd73113291f3d42ac72c32f", + "command": "insert", + "accessProfile": "steward", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + }, + { + "name": "registry_rls_update_f37197225c94dab6ad410cc1", + "command": "update", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + }, + { + "name": "registry_membership_7b967b5ec89a5c63ab8056cd", + "command": "select", + "accessProfile": "member", + "appliesTo": "runtime", + "usingExpression": "(NULLIF(current_setting('registry.membership_probe', true), '') = 'membership_7b967b5ec89a5c63ab8056cd' AND NULLIF(current_setting('registry.access_profile', true), '') = 'member') AND (\"breg_e_membership_a36e7273b8ef4eb1\".record_lifecycle = 'active' AND \"breg_e_membership_a36e7273b8ef4eb1\".\"breg_f_membership_principal_dbfb37e169be4783\" = NULLIF(current_setting('registry.principal', true), '') AND \"breg_e_membership_a36e7273b8ef4eb1\".\"breg_f_membership_active_6e662651da1918d2\" IS TRUE)" + } + ] + }, + { + "entityId": "organization", + "physicalName": "breg_e_organization_6ccb51e3b2202a71", + "runtimePrivileges": [ + "select", + "insert" + ], + "policies": [ + { + "name": "registry_rls_select_fc68ada80db4374538d917df", + "command": "select", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_insert_de59d694cebbb215bd3f6b9b", + "command": "insert", + "accessProfile": "steward", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + } + ] + } + ], + "views": [ + { + "id": "entity.facility.source", + "schema": "registry_source", + "name": "facility", + "runtimePrivileges": [ + "select" + ] + }, + { + "id": "entity.membership.source", + "schema": "registry_source", + "name": "membership", + "runtimePrivileges": [ + "select" + ] + }, + { + "id": "entity.organization.source", + "schema": "registry_source", + "name": "organization", + "runtimePrivileges": [ + "select" + ] + } + ], + "functions": [ + { + "id": "registry_context.evaluation_date", + "schema": "registry_context", + "name": "evaluation_date", + "arguments": "", + "runtimeExecute": true + }, + { + "id": "registry_context.membership_7b967b5ec89a5c63ab8056cd", + "schema": "registry_context", + "name": "membership_7b967b5ec89a5c63ab8056cd", + "arguments": "uuid", + "runtimeExecute": true + } + ] +} diff --git a/crates/registry-breg/tests/golden/membership-ddl.sha256 b/crates/registry-breg/tests/golden/membership-ddl.sha256 new file mode 100644 index 0000000000..896afb6dfa --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-ddl.sha256 @@ -0,0 +1 @@ +a43b1a7b8e08d20bd4e3f6a9f32099b8221b0215c6c0fa445cd38f9cf8d41c85 diff --git a/crates/registry-breg/tests/golden/membership-revision.txt b/crates/registry-breg/tests/golden/membership-revision.txt new file mode 100644 index 0000000000..c3e9fef05b --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-revision.txt @@ -0,0 +1 @@ +sha256:4fee679a2a23b6314291f46f7e460bbf736a485af06ff3210ec7d7fbed6db000 diff --git a/crates/registry-breg/tests/golden/membership_refusals.json b/crates/registry-breg/tests/golden/membership_refusals.json new file mode 100644 index 0000000000..818142c647 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership_refusals.json @@ -0,0 +1,336 @@ +{ + "development-availability": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "failedCheck": "membership", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "263", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "development-availability-claim": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "failedCheck": "row-boundary", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "265", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "development-availability-missing": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "failedCheck": "visibility", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "263", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "development-create-claim": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "failedCheck": "row-boundary", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "347", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "development-create-missing": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "failedCheck": "membership", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "345", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "development-generic-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + }, + "development-observed-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + }, + "production-availability": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "236", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "production-availability-claim": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "236", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "production-availability-missing": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "236", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "production-create-claim": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "318", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "production-create-missing": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "318", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "production-generic-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + }, + "production-observed-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + } +} diff --git a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt index b5ffbf23b0..c9173c9b19 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt @@ -180,6 +180,7 @@ breg_request_refusals_total{check="task-grant-scope"} 0 breg_request_refusals_total{check="task-grant-lifetime"} 0 breg_request_refusals_total{check="task-grant-status"} 0 breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="membership"} 0 breg_request_refusals_total{check="ownership"} 0 breg_request_refusals_total{check="visibility"} 0 breg_request_refusals_total{check="action-guard"} 0 diff --git a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt index f469ffcaa8..52863c3ce5 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt @@ -151,6 +151,7 @@ breg_request_refusals_total{check="task-grant-scope"} 0 breg_request_refusals_total{check="task-grant-lifetime"} 0 breg_request_refusals_total{check="task-grant-status"} 0 breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="membership"} 0 breg_request_refusals_total{check="ownership"} 0 breg_request_refusals_total{check="visibility"} 0 breg_request_refusals_total{check="action-guard"} 0 diff --git a/crates/registry-breg/tests/http_read_only.rs b/crates/registry-breg/tests/http_read_only.rs index f57820be88..8f0ddd13ec 100644 --- a/crates/registry-breg/tests/http_read_only.rs +++ b/crates/registry-breg/tests/http_read_only.rs @@ -4110,7 +4110,16 @@ async fn runtime_openapi_contract_is_filtered_to_the_selected_acceptance_profile .send( Method::GET, "/openapi.json?accessProfile=site-planner", - Some(registry_principal_claims("site-planning")), + Some( + VerifiedRequestClaims::authenticated( + "registry_principal", + "registry-principal", + BTreeSet::from(["asset:plan".into()]), + Some("site-planning".into()), + BTreeMap::new(), + ) + .unwrap(), + ), ) .await, ) diff --git a/crates/registry-breg/tests/immediate_action_compiler.rs b/crates/registry-breg/tests/immediate_action_compiler.rs index 4bd281d5a1..228ab25103 100644 --- a/crates/registry-breg/tests/immediate_action_compiler.rs +++ b/crates/registry-breg/tests/immediate_action_compiler.rs @@ -559,7 +559,7 @@ fn create_effects_may_rely_entirely_on_server_generated_fields() { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "register", "operations": [operation], @@ -721,7 +721,7 @@ fn action_effect_graph_rejects_invalid_sources_cycles_and_overlaps() { "set":{"label":{"fromInput":"label"},"alpha":{"fromEffect":"alpha"}} }]} }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{ "action":"make-cycle", "operations":["invoke"], "targets":[{"recordType":"alpha","rowBoundaries":"unrestricted"},{"recordType":"beta","rowBoundaries":"unrestricted"}] @@ -749,7 +749,7 @@ fn action_inputs_resolve_project_vocabulary_values_for_type_compatibility() { "inputs":[{"id":"kind","type":"vocabulary-code","vocabulary":"asset-type","required":true,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"asset","target":{"recordType":"asset"},"operation":"create","set":{"kind":{"fromInput":"kind"}}}]} }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{ "action":"create-asset", "operations":["invoke"], "targets":[{"recordType":"asset","rowBoundaries":"unrestricted"}], @@ -780,7 +780,7 @@ fn action_inputs_reject_unknown_project_vocabulary_references() { "inputs":[{"id":"kind","type":"vocabulary-code","vocabulary":"asset-type","required":true,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"asset","target":{"recordType":"asset"},"operation":"create","set":{"kind":{"fromInput":"kind"}}}]} }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{ "action":"create-asset", "operations":["invoke"], "targets":[{"recordType":"asset","rowBoundaries":"unrestricted"}] @@ -821,7 +821,7 @@ fn action_bounds_apply_before_runtime_target_work() { "recordTypes":{{"record":{{"primaryDataset":"test-dataset","route":"records","mutationMode":"mutable", "fields":[{{"id":"label","type":"string","maximumLength":32,"classification":"internal"}}]}}}}, "actions":{{"bulk-fix":{{"execution":{{"mode":"immediate"}},"inputs":[{}],"plan":{{"type":"fixed","effects":[{}]}}}}}}, - "accessProfiles":{{"operator":{{"default":true,"principalClaim":"principal","requiredScopes":"unrestricted", + "accessProfiles":{{"operator":{{"default":true,"principalClaim":"principal","requiredScopes":["records:write"], "permissions":{{"actions":[{{"action":"bulk-fix","operations":["invoke"],"targets":[{}]}}]}}}}}} }}"#, inputs.join(","), @@ -882,7 +882,7 @@ fn action_field_and_snapshot_ceilings_refuse_otherwise_valid_plans() { "operation": "create", "set": Value::Object(assignments) }]} }}, - "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", "requiredScopes": "unrestricted", + "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-bounded-record", "operations": ["invoke"], "targets": [{"recordType": "bounded-record", "rowBoundaries": "unrestricted"}] @@ -981,7 +981,7 @@ fn generated_create_fields_count_toward_the_proposal_snapshot_ceiling() { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["proposals:write"], "permissions": {"actions": [{ "action": "create-bounded-record", "operations": ["start"], diff --git a/crates/registry-breg/tests/immediate_action_handler.rs b/crates/registry-breg/tests/immediate_action_handler.rs index d9c0bcdd10..5370988570 100644 --- a/crates/registry-breg/tests/immediate_action_handler.rs +++ b/crates/registry-breg/tests/immediate_action_handler.rs @@ -30,7 +30,7 @@ fn project() -> Value { {"id":"friend","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]}, {"id":"existing","target":{"fromInput":"person"},"operation":"patch","fields":["name","friend"]} ],"refusals":[{"code":"blank-name","label":"A name is required."}]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} }) } fn compile(source: Value, script: &str) -> Result { diff --git a/crates/registry-breg/tests/import_grant_admission.rs b/crates/registry-breg/tests/import_grant_admission.rs index 3d084db14d..998271273a 100644 --- a/crates/registry-breg/tests/import_grant_admission.rs +++ b/crates/registry-breg/tests/import_grant_admission.rs @@ -28,7 +28,7 @@ fn project(loader_operations: &[&str]) -> Value { "mutationPolicy":{"patch":"proposal-required"}, "fields":[{"id":"label","type":"string","maximumLength":32,"required":true,"classification":"internal"}] }}, - "accessProfiles":{"loader": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted", + "accessProfiles":{"loader": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"enrollment","operations":loader_operations,"readableFields":["label"],"writableFields":["label"], "rowBoundaries":"unrestricted" diff --git a/crates/registry-breg/tests/membership_access.rs b/crates/registry-breg/tests/membership_access.rs index d2b0213e1a..787f1ac464 100644 --- a/crates/registry-breg/tests/membership_access.rs +++ b/crates/registry-breg/tests/membership_access.rs @@ -55,37 +55,37 @@ fn membership_reference_uses_one_positioned_spelling() { let decoded = registry_breg::contract::read_project_yaml("registry.yaml", &bytes).unwrap(); let wire = serde_json::to_value(&decoded.value).unwrap(); assert_eq!( - wire.pointer( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/membershipRecordType" - ), + wire.pointer("/accessProfiles/member/permissions/records/0/rowBoundaries/0/membership"), Some(&json!("membership")) ); - for value in [json!("membership"), json!(""), serde_json::Value::Null] { - let mut previous = source.clone(); - let boundary = previous - .pointer_mut("/accessProfiles/member/permissions/records/0/membershipBoundaries/0") - .unwrap() - .as_object_mut() - .unwrap(); - boundary.remove("membershipRecordType"); - boundary.insert("membershipEntity".to_owned(), value); - let report = registry_breg::contract::read_project_yaml( - "registry.yaml", - &serde_json::to_vec_pretty(&previous).unwrap(), - ) - .expect_err("previous reference is refused"); - let diagnostic = report - .diagnostics() - .iter() - .find(|diagnostic| diagnostic.code == "config.removed-key") - .expect("migration guidance is present"); - assert_eq!( - diagnostic.path, - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/membershipEntity" - ); - assert!(diagnostic.suggested_action.contains("membershipRecordType")); - assert!(diagnostic.source.as_ref().unwrap().line.is_some()); - } +} + +#[test] +fn membership_boundaries_is_refused_with_its_replacement_named() { + let mut source = source("facility"); + source["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"] = + json!([]); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec_pretty(&source).unwrap(), + ) + .expect_err("removed member is refused"); + let diagnostic = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .unwrap(); + assert_eq!( + diagnostic.path, + "/accessProfiles/member/permissions/records/0/membershipBoundaries" + ); + assert!(diagnostic + .suggested_action + .contains("membership: {key, principal, active}")); + assert!(diagnostic + .suggested_action + .contains("rowBoundaries entry {field, membership}")); + assert!(diagnostic.source.as_ref().unwrap().line.is_some()); } #[test] @@ -93,8 +93,8 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { for (path, value, code) in [ ( "/accessProfiles/member/permissions/records/0/operations", - json!(["get", "patch"]), - "breg.access.membership-read-only", + json!(["get", "import"]), + "breg.access.membership-import-unsupported", ), ( "/accessProfiles/member/requiredScopes", @@ -102,23 +102,23 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { "breg.access.requirements-scope-missing", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/field", + "/accessProfiles/member/permissions/records/0/rowBoundaries/0/field", json!("label"), "breg.access.membership-key-type", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/principalField", + "/recordTypes/membership/membership/principal", json!("active"), "breg.access.membership-principal-type", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/activeField", + "/recordTypes/membership/membership/active", json!("principal"), "breg.access.membership-active-type", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/membershipRecordType", - json!("facility"), + "/accessProfiles/member/permissions/records/0/recordType", + json!("membership"), "breg.access.membership-source-recursive", ), ( @@ -156,7 +156,7 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { let mut action = action_requirements::project(); action["accessProfiles"]["registrar"]["permissions"]["actions"][0]["membershipBoundaries"] = source("facility")["accessProfiles"]["member"]["permissions"]["records"][0] - ["membershipBoundaries"] + ["rowBoundaries"] .clone(); let failure = registry_breg::parse_project_yaml(&serde_json::to_vec(&action).unwrap()) .expect_err("an action grant must not silently ignore entity membership rules"); @@ -173,3 +173,76 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { )] ); } + +#[test] +fn module_membership_boundaries_is_refused_with_its_replacement_named() { + for collection in ["recordTypes", "extendRecordTypes"] { + let module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1", + "kind":"BRegModule","id":"membership-core","version":"1", + collection: {"facility":{"accessProfiles":{"member":{"membershipBoundaries":[]}}}} + }); + let bytes = serde_json::to_vec_pretty(&module).unwrap(); + let report = registry_breg::contract::read_module_yaml("module.yaml", &bytes).unwrap_err(); + let code = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .unwrap(); + assert_eq!( + code.path, + format!("/{collection}/facility/accessProfiles/member/membershipBoundaries") + ); + assert!(code + .suggested_action + .contains("membership: {key, principal, active}")); + assert!(code + .suggested_action + .contains("rowBoundaries entry {field, membership}")); + } +} + +#[test] +fn a_project_record_profile_refuses_membership_boundaries_with_its_replacement_named() { + let mut source = source("facility"); + source["recordTypes"]["facility"]["accessProfiles"] = + json!({"member":{"membershipBoundaries":[]}}); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec_pretty(&source).unwrap(), + ) + .unwrap_err(); + let diagnostic = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .unwrap(); + assert_eq!( + diagnostic.path, + "/recordTypes/facility/accessProfiles/member/membershipBoundaries" + ); + assert!(diagnostic + .suggested_action + .contains("membership: {key, principal, active}")); + assert!(diagnostic + .suggested_action + .contains("rowBoundaries entry {field, membership}")); +} + +#[test] +fn an_extension_cannot_declare_membership() { + let module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1", + "kind":"BRegModule","id":"membership-core","version":"1", + "extendRecordTypes":{"facility":{"membership":{"key":"organization","principal":"principal","active":"active"}}} + }); + let report = registry_breg::contract::read_module_yaml( + "module.yaml", + &serde_json::to_vec_pretty(&module).unwrap(), + ) + .unwrap_err(); + assert!(report.diagnostics().iter().any(|diagnostic| { + diagnostic.code == "config.unknown-key" + && diagnostic.path == "/extendRecordTypes/facility/membership" + })); +} diff --git a/crates/registry-breg/tests/membership_authoring.rs b/crates/registry-breg/tests/membership_authoring.rs new file mode 100644 index 0000000000..42530e7b1b --- /dev/null +++ b/crates/registry-breg/tests/membership_authoring.rs @@ -0,0 +1,617 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_breg::compiler::{compile_project, CompileProfile}; +use registry_breg::diagnostics::CompileFailure; +use registry_breg::{parse_project_yaml, CompiledRegistry}; +use serde_json::{json, Value}; + +const PROJECT: &[u8] = + include_bytes!("../../../products/breg/fixtures/organization-membership-access/registry.yaml"); +const ROWS: &str = "/accessProfiles/member/permissions/records/0/rowBoundaries"; +const DECLARATION: &str = "/recordTypes/membership/membership"; + +fn project() -> Value { + serde_json::from_slice(PROJECT).unwrap() +} + +fn compile(project: &Value) -> Result { + let source = parse_project_yaml(&serde_json::to_vec_pretty(project).unwrap())?; + compile_project(&source, &[], CompileProfile::Authoring) +} + +fn compile_production(project: &Value) -> Result { + let mut project = project.clone(); + project["package"] = json!({"sourceRevision":"membership-authoring-test"}); + let source = parse_project_yaml(&serde_json::to_vec_pretty(&project).unwrap())?; + compile_project(&source, &[], CompileProfile::Production) +} + +fn assert_production_refusal(project: &Value, code: &str, path: &str) { + let failure = compile_production(project).expect_err("Production refuses this grant"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == code && diagnostic.path == path), + "wanted {code} at {path}: {failure:?}" + ); +} + +fn assert_refusal(project: &Value, code: &str, path: &str) { + let failure = compile(project).expect_err("project must be refused"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == code && diagnostic.path == path), + "wanted {code} at {path}: {failure:?}" + ); +} + +#[test] +fn a_membership_declaration_compiles_into_the_record_type() { + let project = project(); + let registry = compile(&project).unwrap(); + let entity = serde_json::to_value(®istry.entities()["membership"]).unwrap(); + assert_eq!(entity["membership"], *project.pointer(DECLARATION).unwrap()); +} + +#[test] +fn a_membership_declaration_naming_a_missing_field_is_refused_without_panicking() { + for (field, code) in [ + ("key", "breg.access.membership-key-type"), + ("principal", "breg.access.membership-principal-type"), + ("active", "breg.access.membership-active-type"), + ] { + let mut project = project(); + project.pointer_mut(DECLARATION).unwrap()[field] = json!("missing"); + assert_refusal(&project, code, "recordTypes[id=membership].membership"); + } +} + +#[test] +fn a_record_grant_with_a_membership_entry_compiles_like_the_base_membership_boundary() { + let registry = compile(&project()).unwrap(); + let entry = ®istry.entities()["facility"].membership_boundaries["member"][0]; + assert_eq!(entry.field, "organization"); + assert_eq!(entry.membership_entity, "membership"); + let source = ®istry.entities()["membership"]; + assert_eq!(entry.membership_table, source.physical_table); + assert_eq!( + entry.membership_key_column, + source.fields["organization"].physical_name + ); + assert_eq!( + entry.principal_column, + source.fields["principal"].physical_name + ); + assert_eq!(entry.active_column, source.fields["active"].physical_name); +} + +#[test] +fn claim_and_membership_entries_share_one_row_boundaries_list() { + let mut project = project(); + project + .pointer_mut(ROWS) + .unwrap() + .as_array_mut() + .unwrap() + .push(json!({"field": "label", "claim": "facility-label", "operator": "equals"})); + let registry = compile(&project).unwrap(); + let entity = ®istry.entities()["facility"]; + assert_eq!(entity.access_profiles["member"].row_boundaries.len(), 1); + assert_eq!(entity.membership_boundaries["member"].len(), 1); +} + +#[test] +fn a_membership_only_grant_never_serializes_as_unrestricted() { + let project = project(); + let source = parse_project_yaml(&serde_json::to_vec_pretty(&project).unwrap()).unwrap(); + let serialized = serde_json::to_value(source).unwrap(); + assert_eq!(serialized.pointer(ROWS), project.pointer(ROWS)); +} + +#[test] +fn a_row_boundary_set_with_a_membership_entry_expands_like_the_inline_form() { + let inline = project(); + let mut named = inline.clone(); + named["rowBoundarySets"] = json!({"facility-membership": inline.pointer(ROWS).unwrap()}); + *named.pointer_mut(ROWS).unwrap() = json!({"rowBoundarySet": "facility-membership"}); + let inline = compile(&inline).unwrap(); + let named = compile(&named).unwrap(); + assert_eq!(named.access(), inline.access()); + assert_eq!(named.ddl(), inline.ddl()); +} + +fn shape_is_refused(entry: Value) { + let mut project = project(); + *project.pointer_mut(ROWS).unwrap() = json!([entry]); + let failure = compile(&project).expect_err("invalid boundary shape is refused"); + assert!( + failure.diagnostics().iter().any(|diagnostic| { + diagnostic.message.contains("claim entry") + && diagnostic.message.contains("membership entry") + }), + "{failure:?}" + ); +} + +#[test] +fn an_entry_with_both_claim_and_membership_is_refused() { + shape_is_refused( + json!({"field": "organization", "claim": "sub", "operator": "equals", "membership": "membership"}), + ); +} + +#[test] +fn an_entry_with_neither_is_refused() { + shape_is_refused(json!({"field": "organization"})); +} + +#[test] +fn a_membership_entry_naming_a_type_without_membership_is_refused() { + let mut project = project(); + project.pointer_mut(ROWS).unwrap()[0]["membership"] = json!("organization"); + assert_refusal(&project, "breg.access.membership-entity-unknown", + "recordTypes[id=facility].accessProfiles[id=member].rowBoundaries[membership=organization:field=organization]"); +} + +#[test] +fn a_membership_entry_in_access_requirements_is_refused() { + for use_set in [false, true] { + let mut project = project(); + let entries = json!([{"field":"organization","membership":"membership"}]); + let rows = if use_set { + project["rowBoundarySets"] = json!({"member": entries}); + json!({"rowBoundarySet":"member"}) + } else { + entries + }; + project["recordTypes"]["facility"]["accessRequirements"] = json!({"rowBoundaries": rows}); + let failure = compile(&project).expect_err("requirements accept claim entries only"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code + == "breg.access.membership-access-requirement-unsupported"), + "{failure:?}" + ); + } +} + +const MEMBER_ROW: &str = "recordTypes[id=facility].accessProfiles[id=member].rowBoundaries"; + +#[test] +fn import_grants_refuse_membership_entries() { + let mut project = project(); + project["accessProfiles"]["member"]["permissions"]["records"][0]["operations"] = + json!(["import"]); + assert_production_refusal( + &project, + "breg.access.membership-import-unsupported", + MEMBER_ROW, + ); +} + +#[test] +fn open_record_writes_require_a_principal_boundary() { + let mut project = project(); + project["accessProfiles"]["steward"]["requiredScopes"] = json!("unrestricted"); + assert_refusal( + &project, + "breg.access.open-write-without-principal-boundary", + "recordTypes[id=facility].accessProfiles[id=steward].rowBoundaries", + ); +} + +#[test] +fn a_scopeless_profile_with_requester_clients_cannot_write_membership_records() { + let mut project = project(); + project["accessProfiles"]["steward"]["requiredScopes"] = json!("unrestricted"); + project["accessProfiles"]["steward"]["requesterClients"] = json!(["bounded-client"]); + assert_refusal( + &project, + "breg.access.scopeless-membership-source-write", + "recordTypes[id=membership].accessProfiles[id=steward].rowBoundaries", + ); +} + +#[test] +fn open_profiles_with_membership_must_use_sub() { + let mut project = project(); + project["accessProfiles"]["member"]["requiredScopes"] = json!("unrestricted"); + assert_refusal( + &project, + "breg.access.open-membership-principal-not-sub", + MEMBER_ROW, + ); +} + +#[test] +fn production_admits_and_documents_member_bounded_open_writes() { + let mut project = project(); + project["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + let member = &mut project["accessProfiles"]["member"]; + member["requiredScopes"] = json!("unrestricted"); + member["principalClaim"] = json!("sub"); + member["permissions"]["records"][0]["operations"] = json!([ + "get", + "list", + "lookup", + "create", + "patch", + "tombstone", + "batch" + ]); + member["permissions"]["records"][0]["writableFields"] = json!(["organization", "label"]); + project["recordTypes"]["facility"]["tombstone"] = json!(true); + project["recordTypes"]["facility"]["batch"] = json!({"maximumItems":4,"maximumBytes":8192}); + let registry = compile_production(&project).expect("Production admits the bounded writes"); + assert_eq!( + registry.entities()["facility"].membership_boundaries["member"].len(), + 1 + ); + let api: Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + for (record_path, method) in [ + ("/v1/records/facilities", "post"), + ("/v1/records/facilities/{record_id}", "patch"), + ("/v1/records/facilities:batch", "post"), + ] { + assert_eq!( + api["paths"][record_path][method]["responses"]["403"]["content"] + ["application/problem+json"]["examples"]["write.outside-boundary"]["value"]["code"], + "write.outside-boundary", + "{method} {record_path}" + ); + } +} + +#[test] +fn membership_entries_are_limited_and_unique_after_set_expansion() { + let mut project = project(); + let entry = project.pointer(ROWS).unwrap()[0].clone(); + project["rowBoundarySets"] = json!({"many": vec![entry; 9]}); + *project.pointer_mut(ROWS).unwrap() = json!({"rowBoundarySet":"many"}); + assert_refusal(&project, "breg.access.membership-limit", MEMBER_ROW); + assert_refusal(&project, "breg.access.membership-duplicate", + "recordTypes[id=facility].accessProfiles[id=member].rowBoundaries[membership=membership:field=organization]"); +} + +#[path = "support/action_requirements.rs"] +mod action_requirements; +#[allow(dead_code)] +#[path = "support/proposal_hooks_model.rs"] +mod proposal_hooks_model; + +fn action_project() -> Value { + let mut project = action_requirements::project(); + let records = project["recordTypes"].as_object_mut().unwrap(); + let membership = self::project()["recordTypes"]["membership"].clone(); + let mut membership = membership; + membership["primaryDataset"] = json!("test-dataset"); + membership["fields"][0]["target"] = json!("parent"); + membership + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + records.insert("membership".into(), membership); + project +} + +#[test] +fn production_admits_a_membership_bound_immediate_action_target() { + let mut project = action_project(); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + project["recordTypes"]["child"]["hooks"][0]["handler"] = + json!({"type":"url","destinationId":"record-events"}); + let registry = compile_production(&project).expect("Production admits the bounded Invoke"); + assert!(registry.actions().actions[0].permissions[0] + .targets + .iter() + .any(|target| target.entity_id == "child" && target.membership_boundaries.len() == 1)); +} + +#[test] +fn a_hook_cannot_use_an_action_grant_with_membership() { + let mut project = action_project(); + project["recordTypes"]["child"]["hooks"][0]["principal"] = json!("registrar"); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + assert_refusal(&project, "breg.access.membership-hook-unsupported", + "accessProfiles[id=registrar].permissions.actions[action=register-child].targets[recordType=child].rowBoundaries"); +} + +#[test] +fn a_timer_cannot_use_an_action_grant_with_membership() { + let mut project = action_project(); + project["recordTypes"]["child"]["timers"] = json!([{ + "id":"invoke","at":"label","invoke":"register-child","input":{} + }]); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + assert_refusal(&project, "breg.access.membership-timer-unsupported", + "accessProfiles[id=registrar].permissions.actions[action=register-child].targets[recordType=child].rowBoundaries"); +} + +#[test] +fn production_admits_membership_on_proposal_start_and_lifecycle_targets() { + let mut project = proposal_hooks_model::source(json!([])); + let fixture = self::project(); + for id in ["membership", "organization"] { + project["recordTypes"][id] = fixture["recordTypes"][id].clone(); + project["recordTypes"][id]["primaryDataset"] = json!("directory"); + } + project["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + project["recordTypes"]["target"]["fields"].as_array_mut().unwrap().push( + json!({"id":"organization","type":"reference","target":"organization","classification":"internal"}), + ); + for permission in ["actions", "proposals"] { + let mut candidate = project.clone(); + candidate["accessProfiles"]["clerk"]["permissions"][permission][0]["targets"][0] + ["rowBoundaries"] = json!([{"field":"organization","membership":"membership"}]); + let registry = + compile_production(&candidate).expect("Production admits the Proposal target"); + let action = ®istry.actions().actions[0]; + if permission == "actions" { + assert!(action.permissions[0] + .targets + .iter() + .all(|target| target.membership_boundaries.len() == 1)); + } else { + let registry_breg::model::CompiledActionExecution::Proposal { proposal } = + &action.execution + else { + panic!("expected a Proposal"); + }; + assert_eq!( + proposal.permissions[0].targets[0] + .membership_boundaries + .len(), + 1 + ); + } + } + project["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["targets"][0] + ["rowBoundaries"] = json!([{"field":"organization","membership":"membership"}]); + let target = &mut project["recordTypes"]["target"]; + target["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"active","type":"boolean","classification":"internal"})); + target["membership"] = json!({"key":"organization","principal":"name","active":"active"}); + assert_refusal( + &project, + "breg.access.membership-source-recursive", + "recordTypes[id=target].membership", + ); +} + +#[test] +fn an_encrypted_membership_principal_is_refused_at_its_declaration() { + let mut project = project(); + project["recordTypes"]["membership"]["fields"][1]["encrypted"] = json!(true); + assert_refusal( + &project, + "breg.access.membership-principal-encrypted", + "recordTypes[id=membership].membership", + ); +} + +#[test] +fn a_membership_source_with_an_incoming_read_path_is_refused_at_its_declaration() { + let mut project = project(); + project["recordTypes"]["organization"]["readPaths"] = + json!([{"id":"links","through":"membership","to":"facility","route":"links"}]); + assert_refusal( + &project, + "breg.access.membership-source-recursive", + "recordTypes[id=membership].membership", + ); +} + +#[test] +fn a_membership_source_with_a_row_requirement_is_refused_at_its_declaration() { + let mut project = project(); + project["recordTypes"]["membership"]["accessRequirements"]["rowBoundaries"] = + json!([{"field":"principal","claim":"sub","operator":"equals"}]); + assert_refusal( + &project, + "breg.access.membership-source-row-requirement", + "recordTypes[id=membership].membership", + ); +} + +#[test] +fn membership_entries_are_incompatible_with_spatial_queries() { + let mut project = project(); + project["accessProfiles"]["member"]["permissions"]["records"][0]["spatialQueries"] = + json!({"bbox": {"maximumLongitudeSpanDegrees": 5, "maximumLatitudeSpanDegrees": 5}}); + assert_refusal( + &project, + "breg.access.membership-spatial-unsupported", + MEMBER_ROW, + ); +} + +#[test] +fn a_module_defines_membership_and_its_profile_round_trips() { + use registry_breg::compiler::module_digest; + use registry_breg::contract::parse_module_yaml; + + let mut project = project(); + let grant = project["accessProfiles"]["member"]["permissions"]["records"][0].clone(); + let mut profile = grant.as_object().unwrap().clone(); + profile.remove("recordType"); + profile.insert( + "requiredScopes".into(), + json!(["records:read", "membership:use"]), + ); + profile.insert("principalClaim".into(), json!("principal")); + profile.insert("default".into(), json!(true)); + project["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("member"); + let records = project["recordTypes"].as_object_mut().unwrap(); + let mut facility = records.remove("facility").unwrap(); + facility["accessProfiles"] = json!({"member":profile}); + let module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule", + "id":"membership-core","version":"1", + "recordTypes":{"facility":facility,"membership":records.remove("membership").unwrap()} + }); + let module = parse_module_yaml(&serde_json::to_vec(&module).unwrap()).unwrap(); + let serialized = serde_json::to_value(&module).unwrap(); + assert_eq!( + serialized.pointer("/recordTypes/facility/accessProfiles/member/rowBoundaries"), + grant.get("rowBoundaries") + ); + project["modules"] = json!({"membership-core":{"version":"1","digest":module_digest(&module)}}); + let project = parse_project_yaml(&serde_json::to_vec(&project).unwrap()).unwrap(); + let registry = compile_project(&project, &[module], CompileProfile::Authoring).unwrap(); + assert_eq!( + registry.entities()["facility"].membership_boundaries["member"].len(), + 1 + ); + assert!(registry.entities()["membership"].membership.is_some()); +} + +#[test] +fn an_open_membership_target_requires_sub_even_for_immediate_invoke() { + let mut project = action_project(); + let profile = &mut project["accessProfiles"]["registrar"]; + profile["requiredScopes"] = json!("unrestricted"); + profile["principalClaim"] = json!("email"); + profile["permissions"]["actions"][0]["targets"][1]["rowBoundaries"] = + json!([{"field":"parent","membership":"membership"}]); + let failure = compile(&project).unwrap_err(); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "breg.access.open-membership-principal-not-sub"), + "{failure:?}" + ); + assert!( + failure + .diagnostics() + .iter() + .all(|diagnostic| diagnostic.code != "breg.access.membership-read-only"), + "{failure:?}" + ); +} + +#[test] +fn membership_ids_are_checked_without_repeating_invalid_values() { + let canary = "CANARY SECRET VALUE"; + for path in [ + "/recordTypes/membership/membership/key", + "/recordTypes/membership/membership/principal", + "/recordTypes/membership/membership/active", + "/accessProfiles/member/permissions/records/0/rowBoundaries/0/membership", + "/accessProfiles/member/permissions/records/0/rowBoundaries/0/field", + ] { + let mut project = project(); + *project.pointer_mut(path).unwrap() = json!(canary); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec(&project).unwrap(), + ) + .unwrap_err(); + assert!(!format!("{report:?}").contains(canary)); + } +} + +#[test] +fn membership_requirements_do_not_hide_removed_keys() { + let mut project = project(); + project["recordTypes"]["facility"]["accessRequirements"] = + json!({"rowBoundaries":[{"field":"organization","membership":"membership"}]}); + project["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"] = + json!([]); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec(&project).unwrap(), + ) + .unwrap_err(); + for code in [ + "breg.access.membership-access-requirement-unsupported", + "config.removed-key", + ] { + assert!( + report + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == code), + "{report:?}" + ); + } +} + +#[test] +fn a_membership_source_cannot_have_a_membership_bounded_action_target() { + let mut project = action_project(); + let child = &mut project["recordTypes"]["child"]; + child["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"active", "type":"boolean", "classification":"internal"})); + child["membership"] = json!({"key":"parent","principal":"label","active":"active"}); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + assert_refusal( + &project, + "breg.access.membership-source-recursive", + "recordTypes[id=child].membership", + ); +} + +#[test] +fn answer_and_cancel_are_proposal_writes_for_admission() { + for operation in ["answer", "cancel"] { + let mut project = proposal_hooks_model::source(json!([])); + project["recordTypes"]["organization"] = + self::project()["recordTypes"]["organization"].clone(); + project["recordTypes"]["organization"]["primaryDataset"] = json!("directory"); + let target = &mut project["recordTypes"]["target"]; + target["fields"].as_array_mut().unwrap().extend([ + json!({"id":"organization","type":"reference","target":"organization","classification":"internal"}), + json!({"id":"active","type":"boolean","classification":"internal"}), + ]); + target["membership"] = json!({"key":"organization","principal":"name","active":"active"}); + project["accessProfiles"]["clerk"]["requiredScopes"] = json!("unrestricted"); + project["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = + json!(["get", operation]); + let location = "accessProfiles[id=clerk].permissions.proposals[action=correct-name].targets[recordType=target].rowBoundaries"; + assert_refusal( + &project, + "breg.access.open-write-without-principal-boundary", + location, + ); + assert_refusal( + &project, + "breg.access.scopeless-membership-source-write", + location, + ); + } +} + +#[test] +fn admission_diagnostics_do_not_render_malformed_target_references() { + let mut project = action_project(); + let profile = &mut project["accessProfiles"]["registrar"]; + profile["requiredScopes"] = json!("unrestricted"); + profile["permissions"]["actions"][0]["targets"][1]["recordType"] = json!("CANARY SECRET VALUE"); + let failure = compile(&project).unwrap_err(); + assert!(!format!("{failure:?}").contains("CANARY SECRET VALUE")); +} diff --git a/crates/registry-breg/tests/native_plan_security.rs b/crates/registry-breg/tests/native_plan_security.rs index 06aff724ff..41f43c4e30 100644 --- a/crates/registry-breg/tests/native_plan_security.rs +++ b/crates/registry-breg/tests/native_plan_security.rs @@ -19,7 +19,7 @@ fn source() -> Value { {"id":"unbound","type":"string","maximumLength":64,"classification":"restricted"}], "plan":{"type":"function","function":"calculate","inputs":["label"], "writes":[{"id":"item","target":{"recordType":"item"},"operation":"create","fields":["label"]}]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"actions":[{"action":"register-item","operations":["invoke"],"targets":[{"recordType":"item","rowBoundaries":"unrestricted"}],"results":["item"]}]}}}}) } fn compile(script: &str) -> Result { diff --git a/crates/registry-breg/tests/odrl_export.rs b/crates/registry-breg/tests/odrl_export.rs index e4788c9d97..b1af7928ef 100644 --- a/crates/registry-breg/tests/odrl_export.rs +++ b/crates/registry-breg/tests/odrl_export.rs @@ -338,28 +338,6 @@ fn row_membership_and_consent_restrictions_omit_the_complete_read_grant() { json!([]) ); - let membership = compile_project( - &parse_project_yaml(MEMBERSHIP).unwrap(), - &[], - CompileProfile::Authoring, - ) - .unwrap(); - let membership_export = export_odrl(&membership, Some("member")).unwrap(); - let membership_reads = membership_export.coverage["grants"] - .as_array() - .unwrap() - .iter() - .filter(|grant| grant["operation"] == "get" || grant["operation"] == "list") - .collect::>(); - assert_eq!(membership_reads.len(), 2); - assert!(membership_reads.iter().all(|grant| { - grant["status"] == "omitted" - && grant["reasons"] - .as_array() - .unwrap() - .contains(&json!("membership-boundaries")) - })); - let consent = compile_with_modules(CONSENT, &[CONSENT_PERSON, CONSENT_CORE]); let consent_export = export_odrl(&consent, Some("food-targeting")).unwrap(); assert!(consent_export.coverage["grants"] @@ -691,3 +669,32 @@ fn profile_declares_every_emitted_extension_and_adopts_read() { "one collection and thirteen term definitions" ); } + +#[test] +fn a_membership_only_read_grant_is_omitted_from_the_odrl_export() { + let membership = compile_project( + &parse_project_yaml(MEMBERSHIP).unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap(); + let membership_export = export_odrl(&membership, Some("member")).unwrap(); + let membership_reads = membership_export.coverage["grants"] + .as_array() + .unwrap() + .iter() + .filter(|grant| grant["operation"] == "get" || grant["operation"] == "list") + .collect::>(); + assert_eq!(membership_reads.len(), 2); + assert!(membership_reads.iter().all(|grant| { + grant["status"] == "omitted" + && grant["reasons"] + .as_array() + .unwrap() + .contains(&json!("membership-boundaries")) + })); + assert_eq!( + document(&membership_export, "generated/odrl/policies.jsonld")["@graph"], + json!([]) + ); +} diff --git a/crates/registry-breg/tests/ordered_plan_contract.rs b/crates/registry-breg/tests/ordered_plan_contract.rs index ec46c737c8..ec27b9eb90 100644 --- a/crates/registry-breg/tests/ordered_plan_contract.rs +++ b/crates/registry-breg/tests/ordered_plan_contract.rs @@ -16,7 +16,7 @@ fn project() -> Value { {"id":"parent","type":"reference","target":"entry","classification":"internal"}]}}, "actions":{"create-pair": {"execution":{"mode":"immediate"},"inputs":[{"id":"name","type":"string","maximumLength":32,"required":true,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"z-result","target":{"recordType":"entry"},"operation":"create","set":{"name":{"fromInput":"name"}}},{"id":"a-result","target":{"recordType":"entry"},"operation":"create","set":{"name":{"fromInput":"name"}}}]}}}, - "accessProfiles":{"creator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"create-pair","operations":["invoke"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}],"results":["z-result","a-result"]}]}}} + "accessProfiles":{"creator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"create-pair","operations":["invoke"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}],"results":["z-result","a-result"]}]}}} }) } fn compile( diff --git a/crates/registry-breg/tests/package_change_plan.rs b/crates/registry-breg/tests/package_change_plan.rs index dc9f3ab060..95ffa2bc6c 100644 --- a/crates/registry-breg/tests/package_change_plan.rs +++ b/crates/registry-breg/tests/package_change_plan.rs @@ -846,10 +846,10 @@ fn metadata_only_access_or_disclosure_changes_create_empty_applicable_plans() { fn complete_extension_surface_modules_are_order_independent() { let field_module = parse_module_yaml(br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"field-extension","version":"1","extendRecordTypes":{"asset": {"fields":[{"id":"status","type":"string","maximumLength":16,"classification":"internal"}],"constraints":[{"type":"unique","id":"status-unique","fields":["status"]}],"indexes":[{"id":"status-idx","fields":["status"]}]}}}"#) .expect("field extension parses"); - let event_module = parse_module_yaml(br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"event-extension","version":"1","extendRecordTypes":{"asset": {"accessProfiles":{"auditor": {"principalClaim":"principal","operations":["get","list"],"readableFields":["code","status"],"writableFields":[], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}},"hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code","status"],"handler":{"type":"url","destinationId":"package-change-events"}}]}},"recordTypes":{"site": {"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}}}"#) + let event_module = parse_module_yaml(br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"event-extension","version":"1","extendRecordTypes":{"asset": {"accessProfiles":{"auditor": {"principalClaim":"principal","operations":["get","list"],"readableFields":["code","status"],"writableFields":[], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}},"hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code","status"],"handler":{"type":"url","destinationId":"package-change-events"}}]}},"recordTypes":{"site": {"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"], "requiredScopes":"unrestricted","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}]}}}}}"#) .expect("event extension parses"); let project_bytes = format!( - r#"{{"datasets":{{"neutral-registry": {{}}}},"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject","project":{{"id":"neutral-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://package.example.test"}},"package":{{"sourceRevision":"{SOURCE_REVISION}"}},"manifestProjection":{{"accessProfile":"reader","classificationCeiling":"internal","catalog":{{"baseUrl":"https://package.example.test","title":"Neutral Registry Catalog","publisher":{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}}},"authorities":[{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}],"publicServices":[{{"id":"neutral-registry-service","title":"Neutral Registry Catalog","competentAuthority":"neutral-registry-authority"}}],"datasets":[{{"id":"neutral-registry","title":"Neutral Registry Dataset","owner":"Package Test Publisher","status":"active"}}],"dataServices":[{{"id":"neutral-registry-data-service","title":"Neutral Registry Catalog","endpointUrl":"https://package.example.test","servesDatasets":["neutral-registry"]}}]}},"recordTypes":{{"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}]}}}},"accessProfiles":{{"reader":{{"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{{"records":[{{"rowBoundaries": "unrestricted", "recordType":"asset","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}]}}}}}},"modules":{{"field-extension":{{"version":"1","digest":"{}"}},"event-extension":{{"version":"1","digest":"{}"}}}}}}"#, + r#"{{"datasets":{{"neutral-registry": {{}}}},"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject","project":{{"id":"neutral-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://package.example.test"}},"package":{{"sourceRevision":"{SOURCE_REVISION}"}},"manifestProjection":{{"accessProfile":"reader","classificationCeiling":"internal","catalog":{{"baseUrl":"https://package.example.test","title":"Neutral Registry Catalog","publisher":{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}}},"authorities":[{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}],"publicServices":[{{"id":"neutral-registry-service","title":"Neutral Registry Catalog","competentAuthority":"neutral-registry-authority"}}],"datasets":[{{"id":"neutral-registry","title":"Neutral Registry Dataset","owner":"Package Test Publisher","status":"active"}}],"dataServices":[{{"id":"neutral-registry-data-service","title":"Neutral Registry Catalog","endpointUrl":"https://package.example.test","servesDatasets":["neutral-registry"]}}]}},"recordTypes":{{"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}},{{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}}]}}}},"accessProfiles":{{"reader":{{"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{{"records":[{{"rowBoundaries": [{{"field":"owner","claim":"principal","operator":"equals"}}], "recordType":"asset","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]}}]}}}}}},"modules":{{"field-extension":{{"version":"1","digest":"{}"}},"event-extension":{{"version":"1","digest":"{}"}}}}}}"#, module_digest(&field_module), module_digest(&event_module) ); @@ -2063,7 +2063,8 @@ fn vocabulary_registry(vocabulary: &str, values: &[&str]) -> CompiledRegistry { "vocabulary": vocabulary, "required": true, "classification": "internal" - } + }, + {"id": "owner", "type": "string", "maximumLength": 255, "classification": "internal"} ] }}, "accessProfiles": {"writer": { @@ -2074,8 +2075,8 @@ fn vocabulary_registry(vocabulary: &str, values: &[&str]) -> CompiledRegistry { "recordType": "entry", "operations": ["create", "get", "list", "patch"], "readableFields": ["status"], - "writableFields": ["status"], - "rowBoundaries": "unrestricted" + "writableFields": ["status", "owner"], + "rowBoundaries": [{"field": "owner", "claim": "registry_principal", "operator": "equals"}] }]} }} }); @@ -2132,7 +2133,7 @@ fn field_registry(field: serde_json::Value) -> CompiledRegistry { "primaryDataset": "test-dataset", "route": "entries", "mutationMode": "mutable", - "fields": [field] + "fields": [field, {"id": "owner", "type": "string", "maximumLength": 255, "classification": "internal"}] }}, "accessProfiles": {"writer": { "default": true, @@ -2142,8 +2143,8 @@ fn field_registry(field: serde_json::Value) -> CompiledRegistry { "recordType": "entry", "operations": ["create", "get", "list", "patch"], "readableFields": ["note"], - "writableFields": ["note"], - "rowBoundaries": "unrestricted" + "writableFields": ["note", "owner"], + "rowBoundaries": [{"field": "owner", "claim": "registry_principal", "operator": "equals"}] }]} }} }); @@ -2238,6 +2239,7 @@ fn geojson_source(binding: Option<&str>) -> SourceFixture { serde_json::from_slice(&module_bytes(Variant::Base)).unwrap(); let entity = &mut module["recordTypes"]["asset"]; let fields = entity["fields"].as_array_mut().unwrap(); + fields.retain(|field| field["id"] != "owner"); for id in ["location", "alternate"] { fields.push(serde_json::json!({ "id": id, "type": "crs84-point", "precision": 9, "classification": "internal" @@ -2245,6 +2247,7 @@ fn geojson_source(binding: Option<&str>) -> SourceFixture { } entity["accessProfiles"]["reader"]["operations"] = serde_json::json!(["get"]); entity["accessProfiles"]["reader"]["writableFields"] = serde_json::json!([]); + entity["accessProfiles"]["reader"]["rowBoundaries"] = serde_json::json!("unrestricted"); entity["accessProfiles"]["reader"]["readableFields"] = serde_json::json!(["code", "location", "alternate"]); if let Some(binding) = binding { @@ -2347,7 +2350,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::OptionalField => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"color","type":"string","maximumLength":16,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2355,7 +2358,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RequiredField => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"batch","type":"string","maximumLength":16,"required":true,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2363,7 +2366,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RequiredAndOptionalFields => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"batch","type":"string","maximumLength":16,"required":true,"classification":"internal"},{"id":"color","type":"string","maximumLength":16,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2371,7 +2374,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceConstraintIndex => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"site","type":"reference","target":"site","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, r#","constraints":[{"type":"unique","id":"code-unique","fields":["code"]}]"#, r#","indexes":[{"id":"code-idx","fields":["code"]}]"#, "", @@ -2379,7 +2382,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceConstraintIndexReordered => asset_entity( r#"{"id":"site","type":"reference","target":"site","classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"code","type":"string","maximumLength":8,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["list","get","create"],"writableFields":["code"],"readableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["list","get","create"],"writableFields":["code","owner"],"readableFields":["code"]"#, r#","constraints":[{"fields":["code"],"id":"code-unique","type":"unique"}]"#, r#","indexes":[{"fields":["code"],"id":"code-idx"}]"#, "", @@ -2387,7 +2390,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::FieldRemoved => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2395,7 +2398,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TypeChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"string","maximumLength":8,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2403,7 +2406,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::PlaintextSecret => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"secret","type":"string","maximumLength":64,"classification":"restricted"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2411,7 +2414,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::EncryptedStructuredSecret => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"secret","type":"structured","maximumBytes":1024,"schema":{"type":"object","additionalProperties":false},"classification":"restricted","encrypted":true}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2419,7 +2422,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RouteChanged => asset_entity( base_asset_fields(), r#""route":"equipment""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2427,7 +2430,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::EntityClassificationChanged => asset_entity( base_asset_fields(), r#""route":"assets","classification":"restricted""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2435,7 +2438,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ClassificationChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"restricted"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2443,7 +2446,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::AuthorizationChanged => asset_entity( base_asset_fields(), r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"subject","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"subject","rowBoundaries":[{"field":"owner","claim":"subject","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2452,7 +2455,7 @@ fn module_bytes(variant: Variant) -> Vec { base_asset_fields(), r#""route":"assets""#, "mutable", - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2460,7 +2463,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TemporalChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"required":true,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, r#","constraints":[{"type":"temporal-non-overlap","id":"code-time","scopeFields":["code"],"startField":"valid-from","endField":"valid-to"}]"#, "", r#","temporal":{"startField":"valid-from","endField":"valid-to"}"#, @@ -2468,7 +2471,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TemporalRoleBase => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", "", @@ -2476,7 +2479,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TemporalRoleChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal","validTimeRole":"valid-from"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", "", @@ -2484,7 +2487,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RankRequired => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","required":true,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2492,7 +2495,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceTargetBase => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"home-site","type":"reference","target":"site","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2500,7 +2503,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceTargetChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"home-site","type":"reference","target":"location","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2508,7 +2511,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::MetadataOnlyBase => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", r#","hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code"],"handler":{"type":"url","destinationId":"package-change-events"}}]"#, @@ -2517,7 +2520,7 @@ fn module_bytes(variant: Variant) -> Vec { r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"restricted"},{"id":"valid-from","type":"date","required":true,"classification":"internal","validTimeRole":"valid-from"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"equipment","classification":"restricted","accessRequirements":{"requiredScopes":["asset:read"]}"#, "mutable", - r#""principalClaim":"subject","requiredScopes":["asset:read"],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""principalClaim":"subject","rowBoundaries":[{"field":"owner","claim":"subject","operator":"equals"}],"requiredScopes":["asset:read"],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", r#","hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code","rank"],"handler":{"type":"url","destinationId":"package-change-events"}}]"#, @@ -2525,7 +2528,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::Base | Variant::NewEntity => asset_entity( base_asset_fields(), r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2584,20 +2587,20 @@ fn asset_entity_with_mode( temporal: &str, ) -> String { format!( - r#""asset":{{"primaryDataset":"neutral-registry",{route},"mutationMode":"{mutation_mode}","fields":[{fields}]{constraints}{indexes},"accessProfiles":{{"reader":{{"rowBoundaries":"unrestricted",{access}}}}}{temporal}}}"# + r#""asset":{{"primaryDataset":"neutral-registry",{route},"mutationMode":"{mutation_mode}","fields":[{fields},{{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}}]{constraints}{indexes},"accessProfiles":{{"reader":{{{access}}}}}{temporal}}}"# ) } fn site_entity() -> &'static str { - r#""site":{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#""site":{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"], "requiredScopes":"unrestricted"}}}"# } fn location_entity() -> &'static str { - r#""location":{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#""location":{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"], "requiredScopes":"unrestricted"}}}"# } fn placement_entity() -> &'static str { - r#""placement":{"primaryDataset":"neutral-registry","route":"placements","mutationMode":"create-only","fields":[{"id":"asset","type":"reference","target":"asset","required":true,"classification":"internal"},{"id":"site","type":"reference","target":"site","required":true,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["asset","site"],"writableFields":["asset","site"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#""placement":{"primaryDataset":"neutral-registry","route":"placements","mutationMode":"create-only","fields":[{"id":"asset","type":"reference","target":"asset","required":true,"classification":"internal"},{"id":"site","type":"reference","target":"site","required":true,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["asset","site"],"writableFields":["asset","site","owner"], "requiredScopes":"unrestricted"}}}"# } fn build_request( diff --git a/crates/registry-breg/tests/postgres_access_log.rs b/crates/registry-breg/tests/postgres_access_log.rs index 526e842389..c41c65470b 100644 --- a/crates/registry-breg/tests/postgres_access_log.rs +++ b/crates/registry-breg/tests/postgres_access_log.rs @@ -354,6 +354,10 @@ fn token(idp: &MockIdp, client: &str, subject: &str) -> String { idp.mint_token(json!({"aud":AUDIENCE,"sub":subject,"client_id":client,"scope":"registry.read","registry_actor_kind":"service","registry_purpose":PURPOSE})) } +fn writer_token(idp: &MockIdp, client: &str, subject: &str) -> String { + idp.mint_token(json!({"aud":AUDIENCE,"sub":subject,"client_id":client,"scope":"registry.read records:write","registry_actor_kind":"service","registry_purpose":PURPOSE})) +} + async fn send( app: &Router, token: &str, @@ -973,7 +977,7 @@ fn compiled_with_history() -> CompiledRegistry { "revisionAccess":true,"rowBoundaries":"unrestricted"} ] }}, - "steward": {"principalClaim":"sub","requiredScopes":"unrestricted","requiredPurposes":[PURPOSE],"permissions":{ + "steward": {"principalClaim":"sub","requiredScopes":["records:write"],"requiredPurposes":[PURPOSE],"permissions":{ "records":[ {"recordType":"entry","operations":["create"],"readableFields":["subject","label"], "writableFields":["subject","label"],"rowBoundaries":"unrestricted"} @@ -1136,7 +1140,7 @@ async fn logged_operations(db: &TestDatabase, record: &str) -> Vec { #[tokio::test] async fn snapshot_and_revision_reads_write_subject_access_log_entries() { let (db, app, idp, registry) = setup_with_history().await; - let steward = token(&idp, "agency", "steward"); + let steward = writer_token(&idp, "agency", "steward"); let reader = token(&idp, "agency", "officer"); let request = Request::builder() .method(Method::POST) @@ -1311,7 +1315,7 @@ async fn head_on_subject_access_log_reads_is_refused_without_a_journaled_read() #[tokio::test] async fn head_on_history_reads_is_refused_without_a_journaled_read() { let (db, app, idp, _) = setup_with_history().await; - let steward = token(&idp, "agency", "steward"); + let steward = writer_token(&idp, "agency", "steward"); let reader = token(&idp, "agency", "officer"); let request = Request::builder() .method(Method::POST) @@ -1729,7 +1733,7 @@ fn compiled_with_writes() -> CompiledRegistry { }; let entry_writes = json!(["get", "create", "patch", "batch", "tombstone"]); let profile = |reason: bool, records: Value| { - json!({"principalClaim":"sub","requiredScopes":"unrestricted", + json!({"principalClaim":"sub","requiredScopes":["records:write"], "requiredPurposes":[PURPOSE],"requireAccessReason":reason, "permissions":{"records":records}}) }; @@ -1854,7 +1858,7 @@ async fn logged_entries(db: &TestDatabase) -> Vec<(String, String, String, Optio #[tokio::test] async fn each_direct_write_under_a_reasoned_profile_logs_one_write_entry_with_its_reason() { let (db, app, idp, registry) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let (first, etag) = create_entry(&app, &clerk, "clerk", Some("create reason")).await; let (status, body, etag) = write_as( @@ -1959,7 +1963,7 @@ async fn each_direct_write_under_a_reasoned_profile_logs_one_write_entry_with_it #[tokio::test] async fn a_write_under_a_profile_without_the_flag_logs_no_write_entry() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let steward = token(&idp, "agency", "steward"); + let steward = writer_token(&idp, "agency", "steward"); let (record, etag) = create_entry(&app, &steward, "steward", None).await; let (status, body, _) = write_as( &app, @@ -1985,7 +1989,7 @@ async fn a_write_under_a_profile_without_the_flag_logs_no_write_entry() { #[tokio::test] async fn a_type_without_an_access_log_requires_the_reason_and_stores_nothing() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let note = || { Some(( "application/json", @@ -2030,7 +2034,7 @@ async fn a_rolled_back_write_leaves_no_write_entry() { Some(MutationFaultPoint::BeforeCommit), ) .await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let (status, body, _) = write_as( &app, &clerk, @@ -2055,7 +2059,7 @@ async fn a_rolled_back_write_leaves_no_write_entry() { #[tokio::test] async fn a_write_entry_raises_no_read_alert() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let (record, _) = create_entry(&app, &clerk, "clerk", Some("create reason")).await; assert_eq!(logged_entries(&db).await.len(), 1); assert_eq!(read_alerts(&db).await, []); @@ -2079,8 +2083,8 @@ async fn a_write_entry_raises_no_read_alert() { #[tokio::test] async fn write_entries_keep_the_retention_and_exemption_delay_of_read_entries() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); - let investigator = token(&idp, "agency", "investigator"); + let clerk = writer_token(&idp, "agency", "clerk"); + let investigator = writer_token(&idp, "agency", "investigator"); let (prompt, _) = create_entry(&app, &clerk, "clerk", Some("create reason")).await; let (delayed, _) = create_entry(&app, &investigator, "investigator", Some("investigation")).await; diff --git a/crates/registry-breg/tests/postgres_action_handlers.rs b/crates/registry-breg/tests/postgres_action_handlers.rs index 5422bf3d99..857a9c3de9 100644 --- a/crates/registry-breg/tests/postgres_action_handlers.rs +++ b/crates/registry-breg/tests/postgres_action_handlers.rs @@ -1106,7 +1106,7 @@ async fn absent_optional_copy_has_the_same_safe_failure_at_invoke_and_submit() { let claims = VerifiedRequestClaims::authenticated_with_actor_kind( "sub", "author", - BTreeSet::new(), + BTreeSet::from(["entries:write".to_owned()]), None, BTreeMap::new(), registry_platform_oidc::ActorKind::Human, diff --git a/crates/registry-breg/tests/postgres_batch.rs b/crates/registry-breg/tests/postgres_batch.rs index 40b4d1b2ad..6e092b3eb3 100644 --- a/crates/registry-breg/tests/postgres_batch.rs +++ b/crates/registry-breg/tests/postgres_batch.rs @@ -957,7 +957,7 @@ fn compiled_timer_batch_registry() -> registry_breg::CompiledRegistry { .remove("service-editor") .expect("the future-activation example has a service-editor profile"); source["accessProfiles"]["operator"] = renamed; - source["accessProfiles"]["operator"]["requiredScopes"] = json!("unrestricted"); + source["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); source["accessProfiles"]["operator"]["permissions"]["records"][0]["operations"] = json!(["create", "get", "list", "patch", "tombstone", "batch"]); let bytes = serde_json::to_vec(&source).expect("timer batch fixture serializes"); @@ -1074,7 +1074,7 @@ fn compiled_registry_with_create_policy( {"phase":"after","id":"widget-patched","trigger":"patched","projection":["label","quantity"]} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management","case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","patch","batch"], @@ -1082,7 +1082,7 @@ fn compiled_registry_with_create_policy( "writableFields":["jurisdiction","label","secret","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"batch-creator": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"batch-creator": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","batch"], @@ -1090,7 +1090,7 @@ fn compiled_registry_with_create_policy( "writableFields":["jurisdiction","label","secret","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","patch","batch"], @@ -1173,7 +1173,7 @@ fn claims(principal: &str, purpose: &str, jurisdiction: &str) -> VerifiedRequest VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some(purpose.to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_client_capabilities.rs b/crates/registry-breg/tests/postgres_client_capabilities.rs index 181098ffa8..c497239b04 100644 --- a/crates/registry-breg/tests/postgres_client_capabilities.rs +++ b/crates/registry-breg/tests/postgres_client_capabilities.rs @@ -44,7 +44,7 @@ fn registry() -> registry_breg::CompiledRegistry { "temporal":{"startField":"valid-from","endField":"valid-to"}, "constraints":[{"type":"temporal-non-overlap","scopeFields":["code"],"startField":"valid-from","endField":"valid-to"}] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{"recordType":"entry","operations":["create","get","list","patch","batch","tombstone","revisions","snapshot"], "readableFields":["code","label","valid-from","valid-to"],"writableFields":["code","label","valid-from","valid-to"], @@ -61,7 +61,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "sdk-fixture-operator", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".into()), BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/postgres_compiled_schema.rs b/crates/registry-breg/tests/postgres_compiled_schema.rs index 605d6d50c9..20573b4e05 100644 --- a/crates/registry-breg/tests/postgres_compiled_schema.rs +++ b/crates/registry-breg/tests/postgres_compiled_schema.rs @@ -2213,7 +2213,7 @@ fn additive_catalog_registry(variant: AdditiveCatalogVariant) -> registry_breg:: "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2253,7 +2253,7 @@ fn length_catalog_registry(max_length: u32) -> registry_breg::CompiledRegistry { "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2290,7 +2290,7 @@ fn string_length_catalog_registry(min_length: u32) -> registry_breg::CompiledReg "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2339,7 +2339,7 @@ fn vocabulary_catalog_registry_with_constraints( "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2377,7 +2377,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { } }, "accessProfiles":{ - "writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{ "records":[ @@ -2471,7 +2471,7 @@ fn compiled_action_registry() -> registry_breg::CompiledRegistry { "accessProfiles": {"operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": { "actions": [{ "action": "relabel-entry", @@ -2507,7 +2507,7 @@ fn derived_registry() -> registry_breg::CompiledRegistry { ] }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"household","operations":["create","get","list"], "readableFields":["tenant","size","child-count","observed-on"], "writableFields":["tenant","size"], diff --git a/crates/registry-breg/tests/postgres_constraint_races.rs b/crates/registry-breg/tests/postgres_constraint_races.rs index 19a0463c6c..3a33386b3f 100644 --- a/crates/registry-breg/tests/postgres_constraint_races.rs +++ b/crates/registry-breg/tests/postgres_constraint_races.rs @@ -491,7 +491,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "startField":"valid-from","endField":"valid-to" }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["operations"], + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"parent","operations":["create","get"],"readableFields":["name"],"writableFields":["name"], "rowBoundaries": "unrestricted" diff --git a/crates/registry-breg/tests/postgres_data_export.rs b/crates/registry-breg/tests/postgres_data_export.rs index c1c09023a8..2ebf791d9f 100644 --- a/crates/registry-breg/tests/postgres_data_export.rs +++ b/crates/registry-breg/tests/postgres_data_export.rs @@ -74,6 +74,7 @@ async fn real_postgres_export_is_authenticated_projected_audited_and_resumable() "aud":AUDIENCE, "registry_actor_kind":"service", "registry_principal":PRINCIPAL_CANARY, + "scope":"records:write", "purpose":"data-export", "jurisdictions":["north"] })); @@ -81,6 +82,7 @@ async fn real_postgres_export_is_authenticated_projected_audited_and_resumable() "aud":AUDIENCE, "registry_actor_kind":"service", "registry_principal":PRINCIPAL_CANARY, + "scope":"records:write", "purpose":"other-purpose", "jurisdictions":["north"] })); @@ -380,7 +382,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "constraints":[{"type":"unique","fields":["code"]}], "hooks":[{"phase":"after","id":"entry-created","trigger":"created","projection":["code"]}] }}, - "accessProfiles":{PROFILE: { "principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{PROFILE: { "principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["data-export"], "permissions":{"records":[{ "recordType":"entry", diff --git a/crates/registry-breg/tests/postgres_data_facility.rs b/crates/registry-breg/tests/postgres_data_facility.rs index fdd03075c6..4f47b82343 100644 --- a/crates/registry-breg/tests/postgres_data_facility.rs +++ b/crates/registry-breg/tests/postgres_data_facility.rs @@ -21,13 +21,15 @@ const PROFILE: &str = "facility-operator"; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_facility_import_is_authenticated_chunked_resumable_and_race_safe() { let harness = PilotHarness::start("facility").await; - let north_token = harness.token( + let north_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["north-district"]))], + &["registry:facility:operate"], ); - let south_token = harness.token( + let south_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["south-district"]))], + &["registry:facility:operate"], ); let facility_id = create( &harness, diff --git a/crates/registry-breg/tests/postgres_derived_values.rs b/crates/registry-breg/tests/postgres_derived_values.rs index c9af919b93..f132f784ea 100644 --- a/crates/registry-breg/tests/postgres_derived_values.rs +++ b/crates/registry-breg/tests/postgres_derived_values.rs @@ -291,7 +291,7 @@ async fn real_postgres_derived_values_enforce_declared_contracts() { VerifiedRequestClaims::authenticated( "registry_principal", "test-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::new(), ) @@ -343,7 +343,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { ] }] }}, - "accessProfiles":{"reader": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"reader": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get","list"], "readableFields":["scenario","short-code","description","amount","count","state"], diff --git a/crates/registry-breg/tests/postgres_event_record_examples.rs b/crates/registry-breg/tests/postgres_event_record_examples.rs index ce4822e954..7504d44615 100644 --- a/crates/registry-breg/tests/postgres_event_record_examples.rs +++ b/crates/registry-breg/tests/postgres_event_record_examples.rs @@ -277,7 +277,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "registrar-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::::new(), ) diff --git a/crates/registry-breg/tests/postgres_event_record_reader.rs b/crates/registry-breg/tests/postgres_event_record_reader.rs index 2c92ba18cb..507846ea0f 100644 --- a/crates/registry-breg/tests/postgres_event_record_reader.rs +++ b/crates/registry-breg/tests/postgres_event_record_reader.rs @@ -92,7 +92,7 @@ fn record_permissions() -> String { fn compile_reader(declarations: &str, other_permissions: &str) -> registry_breg::CompiledRegistry { let project = format!( "{declarations}\naccessProfiles:\n reader:\n default: true\n \ - principalClaim: registry_principal\n requiredScopes: unrestricted\n \ + principalClaim: registry_principal\n requiredScopes: [records:write]\n \ permissions:\n{other_permissions} records:\n{}", record_permissions() ); @@ -128,7 +128,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "event-record-reader-fixture", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/postgres_field_encryption.rs b/crates/registry-breg/tests/postgres_field_encryption.rs index f9a058f48c..9f0d11e452 100644 --- a/crates/registry-breg/tests/postgres_field_encryption.rs +++ b/crates/registry-breg/tests/postgres_field_encryption.rs @@ -139,7 +139,7 @@ accessProfiles: operator: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [registry:field-encryption:operate] requiredPurposes: [case-management] permissions: records: diff --git a/crates/registry-breg/tests/postgres_fixture_journeys.rs b/crates/registry-breg/tests/postgres_fixture_journeys.rs index c3d038eced..e3033f6012 100644 --- a/crates/registry-breg/tests/postgres_fixture_journeys.rs +++ b/crates/registry-breg/tests/postgres_fixture_journeys.rs @@ -89,6 +89,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -101,6 +102,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: list} @@ -112,6 +114,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -131,6 +134,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -142,6 +146,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -154,6 +159,7 @@ journeys: accessProfile: write-only-end claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -1638,6 +1644,7 @@ fn operator_token(idp: &MockIdp, purpose: bool) -> String { "registry_actor_kind": "service", "registry_principal": "fixture-operator", "jurisdiction": "zone-a", + "scope": "fixture:write", }); if purpose { claims["purpose"] = json!("case-management"); @@ -1847,7 +1854,7 @@ fn compiled_compare_constraint_fixture() -> (registry_breg::CompiledRegistry, Ve 1, ); let write_only_end = format!( - " write-only-end:\n principalClaim: registry_principal\n requiredScopes: unrestricted\n requiredPurposes: [case-management]\n permissions:\n records:\n - recordType: widget\n operations: [create]\n readableFields: [{fields}, valid-from]\n writableFields: [{fields}, valid-from, valid-to]\n rowBoundaries:\n - {{field: jurisdiction, claim: jurisdiction, operator: equals}}\n" + " write-only-end:\n principalClaim: registry_principal\n requiredScopes: [fixture:write]\n requiredPurposes: [case-management]\n permissions:\n records:\n - recordType: widget\n operations: [create]\n readableFields: [{fields}, valid-from]\n writableFields: [{fields}, valid-from, valid-to]\n rowBoundaries:\n - {{field: jurisdiction, claim: jurisdiction, operator: equals}}\n" ); assert!( project_source.contains("right: valid-to}") diff --git a/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs b/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs index e2f7de7a34..03a5f7510f 100644 --- a/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs +++ b/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs @@ -156,7 +156,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "generate":{"type":"sequence","prefix":"REG-","minimumDigits":4,"scope":["jurisdiction"]}} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get","batch"], @@ -232,7 +232,7 @@ fn writer_claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "generated-identifier-writer", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_generated_identifiers.rs b/crates/registry-breg/tests/postgres_generated_identifiers.rs index 04919a98db..867b8714b7 100644 --- a/crates/registry-breg/tests/postgres_generated_identifiers.rs +++ b/crates/registry-breg/tests/postgres_generated_identifiers.rs @@ -49,7 +49,7 @@ fn registry_with_limits( "generate":{"type":"random","prefix":"R-","length":12}} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"sub","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"sub","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get"], "readableFields":["jurisdiction","issued-at","public-id","daily-id","receipt-code"], diff --git a/crates/registry-breg/tests/postgres_history_commit.rs b/crates/registry-breg/tests/postgres_history_commit.rs index 7202ae41ba..26d05fabb5 100644 --- a/crates/registry-breg/tests/postgres_history_commit.rs +++ b/crates/registry-breg/tests/postgres_history_commit.rs @@ -710,7 +710,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"writer": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"membership", diff --git a/crates/registry-breg/tests/postgres_history_erasure.rs b/crates/registry-breg/tests/postgres_history_erasure.rs index 3b5498ea4e..9fe237d6f8 100644 --- a/crates/registry-breg/tests/postgres_history_erasure.rs +++ b/crates/registry-breg/tests/postgres_history_erasure.rs @@ -2652,7 +2652,7 @@ async fn snapshot_client_http( let claims = registry_breg::api::VerifiedRequestClaims::authenticated( "registry_principal", "history-erasure-sdk-reader", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("operations".to_owned()), BTreeMap::new(), ) @@ -2692,7 +2692,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"writer": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"membership", diff --git a/crates/registry-breg/tests/postgres_history_migration.rs b/crates/registry-breg/tests/postgres_history_migration.rs index 2540a504f8..bb6c483b0b 100644 --- a/crates/registry-breg/tests/postgres_history_migration.rs +++ b/crates/registry-breg/tests/postgres_history_migration.rs @@ -987,7 +987,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::StatusRestricted => "restricted", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"history-migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","required":true,"maximumLength":8,"classification":"internal"}},{{"id":"status","type":"string","required":true,"maximumLength":16,"classification":"{status_classification}"}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list","revisions"],"revisionAccess":true,"readableFields":["code"],"writableFields":["code","status"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"history-migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","required":true,"maximumLength":8,"classification":"internal"}},{{"id":"status","type":"string","required":true,"maximumLength":16,"classification":"{status_classification}"}}],"accessProfiles":{{"reader":{{"requiredScopes":["records:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list","revisions"],"revisionAccess":true,"readableFields":["code"],"writableFields":["code","status"]}}}}}}}}}}"# ) .into_bytes() } @@ -1209,7 +1209,7 @@ fn history_claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "principal", "package-reader", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-review".to_owned()), BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/postgres_history_rebaseline.rs b/crates/registry-breg/tests/postgres_history_rebaseline.rs index d8383e9089..0e6898302b 100644 --- a/crates/registry-breg/tests/postgres_history_rebaseline.rs +++ b/crates/registry-breg/tests/postgres_history_rebaseline.rs @@ -1339,7 +1339,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"writer": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"membership", diff --git a/crates/registry-breg/tests/postgres_hook_changes.rs b/crates/registry-breg/tests/postgres_hook_changes.rs index e0b899aa60..9895817a3b 100644 --- a/crates/registry-breg/tests/postgres_hook_changes.rs +++ b/crates/registry-breg/tests/postgres_hook_changes.rs @@ -175,7 +175,7 @@ fn hook_project_json( }} }}}}, "accessProfiles":{{"operator":{{ - "default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{{"records":[{{ "recordType":"case","operations":["create","get","list"], @@ -184,7 +184,7 @@ fn hook_project_json( "rowBoundaries":[{{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}}] }}]}} }},"case-hook":{{ - "principalClaim":"registry_principal","requiredScopes":"unrestricted", + "principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{{"actions":[{{ "action":"open-followup","operations":["invoke"], "targets":[{{"recordType":"followup","rowBoundaries":"unrestricted"}}], @@ -2466,6 +2466,90 @@ async fn real_postgres_a_hook_without_a_principal_compiles_and_delivers() { receiver.stop().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn real_postgres_hook_proposal_refuses_a_claim_bounded_action_target() { + let receiver = HttpsReceiver::start().await; + let hooks = format!( + "[{}]", + hook_json("case-created", true, PROPOSING_RHAI_HANDLER) + ); + let mut project_json: Value = serde_json::from_str(&hook_project_json( + &hooks, + "[]", + r#""results":["followup"]"#, + "", + )) + .expect("hook proposal fixture is JSON"); + + for bounded in [false, true] { + let target = &mut project_json["accessProfiles"]["case-hook"]["permissions"]["actions"][0] + ["targets"][0]; + assert_eq!(target["rowBoundaries"], json!("unrestricted")); + if bounded { + target["rowBoundaries"] = + json!([{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]); + } + let project = parse_project_json( + &serde_json::to_vec(&project_json).expect("hook proposal fixture serializes"), + ) + .expect("hook proposal fixture parses"); + let registry = compile_project_with_assets( + &project, + &[], + &[ + rhai_asset("scripts/open-followup.rhai", ACTION_HANDLER_SCRIPT), + rhai_asset("hooks/propose.rhai", PROPOSAL_HOOK_SCRIPT), + ], + CompileProfile::Authoring, + ) + .expect("hook proposal fixture compiles"); + + let setup = setup(registry, &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, "boundary-control").await; + let delivery_id = single_delivery(&event).to_owned(); + drop(mutation_client); + + assert_eq!( + setup.service.deliver_once().await, + Ok(HookWorkOutcome::Delivered) + ); + let row = delivery_row(&setup, event.event_id, &delivery_id).await; + assert_eq!(row.state, "delivered"); + assert_eq!(row.attempt, 1); + assert_eq!( + row.message_digest.as_deref(), + Some(proposal_message_digest().as_slice()) + ); + if bounded { + assert_eq!(row.disposition.as_deref(), Some("refused")); + assert_eq!( + row.code.as_deref(), + Some("hook.proposal.boundaries-unsatisfiable") + ); + assert_eq!( + row.summary.as_deref(), + Some( + "The declared principal's grant carries row boundaries a hook holds no claims to satisfy." + ) + ); + assert_eq!(row.resulting_revision, None); + assert_eq!(record_count(&setup, "followup").await, 0); + } else { + assert_eq!(row.disposition.as_deref(), Some("applied")); + assert_eq!(row.code, None); + assert_eq!(row.resulting_revision, Some(1)); + assert_eq!(record_count(&setup, "followup").await, 1); + } + setup.teardown().await; + } + receiver.stop().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_a_proposal_without_a_declared_principal_is_dead_lettered_readable() { let receiver = HttpsReceiver::start().await; diff --git a/crates/registry-breg/tests/postgres_immediate_actions.rs b/crates/registry-breg/tests/postgres_immediate_actions.rs index 5f3e80af53..03ed2b3f35 100644 --- a/crates/registry-breg/tests/postgres_immediate_actions.rs +++ b/crates/registry-breg/tests/postgres_immediate_actions.rs @@ -3760,7 +3760,7 @@ const ACTION_PROJECT: &[u8] = br#"{ }, "household-seed-writer": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": { "records": [ { diff --git a/crates/registry-breg/tests/postgres_import_authority.rs b/crates/registry-breg/tests/postgres_import_authority.rs index 01c92288cf..8252b6010f 100644 --- a/crates/registry-breg/tests/postgres_import_authority.rs +++ b/crates/registry-breg/tests/postgres_import_authority.rs @@ -84,7 +84,7 @@ const FIXTURE: &str = r#"{ {"id":"label","type":"string","maximumLength":128,"required":true,"classification":"public"} ] }}, - "accessProfiles":{"loader": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"loader": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"widget","operations":["import"], "readableFields":["jurisdiction","label"],"writableFields":["jurisdiction","label"], @@ -98,7 +98,7 @@ const FIXTURE: &str = r#"{ "readableFields":["jurisdiction","label"],"writableFields":["jurisdiction","label"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"second-loader": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"second-loader": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"widget","operations":["import"], "readableFields":["jurisdiction","label"],"writableFields":["jurisdiction","label"], @@ -824,7 +824,7 @@ fn claims_for(principal: &str, jurisdiction: &str) -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_ingestion_contract.rs b/crates/registry-breg/tests/postgres_ingestion_contract.rs index fec00a774c..42c0fc68a8 100644 --- a/crates/registry-breg/tests/postgres_ingestion_contract.rs +++ b/crates/registry-breg/tests/postgres_ingestion_contract.rs @@ -520,7 +520,7 @@ fn claims_with( VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), claims, ) @@ -555,7 +555,7 @@ fn fixture_registry(batch_maximum_bytes: u32) -> Arc VerifiedRequestClaims VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_ingestion_runs.rs b/crates/registry-breg/tests/postgres_ingestion_runs.rs index ece016f939..cb188f06d0 100644 --- a/crates/registry-breg/tests/postgres_ingestion_runs.rs +++ b/crates/registry-breg/tests/postgres_ingestion_runs.rs @@ -3021,7 +3021,7 @@ fn timer_ingestion_registry_with_operations( .remove("service-editor") .expect("the future-activation example has a service-editor profile"); source["accessProfiles"]["operator"] = renamed; - source["accessProfiles"]["operator"]["requiredScopes"] = json!("unrestricted"); + source["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); source["accessProfiles"]["operator"]["requiredPurposes"] = json!(["case-management"]); source["accessProfiles"]["operator"]["permissions"]["records"][0]["operations"] = json!(operations); @@ -5327,7 +5327,7 @@ fn operator_claims(principal: &str, jurisdiction: &str) -> VerifiedRequestClaims VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), @@ -5373,7 +5373,7 @@ const FIXTURE_HEAD: &str = r#"{ }},"#; const FIXTURE_TAIL: &str = r#" - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management","case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","patch","batch"], @@ -5381,7 +5381,7 @@ const FIXTURE_TAIL: &str = r#" "writableFields":["jurisdiction","label","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","patch","batch"], @@ -5473,7 +5473,7 @@ fn patch_only_registry() -> Arc { {"id":"label","type":"string","maximumLength":128,"required":true,"classification":"public"} ] }}, - "accessProfiles":{"patcher": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"patcher": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{ "records":[ diff --git a/crates/registry-breg/tests/postgres_kernel.rs b/crates/registry-breg/tests/postgres_kernel.rs index fa28daf96f..48fe5db34b 100644 --- a/crates/registry-breg/tests/postgres_kernel.rs +++ b/crates/registry-breg/tests/postgres_kernel.rs @@ -790,7 +790,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "constraints":[{"type":"temporal-non-overlap","scopeFields":["authority"]}] }}, "accessProfiles":{"operator": {"default":true,"principalClaim":"principal", - "requiredScopes":"unrestricted","requiredPurposes":["registry-administration"], + "requiredScopes":["records:write"],"requiredPurposes":["registry-administration"], "permissions":{"records":[{"recordType":"entry","operations":["create","get","list","patch"], "readableFields":["authority","payload","valid-from","valid-to"], "writableFields":["authority","payload","valid-from","valid-to"], diff --git a/crates/registry-breg/tests/postgres_membership_access.rs b/crates/registry-breg/tests/postgres_membership_access.rs index 90dbadc100..d43b4bb1d6 100644 --- a/crates/registry-breg/tests/postgres_membership_access.rs +++ b/crates/registry-breg/tests/postgres_membership_access.rs @@ -7,6 +7,27 @@ mod membership_fixture; #[allow(dead_code)] mod postgres_harness; +#[cfg(feature = "tooling")] +use registry_breg as breg_fixture_crate; +#[cfg(feature = "tooling")] +#[path = "support/membership_targets.rs"] +mod membership_targets; +#[cfg(feature = "tooling")] +#[path = "support/membership_write_journeys.rs"] +mod membership_write_journeys; +#[cfg(feature = "tooling")] +#[path = "support/membership_write_project.rs"] +mod membership_write_project; +#[cfg(feature = "tooling")] +#[path = "support/postgres_membership_writes.rs"] +mod postgres_membership_writes; +#[cfg(feature = "tooling")] +use registry_breg as breg; +#[cfg(feature = "tooling")] +#[path = "support/action_evidence_provider.rs"] +#[allow(dead_code)] +mod action_evidence_provider; + use axum::body::{to_bytes, Body}; use axum::http::{Method, Request, StatusCode}; use registry_breg::api::{ @@ -494,8 +515,12 @@ async fn real_postgres_membership_successors_match_fresh_install_when_added_chan managed_schema_fingerprint, reconcile_compiled_runtime_acl_for_test, }; let mut base = membership_fixture::source("facility"); - base["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"] = - json!([]); + base["accessProfiles"]["member"]["permissions"]["records"][0]["rowBoundaries"] = + json!("unrestricted"); + base["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("membership"); let mut previous = membership_fixture::compile(&base).unwrap(); let upgraded = postgres_harness::TestDatabase::create(1).await; let (migration, task) = upgraded.connect_migration().await; @@ -504,17 +529,25 @@ async fn real_postgres_membership_successors_match_fresh_install_when_added_chan .unwrap(); let guarded = membership_fixture::source("facility"); let mut changed = guarded.clone(); - changed["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"][0] - ["principalField"] = json!("private-note"); + changed["recordTypes"]["membership"]["membership"]["principal"] = json!("private-note"); for (stage, source) in [("added", guarded), ("changed", changed), ("removed", base)] { let candidate = membership_fixture::compile(&source).unwrap(); let changes = compiled_registry_change_set(&previous, &candidate, "prior-membership-package"); let plan = change_set_to_applicable_migration_plan(&changes) .expect("membership access changes produce compiler-owned successor DDL"); - assert!( - !plan.statements.is_empty(), - "{stage} helper change needs successor DDL" + let index_id = "entity.membership.membership.key-index"; + assert_eq!( + plan.statements + .iter() + .any(|statement| statement.id == index_id), + stage != "removed" + ); + assert_eq!( + plan.statements + .iter() + .any(|statement| statement.id == format!("{index_id}.drop")), + stage != "added" ); for statement in &plan.statements { migration @@ -553,3 +586,62 @@ async fn real_postgres_membership_successors_match_fresh_install_when_added_chan task.abort(); upgraded.cleanup().await; } + +#[tokio::test] +async fn real_postgres_pre_index_membership_successor_matches_fresh_catalog() { + use registry_breg::package::{ + change_set_to_applicable_migration_plan, compiled_registry_change_set_from_baseline, + CompiledRegistryMigrationBaseline, + }; + use registry_breg::postgres::{ + managed_schema_fingerprint, reconcile_compiled_runtime_acl_for_test, + }; + let candidate = membership_fixture::compile(&membership_fixture::source("facility")).unwrap(); + let mut baseline = CompiledRegistryMigrationBaseline::from_compiled("prior", &candidate); + baseline.generated_ddl_sha256 = + Some("sha256:88ce9380a31f7201ccda598870579c46fba1352db5598b0eb667bbb23bf68042".to_owned()); + let changes = compiled_registry_change_set_from_baseline(&baseline, &candidate, "prior"); + assert!(changes.changes.is_empty()); + let plan = change_set_to_applicable_migration_plan(&changes).unwrap(); + let upgraded = postgres_harness::TestDatabase::create(1).await; + let (migration, task) = upgraded.connect_migration().await; + install_compiled_schema(&migration, &candidate, &upgraded.runtime_role) + .await + .unwrap(); + // Model the pre-index installation precisely: retained helpers and policy + // definitions are already present in the predecessor, only the index is absent. + migration + .batch_execute("DROP INDEX registry_data.breg_membership_key_b9ee6c3037") + .await + .unwrap(); + for statement in &plan.statements { + migration + .batch_execute(&statement.sql) + .await + .unwrap_or_else(|error| { + panic!("compiler successor statement {}: {error}", statement.id) + }); + } + reconcile_compiled_runtime_acl_for_test(&migration, &candidate, &upgraded.runtime_role) + .await + .unwrap(); + let catalog = ExpectedManagedCatalog::compiled(&candidate); + let upgraded_fingerprint = + managed_schema_fingerprint(&migration, &upgraded.runtime_role, &catalog) + .await + .unwrap(); + let fresh = postgres_harness::TestDatabase::create(1).await; + let (fresh_migration, fresh_task) = fresh.connect_migration().await; + install_compiled_schema(&fresh_migration, &candidate, &fresh.runtime_role) + .await + .unwrap(); + let fresh_fingerprint = + managed_schema_fingerprint(&fresh_migration, &fresh.runtime_role, &catalog) + .await + .unwrap(); + assert_eq!(upgraded_fingerprint, fresh_fingerprint); + fresh_task.abort(); + fresh.cleanup().await; + task.abort(); + upgraded.cleanup().await; +} diff --git a/crates/registry-breg/tests/postgres_migration.rs b/crates/registry-breg/tests/postgres_migration.rs index 81691101f7..3ff7f0765a 100644 --- a/crates/registry-breg/tests/postgres_migration.rs +++ b/crates/registry-breg/tests/postgres_migration.rs @@ -5731,7 +5731,7 @@ fn module_bytes(variant: Variant) -> Vec { _ => "", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}},{{"id":"rank","type":"int64","classification":"internal"{rank_required}}}{legacy}{batch}{secret}{alias}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}},{{"id":"rank","type":"int64","classification":"internal"{rank_required}}}{legacy}{batch}{secret}{alias}],"accessProfiles":{{"reader":{{"requiredScopes":["records:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/postgres_mutation.rs b/crates/registry-breg/tests/postgres_mutation.rs index 4e33efb16f..1c860ce21e 100644 --- a/crates/registry-breg/tests/postgres_mutation.rs +++ b/crates/registry-breg/tests/postgres_mutation.rs @@ -1813,7 +1813,7 @@ async fn real_postgres_row_local_constraint_problems_name_only_readable_declarat {"id":"valid-to","type":"date","validTimeRole":"valid-to","classification":"public"} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"window","operations":["create","get","patch","batch"], "readableFields":["jurisdiction","label","valid-from","valid-to","score","status"], @@ -1825,7 +1825,7 @@ async fn real_postgres_row_local_constraint_problems_name_only_readable_declarat "writableFields":["jurisdiction","scope","valid-from","valid-to"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"write-only-end": {"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + },"write-only-end": {"principalClaim":"registry_principal","requiredScopes":["records:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"window","operations":["create"], "readableFields":["jurisdiction","label","valid-from","score","status"], @@ -2230,7 +2230,10 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { BREG_SEC_13_PRINCIPAL_CANARY, "case-management", Some(BREG_SEC_13_ZONE_CANARY), - BTreeSet::from(["breg-sec-13-scope-canary".to_owned()]), + BTreeSet::from([ + "records:write".to_owned(), + "breg-sec-13-scope-canary".to_owned(), + ]), ); let operator_openapi = body_json( @@ -3888,7 +3891,7 @@ fn row_boundary_batch_registry() -> registry_breg::CompiledRegistry { {"id":"quantity","type":"int64","required":true,"classification":"public"} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","batch"], @@ -3920,7 +3923,7 @@ fn located_refusal_registry() -> registry_breg::CompiledRegistry { {"id":"secret","type":"string","maximumLength":128,"required":false,"classification":"public"} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","batch"], @@ -3930,7 +3933,7 @@ fn located_refusal_registry() -> registry_breg::CompiledRegistry { "sortableFields":["label"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"keeper": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"keeper": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["get","list","patch"], @@ -3940,7 +3943,7 @@ fn located_refusal_registry() -> registry_breg::CompiledRegistry { "sortableFields":["secret"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"drafter": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"drafter": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-drafting"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get"], @@ -4726,7 +4729,12 @@ fn header_string(headers: &axum::http::HeaderMap, name: &str) -> String { } fn api_claims(purpose: &str, zone: Option<&str>) -> VerifiedRequestClaims { - api_claims_with_principal_and_scopes(PRINCIPAL_CANARY, purpose, zone, BTreeSet::new()) + api_claims_with_principal_and_scopes( + PRINCIPAL_CANARY, + purpose, + zone, + BTreeSet::from(["records:write".to_owned()]), + ) } fn api_claims_with_principal_and_scopes( @@ -4782,7 +4790,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { {"id":"name","type":"string","maximumLength":128,"required":true,"classification":"public"} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management","case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","tombstone"], @@ -4790,7 +4798,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "writableFields":["jurisdiction","label","note","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"review-operator": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"review-operator": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","tombstone"], @@ -4804,7 +4812,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "readableFields":["label"], "rowBoundaries": "unrestricted" }]} - },"label-editor": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"label-editor": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["get","patch"], @@ -4812,7 +4820,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "writableFields":["label"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"case-operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"case-operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"log","operations":["create","get","list"], @@ -6167,7 +6175,7 @@ fn linked_registry() -> registry_breg::CompiledRegistry { "externalViews":{"local-with-subject": {"recordType":"local-record", "links":[{"id":"subject","projection":"approved-subjects","fromField":"subjectkey"}] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["local-consultation"], "permissions":{"records":[{ "recordType":"local-record","operations":["create","get","list","patch"], diff --git a/crates/registry-breg/tests/postgres_mutation_logical_names.rs b/crates/registry-breg/tests/postgres_mutation_logical_names.rs index 1b38090d4b..8f6f4385fc 100644 --- a/crates/registry-breg/tests/postgres_mutation_logical_names.rs +++ b/crates/registry-breg/tests/postgres_mutation_logical_names.rs @@ -15,7 +15,7 @@ use serde_json::{json, Value}; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_mutations_use_only_governed_api_field_names() { let harness = PilotHarness::start("asset-site-placement").await; - let token = harness.token("asset-management", &[]); + let token = harness.token_with_scopes("asset-management", &[], &["asset:manage"]); let created = harness .send_json( diff --git a/crates/registry-breg/tests/postgres_package.rs b/crates/registry-breg/tests/postgres_package.rs index 53b2568b9c..58da107315 100644 --- a/crates/registry-breg/tests/postgres_package.rs +++ b/crates/registry-breg/tests/postgres_package.rs @@ -3657,7 +3657,7 @@ fn module_bytes(plan: PlanChoice) -> Vec { plan, PlanChoice::SecondTable | PlanChoice::ThirdTable | PlanChoice::HookSecondTable ) { - r#","second-record":{"primaryDataset":"neutral-registry","route":"second-records","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"writer": {"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#","second-record":{"primaryDataset":"neutral-registry","route":"second-records","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"writer": {"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":["records:write"],"rowBoundaries":"unrestricted"}}}"# } else { "" }; diff --git a/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs b/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs index bd801d666a..89f8347746 100644 --- a/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs +++ b/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs @@ -601,7 +601,7 @@ fn indexed_module_bytes(other: OtherEntity) -> Vec { OtherEntity::Unchanged | OtherEntity::GainsAField => "second-records", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"neutral-record":{{"primaryDataset":"neutral-registry","route":"neutral-records","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}],"indexes":[{{"id":"code-idx","fields":["code"]}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list"],"readableFields":["code"]}}}}}},"second-record":{{"primaryDataset":"neutral-registry","route":"{route}","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}{added}],"accessProfiles":{{"writer":{{"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"],"requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"neutral-record":{{"primaryDataset":"neutral-registry","route":"neutral-records","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}],"indexes":[{{"id":"code-idx","fields":["code"]}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list"],"readableFields":["code"]}}}}}},"second-record":{{"primaryDataset":"neutral-registry","route":"{route}","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}{added}],"accessProfiles":{{"writer":{{"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"],"requiredScopes":["records:write"],"rowBoundaries":"unrestricted"}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/postgres_package/policy_upgrade.rs b/crates/registry-breg/tests/postgres_package/policy_upgrade.rs index 9bcb6df60b..c5578ccf48 100644 --- a/crates/registry-breg/tests/postgres_package/policy_upgrade.rs +++ b/crates/registry-breg/tests/postgres_package/policy_upgrade.rs @@ -19,7 +19,7 @@ async fn ordinary_profile_removal_applies_and_matches_fresh_catalog() { async fn ordinary_profile_operation_narrowing_applies_and_matches_fresh_catalog() { assert_profile_successor( Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["create"], "writableFields": ["code", "note"] })), ProfileSuccessor::Compiler, @@ -31,7 +31,7 @@ async fn ordinary_profile_operation_narrowing_applies_and_matches_fresh_catalog( async fn ordinary_profile_create_revocation_applies_and_matches_fresh_catalog() { assert_profile_successor( Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["get", "list"], "readableFields": ["code", "note"] })), ProfileSuccessor::Compiler, @@ -43,7 +43,7 @@ async fn ordinary_profile_create_revocation_applies_and_matches_fresh_catalog() async fn ordinary_profile_field_narrowing_applies_and_matches_fresh_catalog() { assert_profile_successor( Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["create", "get", "list"], "writableFields": ["code", "note"], "readableFields": ["code"] })), @@ -294,7 +294,7 @@ fn proposal_policy_sources(add_submitter: bool, add_optional_field: bool) -> (Ve json!({"casework-main": {"protocol": "id.registrystack.org/protocols/review/v1"}}); let profile = |id: &str, default: bool| { json!({ - id: {"default": default, "principalClaim": "principal", "requiredScopes": "unrestricted", + id: {"default": default, "principalClaim": "principal", "requiredScopes": ["proposals:write"], "permissions": { "records": [{"recordType": "asset", "operations": ["get", "list"], "readableFields": ["label"], "rowBoundaries": "unrestricted"}], @@ -391,7 +391,7 @@ pub(super) async fn fresh_fingerprint(registry: ®istry_breg::model::CompiledR async fn assert_profile_successor(auditor: Option, kind: ProfileSuccessor) { let baseline_bytes = profile_module(Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["create", "get", "list"], "writableFields": ["code", "note"], "readableFields": ["code", "note"] }))); diff --git a/crates/registry-breg/tests/postgres_package/reference_upgrade.rs b/crates/registry-breg/tests/postgres_package/reference_upgrade.rs index 53b1b09f3e..702d2f6bcd 100644 --- a/crates/registry-breg/tests/postgres_package/reference_upgrade.rs +++ b/crates/registry-breg/tests/postgres_package/reference_upgrade.rs @@ -970,7 +970,7 @@ fn reference_module_bytes(target: Option<&str>) -> Vec { ) }); format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"site":{{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":"unrestricted","rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"location":{{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":"unrestricted","rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}{reference_field}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":"unrestricted","rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"site":{{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":["records:write"],"rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"location":{{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":["records:write"],"rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}{reference_field}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":["records:write"],"rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/postgres_pilot_acceptance.rs b/crates/registry-breg/tests/postgres_pilot_acceptance.rs index 2fd37ea10a..c39a19ec01 100644 --- a/crates/registry-breg/tests/postgres_pilot_acceptance.rs +++ b/crates/registry-breg/tests/postgres_pilot_acceptance.rs @@ -38,9 +38,9 @@ async fn real_postgres_five_domain_pilot_is_configured_production_closed_and_sou } async fn asset_site_placement_journey(harness: &PilotHarness) { - let token = harness.token("asset-management", &[]); + let token = harness.token_with_scopes("asset-management", &[], &["asset:manage"]); assert_fixture_surface(harness, "asset-operator", &token, "asset").await; - let planner_token = harness.token("site-planning", &[]); + let planner_token = harness.token_with_scopes("site-planning", &[], &["asset:plan"]); let planner_openapi = assert_fixture_surface(harness, "site-planner", &planner_token, "asset").await; assert!(planner_openapi["paths"] @@ -414,7 +414,7 @@ async fn establishments_journey(harness: &PilotHarness) { } async fn inspection_journey(harness: &PilotHarness) { - let token = harness.token("facility-inspection", &[]); + let token = harness.token_with_scopes("facility-inspection", &[], &["inspection:manage"]); let openapi = assert_fixture_surface(harness, "inspection-inspector", &token, "inspection").await; assert_eq!( @@ -592,13 +592,15 @@ async fn inspection_journey(harness: &PilotHarness) { } async fn facility_journey(harness: &PilotHarness) { - let north_token = harness.token( + let north_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["north-district"]))], + &["registry:facility:operate"], ); - let south_token = harness.token( + let south_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["south-district"]))], + &["registry:facility:operate"], ); let openapi = assert_fixture_surface(harness, "facility-operator", &north_token, "facility").await; @@ -851,7 +853,7 @@ async fn facility_journey(harness: &PilotHarness) { } async fn business_journey(harness: &PilotHarness) { - let token = harness.token("business-registry", &[]); + let token = harness.token_with_scopes("business-registry", &[], &["business:register"]); assert_fixture_surface(harness, "business-registrar", &token, "business").await; let legal_entity = create_record( harness, diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index 0bd6e257c4..6594cc4998 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -4,6 +4,10 @@ #[path = "support/client_http.rs"] #[allow(dead_code)] mod client_http; +#[path = "support/membership_fixture.rs"] +mod membership_fixture; +#[path = "support/membership_write_project.rs"] +mod membership_write_project; #[path = "support/postgres_harness.rs"] #[allow(dead_code)] mod postgres_harness; @@ -2585,6 +2589,223 @@ async fn proposal_list_audit_counts_only_each_actions_returned_items() { fixture.finish().await; } +#[tokio::test] +async fn proposal_list_correlates_membership_filtered_page_with_its_journal() { + let registry = membership_fixture::compile(&membership_write_project::proposal_project()) + .unwrap_or_else(|_| panic!("the maintained membership Proposal fixture must compile")); + let human = |principal, scopes| { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + principal, + scopes, + None, + BTreeMap::from([( + "sub".into(), + VerifiedClaimValue::direct_string(principal).unwrap(), + )]), + registry_platform_oidc::ActorKind::Human, + ) + .expect("fixture claims are valid") + }; + let fixture = + client_http::ClientFixture::start(registry, human("member", BTreeSet::new())).await; + let steward = fixture + .client_for(human( + "steward", + BTreeSet::from(["records:manage".into(), "membership:use".into()]), + )) + .await; + let member = &fixture.http.client; + let metadata = member + .registry_contract(Some("member")) + .await + .unwrap_or_else(|_| panic!("member metadata must be available")); + let action = metadata + .value + .select_action("propose-facility", "member") + .expect("member can start a facility Proposal"); + + let http = reqwest::Client::new(); + let create = async |route: &str, body: Value, idempotency_key: String| { + let response = http + .post(format!( + "{}/v1/records/{route}?accessProfile=steward", + steward.base_url + )) + .header("idempotency-key", idempotency_key) + .json(&body) + .send() + .await + .unwrap_or_else(|_| panic!("steward create request failed")); + assert!(response.status() == reqwest::StatusCode::CREATED); + let etag = response.headers().get("etag").cloned(); + let body: Value = response + .json() + .await + .unwrap_or_else(|_| panic!("steward create response must be JSON")); + let id = body["data"]["recordIdentifier"] + .as_str() + .expect("steward create returns a Record identifier") + .to_owned(); + (id, etag) + }; + let mut submitted = Vec::new(); + for index in 0..3 { + let (organization, _) = create( + "organizations", + json!({"data":{"name":format!("List organization {index}"),"owner":"member"}}), + format!("list-organization-{index}"), + ) + .await; + let (membership, etag) = create( + "memberships", + json!({"data":{"organization":organization,"principal":"member","active":true}}), + format!("list-membership-{index}"), + ) + .await; + let input = BRegActionInvocationRequest::new( + &action, + map(json!({"organization":organization,"label":format!("List facility {index}")})), + None, + ) + .unwrap_or_else(|_| panic!("fixture inputs must match the Action")); + let draft = member + .start_proposal(&action, &input, &key(&format!("list-start-{index}"))) + .await + .unwrap_or_else(|_| panic!("member must be able to start with active membership")) + .value; + let submit = member + .prepare_proposal( + &draft, + "submit", + json!({}), + &key(&format!("list-submit-{index}")), + ) + .unwrap_or_else(|_| panic!("member must be able to prepare submission")); + let proposal = member + .execute_proposal(&submit) + .await + .unwrap_or_else(|_| panic!("member must be able to submit with active membership")) + .value; + submitted.push((proposal.id().to_owned(), membership, etag)); + } + // The omitted candidate must sort between the returned item and the visible + // lookahead, so one bounded request necessarily scans all three candidates. + submitted.sort_by(|left, right| left.0.cmp(&right.0)); + let (first, _, _) = &submitted[0]; + let (_, membership, etag) = &submitted[1]; + let response = http + .patch(format!( + "{}/v1/records/memberships/{membership}?accessProfile=steward", + steward.base_url + )) + .header("content-type", "application/json-patch+json") + .header( + "if-match", + etag.clone().expect("membership create returns an ETag"), + ) + .header("idempotency-key", "list-withdraw-membership") + .json(&json!([{"op":"replace","path":"/data/active","value":false}])) + .send() + .await + .unwrap_or_else(|_| panic!("steward membership update request failed")); + assert!(response.status() == reqwest::StatusCode::OK); + + let before = fixture.audit_capture.entries().len(); + let response = http + .get(format!( + "{}/v1/proposals?accessProfile=member&limit=1", + fixture.http.base_url + )) + .send() + .await + .unwrap_or_else(|_| panic!("member list request failed")); + assert!(response.status() == reqwest::StatusCode::OK); + let trace_id = response + .headers() + .get("traceparent") + .and_then(|header| header.to_str().ok()) + .and_then(|header| header.split('-').nth(1)) + .expect("successful list returns a trace ID") + .to_owned(); + let page: Value = response + .json() + .await + .unwrap_or_else(|_| panic!("successful list response must be JSON")); + let items = page["items"].as_array().expect("list has an items array"); + assert_eq!(items.len(), 1); + assert!(items[0]["id"].as_str() == Some(first.as_str())); + let cursor = page["nextCursor"].as_str().expect("list has a next cursor"); + assert_eq!(cursor, first.as_str()); + + let entries = fixture.audit_capture.entries(); + let list_entries = &entries[before..]; + assert_eq!( + list_entries.len(), + 4, + "two attempts and two terminal records" + ); + let request_id = list_entries[0]["correlation"] + .as_str() + .expect("list attempt has a request correlation"); + assert!(uuid::Uuid::parse_str(request_id).is_ok()); + for entry in list_entries { + let record = &entry["record"]; + assert!(entry["correlation"].as_str() == Some(request_id)); + assert!(record["requestId"].as_str() == Some(request_id)); + assert!(record["traceId"].as_str() == Some(trace_id.as_str())); + } + for (action, count, outcome) in [ + ("propose-facility", 1, "returned"), + ("propose-move", 0, "empty"), + ] { + let operation = format!("proposals.{action}.list"); + for (phase, envelope_phase) in [("attempt", "request"), ("terminal", "response")] { + let matching = list_entries + .iter() + .filter(|entry| { + let record = &entry["record"]; + entry["phase"] == envelope_phase + && record["phase"] == phase + && record["method"] == "GET" + && record["operationId"].as_str() == Some(operation.as_str()) + && record["actionId"] == action + && (phase == "attempt" + || (record["resultCount"].as_u64() == Some(count) + && record["outcome"] == outcome)) + }) + .count(); + assert_eq!(matching, 1, "one {phase} journal record for {action}"); + } + } + + let response = http + .get(format!( + "{}/v1/proposals?accessProfile=member&limit=1&cursor={cursor}", + fixture.http.base_url + )) + .send() + .await + .unwrap_or_else(|_| panic!("member continuation request failed")); + assert_eq!(response.status(), reqwest::StatusCode::OK); + let page: Value = response + .json() + .await + .unwrap_or_else(|_| panic!("successful continuation response must be JSON")); + let items = page["items"] + .as_array() + .expect("continuation has an items array"); + assert_eq!(items.len(), 1); + assert_eq!(items[0]["id"].as_str(), Some(submitted[2].0.as_str())); + assert!( + page.get("nextCursor").is_none(), + "the visible list is exhausted" + ); + + drop(steward); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn manual_no_review_attachments_cas_concealment_and_exact_receipt() { let fixture = client_http::ClientFixture::start( diff --git a/crates/registry-breg/tests/postgres_proposal_security.rs b/crates/registry-breg/tests/postgres_proposal_security.rs index 8446fbf8aa..ea21c9a8d1 100644 --- a/crates/registry-breg/tests/postgres_proposal_security.rs +++ b/crates/registry-breg/tests/postgres_proposal_security.rs @@ -37,10 +37,12 @@ fn source(membership: bool) -> Value { let mut reader = json!({"recordType":"target","operations":["get","list"],"readableFields":["name"], "rowBoundaries":[{"field":"jurisdiction","claim":"recordJurisdiction","operator":"equals"}]}); if membership { - reader["membershipBoundaries"] = json!([{"field":"organization","membershipRecordType":"membership", - "membershipKeyField":"organization","principalField":"principal","activeField":"active"}]); + reader["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); } - let source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", + let mut source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", "project":{"id":"proposal-security","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://proposal.example.test"}, "datasets":{"directory": {}},"recordTypes":{ "organization": {"primaryDataset":"directory","route":"organizations","mutationMode":"mutable", @@ -76,6 +78,10 @@ fn source(membership: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":targets}], "proposals":[{"action":"correct-name","operations":["get","edit","submit","get-review-context"], "ownership":"caller","readableInputs":["target","value"],"readableContextFields":["currentName","proposedName"],"targets":targets}]}}}}); + if membership { + source["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + } source } @@ -106,6 +112,21 @@ fn clerk() -> VerifiedRequestClaims { .unwrap() } +fn human_clerk() -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "registry_principal", + "author", + BTreeSet::from(["proposal:manage".into()]), + Some("registry-administration".into()), + BTreeMap::from([( + "jurisdiction".into(), + VerifiedClaimValue::direct_string("zone-a").unwrap(), + )]), + registry_platform_oidc::ActorKind::Human, + ) + .unwrap() +} + struct Status { active: AtomicBool, calls: AtomicUsize, @@ -221,6 +242,25 @@ async fn seed(fixture: &client_http::ClientFixture) -> (String, String) { (organization, target) } +async fn set_membership_active(http: &client_http::ClientHttp, membership: &str, active: bool) { + let path = format!("/v1/records/memberships/{membership}?accessProfile=clerk"); + let (code, _, etag) = send(http, Method::GET, &path, Value::Null, None, None).await; + assert_eq!(code, StatusCode::OK); + let response = reqwest::Client::new() + .patch(format!("{}{path}", http.base_url)) + .header("content-type", "application/json-patch+json") + .header("if-match", etag.unwrap()) + .header( + "idempotency-key", + format!("membership-{membership}-{active}"), + ) + .json(&json!([{"op":"replace","path":"/data/active","value":active}])) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn signed_proposal_start_and_lifecycle_receipts_reject_sibling_grants() { let status = Arc::new(Status { @@ -1887,9 +1927,9 @@ async fn applicant_progress_rechecks_withdrawal_and_audit_before_release() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn review_status_service_reads_only_its_exact_frozen_review_binding() { - let mut source = source(false); - let proposal_targets = - source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["targets"].clone(); + let mut source = source(true); + source["actions"]["correct-name"]["execution"]["proposal"]["reviewContext"]["fields"] + ["changes"] = json!({"type":"changes","recordType":"target","fields":["name"]}); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = json!([ "get", "edit", @@ -1899,7 +1939,7 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { "get-review-context" ]); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableContextFields"] = - json!(["currentName", "proposedName"]); + json!(["changes", "currentName", "proposedName"]); source["reviewAuthorities"] = json!({"casework": {"protocol":"id.registrystack.org/protocols/review/v1"}}); source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({"type":"required","authority":"casework","source":"proposal-security", @@ -1910,15 +1950,18 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { "reviewAuthority":"casework","operations":["get-review-status"]}]}})); source["accessProfiles"].as_object_mut().unwrap().insert("task-context".to_owned(), json!({"principalClaim":"registry_principal", "actorKind":"service","requesterClients":["agent-client"],"requiredScopes":["proposal:task-context"], - "requiredPurposes":["registry-administration"],"permissions":{"proposals":[{"action":"correct-name", + "requiredPurposes":["registry-administration"],"permissions":{"records":[{ + "recordType":"target","operations":["get"],"readableFields":["name"],"rowBoundaries":"unrestricted" + }],"proposals":[{"action":"correct-name", "operations":["get","get-task-grant-context"],"ownership":"caller", - "readableContextFields":["proposedName"],"targets":proposal_targets}]}})); + "readableContextFields":["changes","currentName","proposedName"], + "targets":[{"recordType":"target","rowBoundaries":[{"field":"organization","membership":"membership"}]}]}]}})); let fixture = client_http::ClientFixture::start_with_mutations(compile(source), clerk(), |service| { service.with_review_result_source(review_binding()) }) .await; - let (_, target) = seed(&fixture).await; + let (organization, target) = seed(&fixture).await; let (code, draft, etag) = send( &fixture.http, Method::POST, @@ -2098,11 +2141,11 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET authority='casework',create_request=$1,expected_policy=$2,expected_submission_digest=$3", &[&stored,&policy,&digest]).await.unwrap(); } - let create: registry_review_client::ReviewCreateRequest = + let create_request: registry_review_client::ReviewCreateRequest = serde_json::from_value(stored).unwrap(); let accepted = registry_review_client::ReviewRequestAccepted { request_id: uuid::Uuid::new_v4(), - subject: create.subject, + subject: create_request.subject, policy: serde_json::from_value(policy).unwrap(), submission_digest: registry_review_client::SubmissionDigest::parse(&digest).unwrap(), }; @@ -2128,6 +2171,13 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { let task_binding = metadata .select_proposal_task_grant_context("task-context", "correct-name") .unwrap(); + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"review-service","active":true}), + "task-context-membership", + ) + .await; let typed_task_request: registry_breg_client::BRegProposalTaskContextRequest = serde_json::from_value(task_request.clone()).unwrap(); let task_document = task_service @@ -2141,6 +2191,63 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { task_document.proposal.context.fields.unwrap(), BTreeMap::from([("proposedName".into(), json!("Proposed"))]) ); + let record_path = format!("/v1/records/targets/{target}?accessProfile=task-context"); + let context_fields = [ + ("currentName", json!("current-name-canary")), + ( + "changes", + json!([{"recordId":target,"operation":"patch", + "before":{"name":"current-name-canary"},"after":{"name":"Proposed"}}]), + ), + ]; + for (field, expected_value) in &context_fields { + let mut selected = task_request.clone(); + selected["fields"] = json!([field]); + let selected = serde_json::from_value(selected).unwrap(); + let document = task_service + .client + .read_proposal_task_grant_context(&task_binding, &selected) + .await + .unwrap() + .value; + assert_eq!(document.request, selected); + assert_eq!( + document.proposal.context.fields.unwrap(), + BTreeMap::from([(field.to_string(), expected_value.clone())]) + ); + } + set_membership_active(&fixture.http, &membership, false).await; + assert_eq!( + send( + &task_service, + Method::GET, + &record_path, + Value::Null, + None, + None + ) + .await + .0, + StatusCode::OK, + "the ordinary Record grant is independent of the Proposal target scope" + ); + for (field, _) in context_fields { + let mut selected = task_request.clone(); + selected["fields"] = json!([field]); + let (code, problem, _) = send( + &task_service, + Method::POST, + &task_path, + selected, + None, + None, + ) + .await; + assert_eq!(code, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + assert!(problem.get("proposal").is_none()); + } + set_membership_active(&fixture.http, &membership, true).await; let mut substituted_request = task_request.clone(); substituted_request["requestId"] = json!(uuid::Uuid::new_v4()); let (code, value, _) = send( @@ -2647,6 +2754,734 @@ async fn frozen_changes_inspection_covers_patch_and_create_without_applying_or_r fixture.finish().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn review_context_checks_each_frozen_membership_and_saved_document() { + let mut project = source(true); + let profiles = project["accessProfiles"].as_object_mut().unwrap(); + profiles.remove("task-reviewer"); + let clerk_permissions = &mut profiles.get_mut("clerk").unwrap()["permissions"]; + clerk_permissions["actions"][0]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"recordType":"organization","rowBoundaries":"unrestricted"})); + clerk_permissions["proposals"][0]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"recordType":"organization","rowBoundaries":"unrestricted"})); + clerk_permissions["proposals"][0]["operations"] + .as_array_mut() + .unwrap() + .push(json!("apply")); + clerk_permissions["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("destination")); + clerk_permissions["proposals"][0]["writableAttachments"] = json!(["support"]); + profiles.insert("member-review".into(), json!({ + "principalClaim":"registry_principal","actorKind":"human", + "requiredScopes":["proposal:manage"],"requiredPurposes":["registry-administration"], + "permissions":{ + "records":[{"recordType":"target","operations":["get"], + "readableFields":["name"],"rowBoundaries":"unrestricted"}], + "proposals":[{"action":"correct-name","operations":["get-review-context"], + "readableContextFields":["changes","currentName","document"],"targets":[ + {"recordType":"target","rowBoundaries":[{"field":"organization","membership":"membership"}]}, + {"recordType":"organization","rowBoundaries":"unrestricted"} + ]}] + } + })); + let action = &mut project["actions"]["correct-name"]; + action["inputs"].as_array_mut().unwrap().push(json!({ + "id":"destination","type":"reference","target":"organization","required":true, + "classification":"internal" + })); + action["plan"]["effects"][0]["set"]["organization"] = json!({"fromInput":"destination"}); + let proposal = &mut action["execution"]["proposal"]; + proposal["attachments"] = json!([ + {"id":"support","required":false,"maximumBytes":64,"contentTypes":["text/plain"],"classification":"restricted"} + ]); + proposal["reviewContext"]["fields"] = json!({ + "changes":{"type":"changes","recordType":"target","fields":["name"]}, + "currentName":{"type":"record","input":"target","field":"name"}, + "document":{"type":"document","slot":"support"} + }); + let fixture = client_http::ClientFixture::start(compile(project), human_clerk()).await; + let (origin, target) = seed(&fixture).await; + let destination = create( + &fixture.http, + "organizations", + json!({"name":"Destination"}), + "destination", + ) + .await; + let original_membership = create( + &fixture.http, + "memberships", + json!({"organization":origin,"principal":"author","active":true}), + "original-membership", + ) + .await; + let destination_membership = create( + &fixture.http, + "memberships", + json!({"organization":destination,"principal":"author","active":true}), + "destination-membership", + ) + .await; + let (status, draft, etag) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":{"target":target,"value":"Proposed","destination":destination}}), + Some("start-move"), + None, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let id = draft["id"].as_str().unwrap(); + let support = format!("/v1/proposals/{id}/attachments/support?accessProfile=clerk"); + let response = reqwest::Client::new() + .patch(format!("{}{support}", fixture.http.base_url)) + .header("content-type", "text/plain") + .header("if-match", etag.unwrap()) + .header("idempotency-key", "move-document") + .body("Synthetic review document") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let (status, submitted, etag) = send( + &fixture.http, + Method::POST, + &format!("/v1/proposals/{id}/submit?accessProfile=clerk"), + json!({}), + Some("submit-move"), + response.headers()["etag"].to_str().ok(), + ) + .await; + assert_eq!(status, StatusCode::OK); + + let scalar = format!("/v1/proposals/{id}/review-context?accessProfile=member-review"); + let batch = format!("/v1/proposals/review-context?accessProfile=member-review&ids={id}"); + let (status, context, _) = + send(&fixture.http, Method::GET, &scalar, Value::Null, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(context["effectDigest"], submitted["effectDigest"]); + assert_eq!( + context["context"]["fields"]["currentName"], + "current-name-canary" + ); + assert_eq!( + context["context"]["fields"]["changes"], + json!([{ + "recordId":target,"operation":"patch","before":{"name":"current-name-canary"},"after":{"name":"Proposed"} + }]) + ); + let (status, page, _) = send(&fixture.http, Method::GET, &batch, Value::Null, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + page, + json!({"items":[{"id":id,"status":"visible","context":context}]}) + ); + let saved = context["context"]["fields"]["document"]["download"]["path"] + .as_str() + .unwrap(); + let download = format!( + "{}{saved}&accessProfile=member-review", + fixture.http.base_url + ); + let http = reqwest::Client::new(); + let response = http.get(&download).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert!(response.bytes().await.unwrap().as_ref() == b"Synthetic review document"); + + for (membership, apply_after) in [ + (&destination_membership, true), + (&original_membership, false), + ] { + set_membership_active(&fixture.http, membership, false).await; + let (status, problem, _) = + send(&fixture.http, Method::GET, &scalar, Value::Null, None, None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + assert!(problem.get("context").is_none()); + let (status, page, _) = + send(&fixture.http, Method::GET, &batch, Value::Null, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(page, json!({"items":[{"id":id,"status":"concealed"}]})); + let response = http.get(&download).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.json::().await.unwrap()["code"], + "resource.not-found" + ); + if apply_after { + set_membership_active(&fixture.http, membership, true).await; + let (status, value, _) = send( + &fixture.http, Method::POST, &format!("/v1/proposals/{id}/apply?accessProfile=clerk"), + json!({"submissionVersion":submitted["submissionVersion"],"effectDigest":submitted["effectDigest"]}), + Some("apply-move"), etag.as_deref() + ).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(value["state"], "applied"); + assert_eq!( + send(&fixture.http, Method::GET, &scalar, Value::Null, None, None) + .await + .0, + StatusCode::OK + ); + } + } + fixture.finish().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn attachment_membership_accounting_requires_accepted_refusal_audit() { + use axum::{ + body::{to_bytes, Body}, + http::Request, + }; + use registry_breg::metrics::{metrics_app, Metrics}; + use registry_platform_config::Posture; + use tower::ServiceExt as _; + + // Isolate the process-wide counter from other tests in this target. + const CHILD: &str = "BREG_TEST_ATTACHMENT_MEMBERSHIP_ACCOUNTING_CHILD"; + const TEST: &str = "attachment_membership_accounting_requires_accepted_refusal_audit"; + if std::env::var_os(CHILD).is_none() { + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + result.status.success() + && String::from_utf8_lossy(&result.stdout).contains("1 passed; 0 failed"), + "isolated attachment accounting check failed" + ); + return; + } + + async fn membership_refusals() -> u64 { + let response = metrics_app( + Arc::new(Metrics::without_pool_for_test()), + Posture::Production, + ) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let body = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .unwrap(); + std::str::from_utf8(&body) + .unwrap() + .lines() + .find_map(|line| { + line.strip_prefix("breg_request_refusals_total{check=\"membership\"} ") + }) + .expect("membership refusal counter is present") + .parse() + .expect("membership refusal counter is numeric") + } + + let mut project = source(true); + project["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("task-reviewer"); + // A submitted Create checks membership against the frozen after-image. + // Loading an existing target can return a generic 412 before that probe. + let action = &mut project["actions"]["correct-name"]; + action.as_object_mut().unwrap().remove("commitGuards"); + action["inputs"][0] = json!({"id":"organization","type":"reference","target":"organization", + "required":true,"classification":"internal"}); + action["plan"]["effects"] = json!([{ + "id":"record","target":{"recordType":"target"},"operation":"create", + "set":{"name":{"fromInput":"value"},"jurisdiction":{"value":"zone-a"}, + "organization":{"fromInput":"organization"}} + }]); + let proposal = &mut action["execution"]["proposal"]; + proposal["reviewContext"]["fields"] = json!({"proposedName":{"type":"input","input":"value"}}); + proposal["attachments"] = json!([ + {"id":"support","required":false,"maximumBytes":64, + "contentTypes":["text/plain"],"classification":"restricted"} + ]); + let permissions = &mut project["accessProfiles"]["clerk"]["permissions"]; + let mut targets = permissions["actions"][0]["targets"].clone(); + targets[0]["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); + targets + .as_array_mut() + .unwrap() + .push(json!({"recordType":"organization","rowBoundaries":"unrestricted"})); + permissions["actions"][0]["targets"] = targets.clone(); + let grant = &mut permissions["proposals"][0]; + grant["readableInputs"] = json!(["organization", "value"]); + grant["writableAttachments"] = json!(["support"]); + grant["targets"] = targets; + + for method in [Method::PATCH, Method::DELETE] { + let fixture = client_http::ClientFixture::start(compile(project.clone()), clerk()).await; + let organization = create( + &fixture.http, + "organizations", + json!({"name":"Unit"}), + "organization", + ) + .await; + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"author","active":true}), + "attachment-accounting-membership", + ) + .await; + let (status, draft, etag) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":{"organization":organization,"value":"Proposed"}}), + Some("attachment-accounting-start"), + None, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let id = draft["id"].as_str().unwrap(); + let (status, _, etag) = send( + &fixture.http, + Method::POST, + &format!("/v1/proposals/{id}/submit?accessProfile=clerk"), + json!({}), + Some("attachment-accounting-submit"), + etag.as_deref(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let etag = etag.unwrap(); + set_membership_active(&fixture.http, &membership, false).await; + let url = format!( + "{}/v1/proposals/{id}/attachments/support?accessProfile=clerk", + fixture.http.base_url + ); + let http = reqwest::Client::new(); + for (reject_audit, expected_status, expected_code, expected_delta) in [ + ( + false, + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + 1, + ), + ( + true, + StatusCode::SERVICE_UNAVAILABLE, + "source.unavailable", + 0, + ), + ] { + let before_count = membership_refusals().await; + let before_entries = fixture.audit_capture.entries().len(); + let before_rejections = fixture.audit_capture.matched_refusal_count(); + if reject_audit { + fixture + .audit_capture + .fail_on(registry_breg::audit::AUDIT_SCHEMA, "refusal"); + } + let request = http + .request(method.clone(), &url) + .header("if-match", etag.as_str()) + .header( + "idempotency-key", + format!("attachment-accounting-{reject_audit}"), + ); + let request = if method == Method::PATCH { + request + .header("content-type", "text/plain") + .body("Synthetic document") + } else { + request + }; + let response = request.send().await.unwrap(); + assert_eq!(response.status(), expected_status, "{method}"); + let problem: Value = response.json().await.unwrap(); + assert_eq!(problem["code"], expected_code, "{method}"); + assert!(problem.get("failedCheck").is_none(), "{method}"); + assert!(problem.get("guardReason").is_none(), "{method}"); + let accepted = fixture.audit_capture.entries()[before_entries..] + .iter() + .any(|entry| { + entry["record"]["phase"] == "refusal" + && entry["record"]["method"] == method.as_str() + }); + let rejected = fixture.audit_capture.matched_refusal_count() > before_rejections; + assert_eq!( + (accepted, rejected), + (!reject_audit, reject_audit), + "{method}" + ); + assert_eq!( + membership_refusals().await - before_count, + expected_delta, + "{method}" + ); + } + fixture.finish().await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn submitted_create_membership_controls_attachments_answers_and_commands() { + let mut project = source(true); + project["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("task-reviewer"); + project["reviewAuthorities"] = + json!({"casework":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + let action = &mut project["actions"]["correct-name"]; + action.as_object_mut().unwrap().remove("commitGuards"); + action["inputs"][0] = json!({"id":"organization","type":"reference","target":"organization", + "required":true,"classification":"internal"}); + action["plan"]["effects"] = json!([{ + "id":"record","target":{"recordType":"target"},"operation":"create", + "set":{"name":{"fromInput":"value"},"jurisdiction":{"value":"zone-a"}, + "organization":{"fromInput":"organization"}} + }]); + let proposal = &mut action["execution"]["proposal"]; + proposal["review"] = json!({"type":"required","authority":"casework","source":"proposal-security", + "policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); + proposal["reviewContext"]["fields"] = json!({"proposedName":{"type":"input","input":"value"}}); + proposal["attachments"] = json!([ + {"id":"support","required":false,"maximumBytes":64,"contentTypes":["text/plain"],"classification":"restricted"} + ]); + proposal["additions"] = json!({"id":"other","maximumBytes":64,"maximumCount":3, + "contentTypes":["text/plain"],"classification":"restricted"}); + let permissions = &mut project["accessProfiles"]["clerk"]["permissions"]; + let targets = json!([ + {"recordType":"target","rowBoundaries":[{"field":"organization","membership":"membership"}]}, + {"recordType":"organization","rowBoundaries":"unrestricted"} + ]); + permissions["actions"][0]["targets"] = targets.clone(); + permissions["proposals"][0] = json!({ + "action":"correct-name","ownership":"caller","targets":targets, + "operations":["get","list","get-review-context","get-review-status","edit","submit","revise","rebase","cancel","retry","answer","add"], + "readableInputs":["organization","value"],"readableContextFields":["proposedName"], + "readableAttachments":["support","other"],"writableAttachments":["support","other"] + }); + project["accessProfiles"]["task-context"] = json!({ + "principalClaim":"registry_principal","actorKind":"service","requesterClients":["agent-client"], + "requiredScopes":["proposal:task-context"],"requiredPurposes":["registry-administration"], + "permissions":{"proposals":[{"action":"correct-name","operations":["get-task-grant-context"], + "readableContextFields":["proposedName"],"targets":targets}]} + }); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(project), + human_clerk(), + |service| service.with_review_result_source(review_binding()), + ) + .await; + let organization = create( + &fixture.http, + "organizations", + json!({"name":"Unit"}), + "attachment-unit", + ) + .await; + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"author","active":true}), + "attachment-membership", + ) + .await; + let input = json!({"organization":organization,"value":"Proposed"}); + let (status, draft, etag) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":input}), + Some("start-attachments"), + None, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let id = uuid::Uuid::parse_str(draft["id"].as_str().unwrap()).unwrap(); + let base = format!("/v1/proposals/{id}"); + let attachment = format!("{base}/attachments/support?accessProfile=clerk"); + let addition_upload = format!("{base}/additions/other?accessProfile=clerk"); + let http = reqwest::Client::new(); + let document = |method: Method, path: &str, key: &str, etag: &str| { + let sends_bytes = method != Method::DELETE; + let request = http + .request(method, format!("{}{path}", fixture.http.base_url)) + .header("if-match", etag) + .header("idempotency-key", key); + if sends_bytes { + request + .header("content-type", "text/plain") + .body("Synthetic document") + } else { + request + } + }; + let mut etag = etag.unwrap(); + for (method, key) in [ + (Method::PATCH, "attach-draft-file"), + (Method::DELETE, "remove-draft-file"), + (Method::PATCH, "restore-draft-file"), + ] { + let response = document(method, &attachment, key, &etag) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + etag = response.headers()["etag"].to_str().unwrap().to_owned(); + } + let (status, _, submitted_etag) = send( + &fixture.http, + Method::POST, + &format!("{base}/submit?accessProfile=clerk"), + json!({}), + Some("submit-attachments"), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::OK); + let response = document( + Method::POST, + &addition_upload, + "add-document", + &submitted_etag.unwrap(), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let etag = response.headers()["etag"].to_str().unwrap().to_owned(); + let value: Value = response.json().await.unwrap(); + let addition = value["additions"]["other"]["items"][0]["id"] + .as_str() + .unwrap(); + let addition_download = + format!("{base}/additions/{addition}?submissionVersion=1&accessProfile=clerk"); + let attachment_download = format!("{attachment}&submissionVersion=1"); + for path in [&attachment_download, &addition_download] { + let response = http + .get(format!("{}{path}", fixture.http.base_url)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert!(response.bytes().await.unwrap().as_ref() == b"Synthetic document"); + } + // Install the synthetic review acceptance and mirrored ask. The maintained + // review-delivery suite independently exercises their provider transport. + let row = fixture + .database + .admin + .query_one( + "SELECT create_request,expected_policy,expected_submission_digest + FROM registry_internal.registry_proposal_review_submissions WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap(); + let create: registry_review_client::ReviewCreateRequest = + serde_json::from_value(row.get(0)).unwrap(); + let accepted = registry_review_client::ReviewRequestAccepted { + request_id: uuid::Uuid::new_v4(), + subject: create.subject, + policy: serde_json::from_value(row.get(1)).unwrap(), + submission_digest: registry_review_client::SubmissionDigest::parse( + row.get::<_, String>(2).as_str(), + ) + .unwrap(), + }; + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET state='accepted',accepted_binding=$1 WHERE proposal_id=$2", + &[&serde_json::to_value(&accepted).unwrap(), &id], + ) + .await + .unwrap(); + let as_of = chrono::Utc::now(); + let ask = uuid::Uuid::new_v4(); + fixture.database.admin.execute( + "INSERT INTO registry_internal.registry_proposal_review_asks + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version,text,wants,asked_at,asked_at_wire,state) + VALUES ('casework',$1,$2,'correct-name',$3,1,'Synthetic question',$4,$5,$6,'open')", + &[&accepted.request_id,&ask,&id,&json!([{"kind":"answer"}]),&as_of,&as_of.to_rfc3339()] + ).await.unwrap(); + let answer = format!("{base}/asks/{ask}/answer?accessProfile=clerk"); + let (status, _, answered_etag) = send( + &fixture.http, + Method::POST, + &answer, + json!({"text":"Synthetic answer"}), + Some("answer-ask"), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::OK); + let etag = answered_etag.unwrap(); + let (status, context, _) = send( + &fixture.http, + Method::GET, + &format!("{base}/review-context?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + context["context"]["fields"], + json!({"proposedName":"Proposed"}) + ); + let (status, _, _) = send( + &fixture.http, + Method::GET, + &format!("{base}/review-status?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + let idp = MockIdp::start().await; + let auth = authenticator(&fixture.registry, &idp).await; + let task_caller = fixture.client_for(auth.authenticate(&idp.mint_token(json!({ + "aud":"urn:example:breg","sub":"author","azp":"agent-client","registry_principal":"author", + "registry_actor_kind":"service","registry_purpose":"registry-administration","scope":"proposal:task-context" + }))).await.unwrap()).await; + let task_path = format!("{base}/task-grant-context?accessProfile=task-context"); + let task_request = json!({ + "expected":{"actionId":"correct-name","subject":context["subject"],"contract":context["context"]["contract"]}, + "requestId":accepted.request_id,"taskId":uuid::Uuid::new_v4(),"taskRevision":1, + "policy":accepted.policy,"purpose":"task-grant","fields":["proposedName"] + }); + let (status, task_context, _) = send( + &task_caller, + Method::POST, + &task_path, + task_request.clone(), + None, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + task_context["proposal"]["context"]["fields"], + json!({"proposedName":"Proposed"}) + ); + set_membership_active(&fixture.http, &membership, false).await; + let (status, problem, _) = send( + &task_caller, + Method::POST, + &task_path, + task_request, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + assert!(problem.get("proposal").is_none()); + for path in [&attachment_download, &addition_download] { + let response = http + .get(format!("{}{path}", fixture.http.base_url)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.json::().await.unwrap()["code"], + "resource.not-found" + ); + } + for (method, path, key, expected, problem) in [ + ( + Method::PATCH, + &attachment, + "deny-attachment-replace", + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ( + Method::DELETE, + &attachment, + "remove-draft-file", + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ( + Method::POST, + &addition_upload, + "deny-addition", + StatusCode::NOT_FOUND, + "resource.not-found", + ), + ] { + let response = document(method, path, key, &etag).send().await.unwrap(); + assert_eq!(response.status(), expected); + let body = response.json::().await.unwrap(); + assert_eq!(body["code"], problem); + assert!(body.get("failedCheck").is_none()); + } + let (status, problem, _) = send( + &fixture.http, + Method::POST, + &answer, + json!({"text":"Synthetic answer"}), + Some("answer-ask"), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + for operation in ["review-context", "review-status"] { + let (status, problem, _) = send( + &fixture.http, + Method::GET, + &format!("{base}/{operation}?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + } + for operation in ["revise", "rebase", "cancel", "retry"] { + let (status, problem, _) = send( + &fixture.http, + Method::POST, + &format!("{base}/{operation}?accessProfile=clerk"), + if matches!(operation, "revise" | "rebase") { + json!({"input":input}) + } else { + json!({}) + }, + Some(operation), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED); + assert_eq!(problem["code"], "precondition.failed"); + assert!(problem.get("failedCheck").is_none()); + } + fixture.finish().await; +} + fn caller(subject: &str) -> VerifiedRequestClaims { caller_in(subject, "zone-a") } @@ -2701,6 +3536,15 @@ fn link_source() -> Value { /// Proposal id). async fn linked_history(fixture: &client_http::ClientFixture) -> (String, String, String) { let (organization, target) = seed(fixture).await; + let id = apply_and_link_history(fixture, &organization, &target).await; + (organization, target, id) +} + +async fn apply_and_link_history( + fixture: &client_http::ClientFixture, + organization: &str, + target: &str, +) -> String { let (code, condition, _) = send( &fixture.http, Method::POST, @@ -2754,7 +3598,7 @@ async fn linked_history(fixture: &client_http::ClientFixture) -> (String, String ) .await; assert_eq!(code, StatusCode::OK, "{applied}"); - (organization, target, id) + id } async fn history( @@ -2897,6 +3741,59 @@ async fn record_history_omits_the_proposal_from_a_profile_without_a_proposal_gra fixture.finish().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn record_history_rechecks_proposal_membership_without_hiding_the_revision() { + let mut project = link_source(); + project["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + let clerk_permissions = &mut project["accessProfiles"]["clerk"]["permissions"]; + clerk_permissions["proposals"][0]["targets"][0]["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); + clerk_permissions["actions"][0]["targets"][0]["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); + let fixture = client_http::ClientFixture::start(compile(project), clerk()).await; + let (organization, target) = seed(&fixture).await; + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"author","active":true}), + "history-membership", + ) + .await; + let id = apply_and_link_history(&fixture, &organization, &target).await; + assert_link(&fixture.http, &target, "clerk", &id).await; + set_membership_active(&fixture.http, &membership, false).await; + assert_no_link(&fixture.http, &target, "clerk").await; + let (status, problem, _) = send( + &fixture.http, + Method::GET, + &format!("/v1/proposals/{id}?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + let (status, problem, _) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":{"target":target,"value":"Proposed"}}), + Some("start-without-membership"), + None, + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED); + assert_eq!(problem["code"], "precondition.failed"); + assert!(problem.get("failedCheck").is_none()); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn record_history_omits_the_proposal_when_ownership_does_not_match() { let fixture = client_http::ClientFixture::start(compile(link_source()), clerk()).await; diff --git a/crates/registry-breg/tests/postgres_read_dependencies.rs b/crates/registry-breg/tests/postgres_read_dependencies.rs index ab74ce3b1f..68e440203e 100644 --- a/crates/registry-breg/tests/postgres_read_dependencies.rs +++ b/crates/registry-breg/tests/postgres_read_dependencies.rs @@ -363,7 +363,7 @@ async fn send(app: &axum::Router, uri: &str, lookup: bool, tenant: &str) -> (Sta VerifiedRequestClaims::authenticated( "registry_principal", "test-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::from([( "tenant".to_owned(), @@ -412,7 +412,7 @@ fn compiled_registry( {"id":"population","sql":"population.sql","key":"id","execution":"live","fields":[{"id":"population","type":"int64","classification":"internal"}]} ] }}, - "accessProfiles":{"reader": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"reader": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get","list","lookup"], "readableFields":["code","active","population"], diff --git a/crates/registry-breg/tests/postgres_record_profile_conformance.rs b/crates/registry-breg/tests/postgres_record_profile_conformance.rs index 659d985b06..6291f59761 100644 --- a/crates/registry-breg/tests/postgres_record_profile_conformance.rs +++ b/crates/registry-breg/tests/postgres_record_profile_conformance.rs @@ -226,7 +226,7 @@ async fn real_postgres_registry_record_profile_matches_the_cross_product_semanti #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn breg_client_executes_metadata_bound_direct_writes_against_real_postgres() { let harness = PilotHarness::start("asset-site-placement").await; - let token = harness.token("asset-management", &[]); + let token = harness.token_with_scopes("asset-management", &[], &["asset:manage"]); let http_server = harness.serve_http().await; let client = BaseRegistryClient::new( BaseRegistryClientConfig::new_without_peer_policy( diff --git a/crates/registry-breg/tests/postgres_record_timer_clock.rs b/crates/registry-breg/tests/postgres_record_timer_clock.rs index c5d54ad17d..96127b2292 100644 --- a/crates/registry-breg/tests/postgres_record_timer_clock.rs +++ b/crates/registry-breg/tests/postgres_record_timer_clock.rs @@ -932,7 +932,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"service-editor": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["service-administration"], "permissions":{"records":[{ "recordType":"service", diff --git a/crates/registry-breg/tests/postgres_record_timer_retention.rs b/crates/registry-breg/tests/postgres_record_timer_retention.rs index 4bc32f98b7..f57931920d 100644 --- a/crates/registry-breg/tests/postgres_record_timer_retention.rs +++ b/crates/registry-breg/tests/postgres_record_timer_retention.rs @@ -797,7 +797,7 @@ fn timer_project_source() -> Value { }]} }}, "accessProfiles":{"service-editor": {"default":true,"principalClaim":"registry_principal", - "requiredScopes":"unrestricted","requiredPurposes":["service-administration"], + "requiredScopes":["records:write"],"requiredPurposes":["service-administration"], "permissions":{"records":[{ "recordType":"service","operations":["create","get","patch"], "readableFields":["jurisdiction","status","activates-at"], diff --git a/crates/registry-breg/tests/postgres_record_timers.rs b/crates/registry-breg/tests/postgres_record_timers.rs index e28d436106..34fcfcb4e0 100644 --- a/crates/registry-breg/tests/postgres_record_timers.rs +++ b/crates/registry-breg/tests/postgres_record_timers.rs @@ -7518,7 +7518,7 @@ fn timer_project_source() -> Value { "id":"activated","target":{"fromInput":"service"},"operation":"patch","set":{"status":{"value":"active"}} }]} }}, - "accessProfiles":{"service-editor": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"service-editor": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["service-administration"], "permissions":{"records":[{ "recordType":"service","operations":["create","get","patch"], diff --git a/crates/registry-breg/tests/postgres_reference_integrity.rs b/crates/registry-breg/tests/postgres_reference_integrity.rs index 6207d735b2..b15a169cd4 100644 --- a/crates/registry-breg/tests/postgres_reference_integrity.rs +++ b/crates/registry-breg/tests/postgres_reference_integrity.rs @@ -840,13 +840,13 @@ fn event_record_registry() -> registry_breg::CompiledRegistry { "occurredAt":{"at":"noted-on"} } }}, - "accessProfiles":{"subject-operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["operations"], + "accessProfiles":{"subject-operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"subject","operations":["create","get","patch","tombstone"], "readableFields":["jurisdiction","name"],"writableFields":["jurisdiction","name"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"recorder": {"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["operations"], + },"recorder": {"principalClaim":"principal","requiredScopes":["records:write"],"requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"decision","operations":["create","get"], "readableFields":["jurisdiction","subject","corrects","occurred-on"], @@ -1125,13 +1125,13 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { {"id":"alternate","type":"reference","target":"target","onDelete":"restrict","classification":"internal"} ] }}, - "accessProfiles":{"target-operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["operations"], + "accessProfiles":{"target-operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"target","operations":["create","get","patch","tombstone"], "readableFields":["jurisdiction","name","related"],"writableFields":["jurisdiction","name","related"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"linker": {"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["operations"], + },"linker": {"principalClaim":"principal","requiredScopes":["records:write"],"requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"source","operations":["create","get","patch","tombstone","batch"], "readableFields":["jurisdiction","name","target","alternate"], diff --git a/crates/registry-breg/tests/postgres_spatial_migration.rs b/crates/registry-breg/tests/postgres_spatial_migration.rs index 266fe115c9..a25cf07e77 100644 --- a/crates/registry-breg/tests/postgres_spatial_migration.rs +++ b/crates/registry-breg/tests/postgres_spatial_migration.rs @@ -927,7 +927,7 @@ fn module_bytes(variant: Variant) -> Vec { r#",{"id":"legacy","type":"string","maximumLength":16,"classification":"internal"}"# }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"site":{{"primaryDataset":"spatial-migration-registry","route":"sites","mutationMode":"mutable","classification":"internal","fields":[{{"id":"code","type":"string","maximumLength":16,"required":true,"classification":"internal"}}{point}{legacy}{polygon}]{geometry_field},"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list","create","patch"],"readableFields":["code"{geometry_access}],"writableFields":["code"{geometry_access}]{spatial_queries}}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"site":{{"primaryDataset":"spatial-migration-registry","route":"sites","mutationMode":"mutable","classification":"internal","fields":[{{"id":"code","type":"string","maximumLength":16,"required":true,"classification":"internal"}}{point}{legacy}{polygon}]{geometry_field},"accessProfiles":{{"reader":{{"requiredScopes":["records:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list","create","patch"],"readableFields":["code"{geometry_access}],"writableFields":["code"{geometry_access}]{spatial_queries}}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/postgres_spatial_storage.rs b/crates/registry-breg/tests/postgres_spatial_storage.rs index 4c7a47d525..270ac9e0f9 100644 --- a/crates/registry-breg/tests/postgres_spatial_storage.rs +++ b/crates/registry-breg/tests/postgres_spatial_storage.rs @@ -140,7 +140,7 @@ fn compiled_spatial_registry() -> registry_breg::CompiledRegistry { ], "geojson":{"geometryField":"location"} }}, - "accessProfiles":{"map-reader": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"map-reader": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"site","operations":["create","get","list","patch","tombstone"], "readableFields":["code","location"],"writableFields":["code","location"], "spatialQueries":{"bbox":{"maximumLongitudeSpanDegrees":0.25,"maximumLatitudeSpanDegrees":1.5}}, @@ -173,7 +173,7 @@ fn compiled_spatial_derived_registry() -> registry_breg::CompiledRegistry { "fields":[{"id":"map-label","type":"string","maximumLength":64,"classification":"internal"}] }] }}, - "accessProfiles":{"map-reader": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"map-reader": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"site","operations":["create","get","list","patch"], "readableFields":["code","location","map-label"], "writableFields":["code","location"], @@ -222,7 +222,7 @@ fn compiled_spatial_cross_entity_derived_registry() -> registry_breg::CompiledRe "fields":[{"id":"map-label","type":"string","maximumLength":96,"classification":"internal"}] }] }}, - "accessProfiles":{"map-reader": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"map-reader": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"zone","operations":["create","get","list"], "readableFields":["code","label"],"writableFields":["code","label"], "rowBoundaries": "unrestricted" diff --git a/crates/registry-breg/tests/postgres_statistics_exact.rs b/crates/registry-breg/tests/postgres_statistics_exact.rs index 739160e061..9362131a43 100644 --- a/crates/registry-breg/tests/postgres_statistics_exact.rs +++ b/crates/registry-breg/tests/postgres_statistics_exact.rs @@ -91,7 +91,7 @@ fn registry_source(dimension: &str) -> Value { "filterableFields":["subject","active","category","event-date","evaluated-category"],"allowCount":true, "rowBoundaries":"unrestricted" }],"datasets":[{"dataset":"records-by-category","operations":["read-live"]}]}}, - "seed": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "seed": {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"record","operations":["create"], "writableFields":["subject","active","category","event-date","amount","quantity"], "rowBoundaries":"unrestricted" diff --git a/crates/registry-breg/tests/postgres_statistics_http.rs b/crates/registry-breg/tests/postgres_statistics_http.rs index 7beb06d8bd..f8c5d8a69d 100644 --- a/crates/registry-breg/tests/postgres_statistics_http.rs +++ b/crates/registry-breg/tests/postgres_statistics_http.rs @@ -4870,7 +4870,7 @@ fn statistics_registry_source() -> Value { "readableFields":["subject","active","category","event-date","jurisdiction"], "filterableFields":["subject","active","category","event-date","jurisdiction"],"allowCount":true,"rowBoundaries":"unrestricted" }],"datasets":[{"dataset":"records-by-category","operations":["publish","read-releases"]}]}}, - "seed": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "seed": {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"record","operations":["create"], "writableFields":["subject","active","category","event-date","jurisdiction"],"rowBoundaries":"unrestricted" }]}}, diff --git a/crates/registry-breg/tests/postgres_statistics_measures.rs b/crates/registry-breg/tests/postgres_statistics_measures.rs index 9025c8de32..ccd01f3284 100644 --- a/crates/registry-breg/tests/postgres_statistics_measures.rs +++ b/crates/registry-breg/tests/postgres_statistics_measures.rs @@ -651,7 +651,7 @@ fn registry_source(dimensions: &[&str], measures: Value) -> Value { "filterableFields":["subject","active","category","event-date"],"allowCount":true, "rowBoundaries":"unrestricted" }],"datasets":[{"dataset":"records-by-category","operations":["read-live"]}]}}, - "seed": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "seed": {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"record","operations":["create"], "writableFields":["subject","active","category","event-date","amount","quantity"], "rowBoundaries":"unrestricted" diff --git a/crates/registry-breg/tests/postgres_tombstone_revision.rs b/crates/registry-breg/tests/postgres_tombstone_revision.rs index 4aa4938fe1..05d3cc1945 100644 --- a/crates/registry-breg/tests/postgres_tombstone_revision.rs +++ b/crates/registry-breg/tests/postgres_tombstone_revision.rs @@ -602,7 +602,7 @@ fn compiled_registry(tombstone: bool) -> registry_breg::CompiledRegistry { {{"id":"message","type":"string","maximumLength":128,"required":true,"classification":"public"}} ] }}}}, - "accessProfiles":{{"operator":{{"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{{"operator":{{"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{{"records":[{{ "recordType":"widget","operations":[{operations}], diff --git a/crates/registry-breg/tests/postgres_webhook_delivery.rs b/crates/registry-breg/tests/postgres_webhook_delivery.rs index 1d6696da63..35c2d066c2 100644 --- a/crates/registry-breg/tests/postgres_webhook_delivery.rs +++ b/crates/registry-breg/tests/postgres_webhook_delivery.rs @@ -3229,7 +3229,7 @@ const WEBHOOK_PROJECT: &[u8] = br#"{"datasets":{"test-dataset": {}}, } }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"case","operations":["create","get","list"], @@ -3264,7 +3264,7 @@ fn local_hook_compiled_registry() -> registry_breg::CompiledRegistry { } }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"case","operations":["create","get","list"], diff --git a/crates/registry-breg/tests/postgres_webhook_outbox.rs b/crates/registry-breg/tests/postgres_webhook_outbox.rs index acfa6a4890..107e50574b 100644 --- a/crates/registry-breg/tests/postgres_webhook_outbox.rs +++ b/crates/registry-breg/tests/postgres_webhook_outbox.rs @@ -738,7 +738,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "handler":{"type":"url","destinationId":"case-operations"} }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"case","operations":["create","patch","get","list"], diff --git a/crates/registry-breg/tests/postgres_workspace_metadata.rs b/crates/registry-breg/tests/postgres_workspace_metadata.rs index 747a10c283..886de1af74 100644 --- a/crates/registry-breg/tests/postgres_workspace_metadata.rs +++ b/crates/registry-breg/tests/postgres_workspace_metadata.rs @@ -25,7 +25,7 @@ fn operation<'a>(document: &'a Value, id: &str) -> &'a Value { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_workspace_metadata_mutation_and_replay_contract() { let harness = PilotHarness::start("asset-site-placement").await; - let token = harness.token("asset-management", &[]); + let token = harness.token_with_scopes("asset-management", &[], &["asset:manage"]); let metadata_response = harness .send(Method::GET, "/v1/registry", Some(&token), &[], Vec::new()) .await; @@ -126,7 +126,7 @@ async fn real_postgres_workspace_metadata_mutation_and_replay_contract() { "schema and parser disagree: {document}" ); } - let planner_token = harness.token("site-planning", &[]); + let planner_token = harness.token_with_scopes("site-planning", &[], &["asset:plan"]); let planner = response_json( harness .send( diff --git a/crates/registry-breg/tests/proposal_generated_identifier_policies.rs b/crates/registry-breg/tests/proposal_generated_identifier_policies.rs index 77df9fd355..06b09ce767 100644 --- a/crates/registry-breg/tests/proposal_generated_identifier_policies.rs +++ b/crates/registry-breg/tests/proposal_generated_identifier_policies.rs @@ -55,7 +55,7 @@ fn project() -> Value { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["proposals:write"], "permissions": { "actions": [{ "action": "register", diff --git a/crates/registry-breg/tests/script_baseline.rs b/crates/registry-breg/tests/script_baseline.rs index f881c8542d..c5cea14035 100644 --- a/crates/registry-breg/tests/script_baseline.rs +++ b/crates/registry-breg/tests/script_baseline.rs @@ -37,7 +37,7 @@ fn action(script: &str) -> CompiledAction { "refusals":[{"code":"blank-label","label":"A label is required."}], "writes":[{"id":"record","target":{"recordType":"record"},"operation":"create","fields":["label","count","amount"]}] }}}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "actions":[ {"action":"register-record","operations":["invoke"],"targets":[{"recordType":"record","rowBoundaries":"unrestricted"}],"results":["record"]} ] diff --git a/crates/registry-breg/tests/standing_agent_ceiling.rs b/crates/registry-breg/tests/standing_agent_ceiling.rs index 80076c154b..8db7b12fb0 100644 --- a/crates/registry-breg/tests/standing_agent_ceiling.rs +++ b/crates/registry-breg/tests/standing_agent_ceiling.rs @@ -48,7 +48,7 @@ fn project() -> Value { "plan":{"type":"fixed","effects":[{"id":"corrected","target":{"fromInput":"case-ref"},"operation":"patch","set":{"label":{"fromInput":"new-label"}}}]}} }, "accessProfiles":{ - "clerk": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","actorKind":"human","requesterClients":["clerk-portal"], + "clerk": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"actorKind":"human","requesterClients":["clerk-portal"], "permissions":{"records":[ {"recordType":"case","operations":["create","get","list","import"],"readableFields":["label"],"writableFields":["label"],"rowBoundaries":"unrestricted"}, {"recordType":"memo","operations":["create","get","list","patch"],"readableFields":["label"],"writableFields":["label"],"rowBoundaries":"unrestricted"}, @@ -57,7 +57,7 @@ fn project() -> Value { {"action":"relabel-note","operations":["invoke"],"targets":[{"recordType":"note","rowBoundaries":"unrestricted"}],"results":["relabelled"]}, {"action":"correct-case","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}], "proposals":[{"action":"correct-case","operations":["get","list","edit","submit","revise","cancel","apply","rebase","retry","get-review-status"],"ownership":"caller","readableInputs":["case-ref","new-label"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]}}, - "assistant": {"principalClaim":"registry_principal","requiredScopes":"unrestricted","actorKind":"agent","requesterClients":["assistant-client"], + "assistant": {"principalClaim":"registry_principal","requiredScopes":["proposals:draft"],"actorKind":"agent","requesterClients":["assistant-client"], "permissions":{"records":[ {"recordType":"case","operations":["get","list"],"readableFields":["label"],"rowBoundaries":"unrestricted"}, {"recordType":"memo","operations":["get","list"],"readableFields":["label"],"writableFields":["label"],"rowBoundaries":"unrestricted"}, diff --git a/crates/registry-breg/tests/support/action_evidence_provider.rs b/crates/registry-breg/tests/support/action_evidence_provider.rs index e4966ceeb6..109b09685d 100644 --- a/crates/registry-breg/tests/support/action_evidence_provider.rs +++ b/crates/registry-breg/tests/support/action_evidence_provider.rs @@ -30,6 +30,10 @@ impl EvidenceProvider { pub async fn start() -> Self { let mut key = registry_platform_crypto::PrivateJwk::parse(r#"{"kty":"EC","crv":"P-256","d":"MInq88dvxx-e1-MEfmdes4I6Gt2QbsKoEmYyk2j0Oj4","x":"3kpzAK6fK6xyfqbdp0HvfZCqfgz7MajMviKyM6bsNE4","y":"GkSdSn8xqge52rp9Sv-4qPaw1Q9TJ2eMUyY22flavLU","alg":"ES256"}"#).unwrap(); key.kid = Some(key.public().jkt().unwrap()); + Self::start_with_key(key).await + } + + pub async fn start_with_key(key: registry_platform_crypto::PrivateJwk) -> Self { let key = Arc::new(key); let public = serde_json::to_value(key.public()).unwrap(); let requests = Arc::new(Mutex::new(Vec::new())); diff --git a/crates/registry-breg/tests/support/event_record_registry.rs b/crates/registry-breg/tests/support/event_record_registry.rs index 36ab85d69c..6dee45c1dc 100644 --- a/crates/registry-breg/tests/support/event_record_registry.rs +++ b/crates/registry-breg/tests/support/event_record_registry.rs @@ -237,7 +237,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] permissions: records: - {recordType: grant, operations: [get, list], readableFields: [grant-number, status], rowBoundaries: unrestricted} diff --git a/crates/registry-breg/tests/support/membership_targets.rs b/crates/registry-breg/tests/support/membership_targets.rs new file mode 100644 index 0000000000..796be3bd54 --- /dev/null +++ b/crates/registry-breg/tests/support/membership_targets.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 + +#[path = "action_requirements.rs"] +mod action_requirements; + +use super::breg_fixture_crate::model::{ + CompiledActionExecution, CompiledActionInventory, CompiledMembershipBoundary, +}; +use super::breg_fixture_crate::{ + compile_project, parse_project_json, CompileProfile, CompiledRegistry, +}; +use serde_json::{json, Value}; + +fn fixture() -> Value { + serde_json::from_str(include_str!( + "../../../../products/breg/fixtures/organization-membership-access/registry.yaml" + )) + .unwrap() +} + +fn compile(source: &Value) -> CompiledRegistry { + compile_project( + &parse_project_json(&serde_json::to_vec(source).unwrap()).unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap() +} + +pub fn immediate(with_steward: bool) -> (CompiledRegistry, CompiledActionInventory) { + let mut source = action_requirements::project(); + let fixture = fixture(); + source["recordTypes"]["membership"] = fixture["recordTypes"]["membership"].clone(); + if with_steward { + let mut steward = fixture["accessProfiles"]["steward"].clone(); + steward["permissions"]["records"] = json!([steward["permissions"]["records"][1]]); + source["accessProfiles"]["steward"] = steward; + } + source["recordTypes"]["membership"]["fields"][0]["target"] = json!("parent"); + source["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + source["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("indexes"); + source["recordTypes"]["parent"]["fields"].as_array_mut().unwrap().push( + json!({"id":"directory","type":"reference","target":"parent","classification":"internal"}), + ); + let registry = compile(&source); + let mut actions = registry.actions().clone(); + for target in &mut actions.actions[0].permissions[0].targets { + let field = match target.entity_id.as_str() { + "child" => "parent", + "parent" => "directory", + other => panic!("unexpected target {other}"), + }; + target + .membership_boundaries + .push(boundary(®istry, field)); + } + (registry, actions) +} + +#[allow(dead_code)] +pub fn proposal(mut source: Value, automatic: bool) -> (CompiledRegistry, CompiledActionInventory) { + let fixture = fixture(); + for id in ["membership", "organization"] { + source["recordTypes"][id] = fixture["recordTypes"][id].clone(); + source["recordTypes"][id]["primaryDataset"] = json!("directory"); + } + source["recordTypes"]["membership"]["accessRequirements"]["requiredScopes"] = + json!(["proposal:manage"]); + source["recordTypes"]["target"]["fields"].as_array_mut().unwrap().push( + json!({"id":"organization","type":"reference","target":"organization","classification":"internal"}), + ); + if automatic { + source["actions"]["correct-name"]["execution"]["proposal"]["application"] = + json!({"mode":"automatic"}); + source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = + json!(["get", "edit", "submit", "cancel"]); + } + let registry = compile(&source); + let mut actions = registry.actions().clone(); + let action = &mut actions.actions[0]; + for target in &mut action.permissions[0].targets { + target + .membership_boundaries + .push(boundary(®istry, "organization")); + } + let CompiledActionExecution::Proposal { proposal } = &mut action.execution else { + panic!("expected a compiled Proposal"); + }; + proposal.permissions[0].targets[0] + .membership_boundaries + .push(boundary(®istry, "organization")); + (registry, actions) +} + +fn boundary(registry: &CompiledRegistry, field: &str) -> CompiledMembershipBoundary { + let source = ®istry.entities()["membership"]; + let column = |field: &str| source.fields[field].physical_name.clone(); + CompiledMembershipBoundary { + field: field.into(), + membership_entity: source.id.clone(), + membership_table: source.physical_table.clone(), + membership_key_column: column("organization"), + principal_column: column("principal"), + active_column: column("active"), + } +} diff --git a/crates/registry-breg/tests/support/membership_write_journeys.rs b/crates/registry-breg/tests/support/membership_write_journeys.rs new file mode 100644 index 0000000000..eb4589e0fa --- /dev/null +++ b/crates/registry-breg/tests/support/membership_write_journeys.rs @@ -0,0 +1,3881 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::{membership_write_project, postgres_harness::TestDatabase, AlwaysReady}; +use axum::body::{to_bytes, Body}; +use axum::http::{HeaderMap, Method, Request, StatusCode}; +use registry_breg::api::{authenticated_router, HttpService, ReadRuntimeIdentity}; +use registry_breg::auth::{AuthenticatorIssuer, AuthorityClaimConfig, RegistryAuthenticator}; +use registry_breg::compiler::compile_project_with_assets; +use registry_breg::contract::ModuleAssetSource; +use registry_breg::cursor::CursorCodec; +use registry_breg::migration::{ + apply_verified_package, ActivationDeployment, ApplyPrecondition, ApplyRoles, ApplyTimeouts, + ApplyVerifiedPackageRequest, +}; +use registry_breg::package::{ + load_package, prepare_package_with_project_assets, PackageBuildRequest, PackageLoadContext, + PackageMigrationPlanInput, PackageSourceFile, FIXTURE_JOURNEYS_PATH, +}; +use registry_breg::postgres::{ + install_compiled_schema, managed_schema_fingerprint, ExpectedManagedCatalog, + ExpectedRegistryIdentity, PostgresRecordMutationService, PostgresRecordReadService, + RegistryLockKey, +}; +use registry_breg::{parse_project_json, CompileProfile, CompiledRegistry}; +use registry_platform_audit::AuditProfile; +use registry_platform_config::{DeclaredPosture, Posture, PostureSource}; +use registry_platform_httputil::FetchUrlPolicy; +use registry_platform_oidc::{ActorKind, DeclaredKinds, JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{oidc_verifier_config, MockIdp}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{sync::Arc, time::Duration}; +use tower::ServiceExt as _; +use uuid::Uuid; +use zeroize::Zeroizing; + +const PACKAGE: &str = "membership-writes"; +const AUDIENCE: &str = "urn:breg:membership-writes"; +const MEMBER: &str = "member"; +const MEMBERSHIP_WRITER: &str = "steward"; +const CLAIMED: &str = "claimed"; +const RECORDS: &str = "/v1/records/facilities"; + +struct Fixture { + database: TestDatabase, + registry: Arc, + identity: ExpectedRegistryIdentity, + app: axum::Router, + service: Arc, + authenticator: Arc, + development: axum::Router, + mutations: Arc, + idp: MockIdp, + keys: Keys, +} + +struct Keys { + allowed: String, + second: String, + inactive: String, + tombstoned: String, + foreign: String, + membership: String, + second_membership: String, +} + +impl Fixture { + async fn create(lock_timeout: Duration) -> Self { + Self::configured( + lock_timeout, + membership_write_project::project(), + Vec::new(), + |service| service, + ) + .await + } + + async fn configured( + lock_timeout: Duration, + project: Value, + assets: Vec, + configure: impl FnOnce(PostgresRecordMutationService) -> PostgresRecordMutationService, + ) -> Self { + Self::configured_with_isolation(lock_timeout, project, assets, "repeatable read", configure) + .await + } + + async fn configured_with_isolation( + lock_timeout: Duration, + project: Value, + assets: Vec, + isolation: &str, + configure: impl FnOnce(PostgresRecordMutationService) -> PostgresRecordMutationService, + ) -> Self { + Self::configured_with_pool(lock_timeout, project, assets, isolation, 4, configure).await + } + + async fn configured_with_pool( + lock_timeout: Duration, + project: Value, + assets: Vec, + isolation: &str, + pool_size: usize, + configure: impl FnOnce(PostgresRecordMutationService) -> PostgresRecordMutationService, + ) -> Self { + let bytes = serde_json::to_vec(&project).unwrap(); + let compiled = compile_project_with_assets( + &parse_project_json(&bytes).unwrap(), + &[], + &assets, + CompileProfile::Production, + ) + .expect("Production admits membership-bound Records and immediate Actions"); + let database = TestDatabase::create(pool_size).await; + let (mut migration, connection) = database.connect_migration().await; + let tx = migration.transaction().await.unwrap(); + install_compiled_schema(&tx, &compiled, &database.runtime_role) + .await + .unwrap(); + let fingerprint = managed_schema_fingerprint( + &tx, + &database.runtime_role, + &ExpectedManagedCatalog::compiled(&compiled), + ) + .await + .unwrap(); + tx.rollback().await.unwrap(); + drop(migration); + connection.abort(); + + let prepared = prepare_package_with_project_assets(PackageBuildRequest { + from_package_digest: None, + compiler_source_revision: "membership-writes-fixture".into(), + schema_fingerprint: fingerprint, + project: PackageSourceFile { + path: "registry.json".into(), + bytes, + }, + modules: vec![], + fixture_journeys: PackageSourceFile { + path: FIXTURE_JOURNEYS_PATH.into(), + bytes: b"apiVersion: id.registrystack.org/formats/breg/journeys/v1\nkind: BRegJourneys\njourneys: []\n".to_vec(), + }, + migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, + }, assets.into_iter().map(|asset| PackageSourceFile {path:asset.path, bytes:asset.bytes}).collect()) + .unwrap(); + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + let package_root = directory.path().join("package"); + prepared.publish_to_directory(&package_root).unwrap(); + let package = load_package( + &package_root, + &PackageLoadContext { + posture: Posture::Production, + }, + ) + .unwrap(); + let identity = apply_verified_package(ApplyVerifiedPackageRequest::new( + &database.migration_config, + &package, + ActivationDeployment::new("production", PACKAGE, PACKAGE), + ApplyPrecondition::InitialActivation, + ApplyRoles::new(&database.migration_role, &database.runtime_role), + ApplyTimeouts::new(Duration::from_secs(2), Duration::from_secs(5)).unwrap(), + database.activation_audit(), + )) + .await + .unwrap(); + let registry = Arc::new(package.registry().clone()); + database + .admin + .batch_execute(&format!( + "ALTER ROLE \"{}\" SET default_transaction_isolation = '{isolation}'", + database.runtime_role.as_str() + )) + .await + .unwrap(); + let pool = database.runtime_config.build_pool().unwrap(); + let client = pool.get_for_test().await.unwrap(); + assert_eq!( + client + .query_one("SHOW transaction_isolation", &[]) + .await + .unwrap() + .get::<_, String>(0), + isolation + ); + let facility = ®istry.entities()["facility"]; + assert!(client.query_one( + "SELECT c.relrowsecurity AND c.relforcerowsecurity AND NOT (r.rolsuper OR r.rolbypassrls) + FROM pg_catalog.pg_class c, pg_catalog.pg_roles r + WHERE c.oid = $1::text::regclass AND r.rolname = current_user", + &[&format!("registry_data.\"{}\"", facility.physical_table)] + ).await.unwrap().get::<_,bool>(0)); + drop(client); + let secret = || [Uuid::new_v4().into_bytes(), Uuid::new_v4().into_bytes()].concat(); + let audit = + database.audit(AuditProfile::production_from_secret_bytes(secret().into()).unwrap()); + let cursors = + Arc::new(CursorCodec::new(Zeroizing::new(secret()), Duration::from_secs(300)).unwrap()); + let lock_key = RegistryLockKey::derive(PACKAGE).unwrap(); + let records = Arc::new(PostgresRecordReadService::new( + pool.clone(), + registry.clone(), + identity.clone(), + lock_key, + lock_timeout, + audit.clone(), + cursors.clone(), + )); + let destinations = event_destinations(®istry, &secret()); + let mutations = Arc::new(configure( + PostgresRecordMutationService::new_with_event_destinations( + pool, + registry.clone(), + identity.clone(), + PACKAGE, + lock_key, + lock_timeout, + audit, + Some(Arc::new(destinations)), + ) + .with_action_timeout_for_test(Duration::from_secs(10)), + )); + let service = HttpService::new( + registry.clone(), + ReadRuntimeIdentity { + package_revision: identity.activation_id.clone(), + schema_fingerprint: identity.schema_fingerprint.clone(), + }, + records, + Arc::new(AlwaysReady), + cursors, + ) + .with_postgres_mutations(mutations.clone()); + let idp = MockIdp::start().await; + let issuer = AuthenticatorIssuer::new( + "fixture", + oidc_verifier_config(idp.issuer(), vec![AUDIENCE.into()]), + Arc::new(JwksFetcher::new_with_fetch_url_policy( + idp.jwks_uri(), + JwksFetcherConfig::defaults(), + FetchUrlPolicy::https_or_loopback(), + )), + ) + .with_declared_kinds(DeclaredKinds::Issuer(ActorKind::Human)); + let authenticator = Arc::new( + RegistryAuthenticator::with_issuers( + ®istry, + vec![issuer], + AuthorityClaimConfig::new("sub", None), + ) + .unwrap(), + ); + let development = authenticated_router( + Arc::new( + service + .clone() + .with_declared_posture_for_test(DeclaredPosture { + posture: Posture::Development, + source: PostureSource::Flag, + }), + ), + authenticator.clone(), + ); + let service = Arc::new(service); + let app = authenticated_router(service.clone(), authenticator.clone()); + let steward = mint(&idp, "steward", "records:manage membership:use", &[]); + let mut keys = Vec::new(); + for name in ["allowed", "second", "inactive", "tombstoned", "foreign"] { + keys.push( + request( + &app, + &steward, + Method::POST, + "/v1/records/organizations", + MEMBERSHIP_WRITER, + json!({"data":{"name":name,"owner":MEMBER}}), + None, + ) + .await + .success(StatusCode::CREATED) + .record_id(), + ); + } + let [allowed, second, inactive, tombstoned, foreign]: [String; 5] = + keys.try_into().unwrap(); + let mut membership = None; + let mut second_membership = None; + for (organization, active) in [ + (&allowed, true), + (&second, true), + (&inactive, false), + (&tombstoned, true), + ] { + let result = request( + &app, + &steward, + Method::POST, + "/v1/records/memberships", + MEMBERSHIP_WRITER, + json!({"data":{"organization":organization,"principal":MEMBER,"active":active}}), + None, + ) + .await + .success(StatusCode::CREATED); + if organization == &allowed { + membership = Some(result.record_id()); + } else if organization == &second { + second_membership = Some(result.record_id()); + } else if organization == &tombstoned { + request( + &app, + &steward, + Method::DELETE, + &format!("/v1/records/memberships/{}", result.record_id()), + MEMBERSHIP_WRITER, + Value::Null, + Some(result.etag()), + ) + .await + .success(StatusCode::OK); + } + } + Self { + database, + registry, + identity, + app, + service, + authenticator, + development, + mutations, + idp, + keys: Keys { + allowed, + second, + inactive, + tombstoned, + foreign, + membership: membership.unwrap(), + second_membership: second_membership.unwrap(), + }, + } + } + + fn member(&self) -> String { + mint(&self.idp, MEMBER, "", &[]) + } + + fn steward(&self) -> String { + mint(&self.idp, "steward", "records:manage membership:use", &[]) + } + + fn claimed(&self) -> String { + mint( + &self.idp, + MEMBER, + "records:claim", + &[&self.keys.allowed, &self.keys.second], + ) + } + + async fn seed(&self, key: Option<&str>, label: &str) -> Reply { + request( + &self.app, + &self.steward(), + Method::POST, + RECORDS, + MEMBERSHIP_WRITER, + json!({"data":{"organization":key,"label":label}}), + None, + ) + .await + .success(StatusCode::CREATED) + } + + async fn durable_state(&self) -> Value { + let entity = &self.registry.entities()["facility"]; + self.database.admin.query_one( + &format!( + "SELECT jsonb_build_array( + (SELECT jsonb_agg(to_jsonb(t) ORDER BY record_id) FROM registry_data.\"{}\" t), + (SELECT count(*) FROM registry_internal.registry_revisions), + (SELECT count(*) FROM registry_internal.registry_outbox), + (SELECT count(*) FROM registry_internal.registry_idempotency), + (SELECT count(*) FROM registry_internal.registry_generated_identifier_reservations), + (SELECT jsonb_agg(to_jsonb(c) ORDER BY entity_id, field_id, scope_values) + FROM registry_internal.registry_generated_identifier_counters c), + (SELECT jsonb_agg(to_jsonb(m) ORDER BY record_id) FROM {} m), + (SELECT count(*) FROM {}))", + entity.physical_table, + table(self, "membership"), + table(self, "organization"), + ), + &[], + ).await.unwrap().get(0) + } + + async fn proposal_markers(&self, proposal: &Reply) -> (i64, Option) { + let id = Uuid::parse_str(proposal.body["id"].as_str().unwrap()).unwrap(); + let row = self.database.admin.query_one( + "SELECT workflow_revision,blocked_reason FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ).await.unwrap(); + (row.get(0), row.get(1)) + } +} + +fn event_destinations( + registry: &CompiledRegistry, + signing_key: &[u8], +) -> registry_breg::event_destination::ActivatedEventDestinationRegistry { + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + write_test_secret( + &directory.path().join("events"), + hex::encode(signing_key).as_bytes(), + ); + let config = runtime_fixture(directory.path()); + let config = format!( + "{config} +destinations: + hooks: + record-events: + origin: https://events.example.test/ + path: /records + networkProfile: production-https + dnsFamily: dual-stack-strict + allowedPrivateCidrs: [] + hmacSha256KeyRef: secret:file/events + classificationCeiling: internal + deliveryCeilings: + attemptTimeoutMilliseconds: 2000 + maximumAttempts: 2 +" + ); + registry_breg::runtime_config::parse_runtime_config(&config, production_posture()) + .unwrap() + .activate_event_destinations(registry) + .unwrap() +} + +fn write_test_secret(path: &std::path::Path, bytes: &[u8]) { + std::fs::write(path, bytes).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } +} + +fn runtime_fixture(secret_root: &std::path::Path) -> String { + include_str!("../../../../products/breg/examples/minimal/runtime.example.yaml") + .replace("/var/lib/breg/secrets", secret_root.to_str().unwrap()) +} + +fn production_posture() -> DeclaredPosture { + DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Flag, + } +} + +fn mint(idp: &MockIdp, principal: &str, scope: &str, organizations: &[&str]) -> String { + let mut claims = json!({"aud":AUDIENCE,"sub":principal}); + if !scope.is_empty() { + claims["scope"] = json!(scope); + } + if !organizations.is_empty() { + claims["organization"] = json!(organizations); + } + idp.mint_token(claims) +} + +struct Reply { + status: StatusCode, + headers: HeaderMap, + bytes: Vec, + body: Value, +} + +impl Reply { + fn success(self, expected: StatusCode) -> Self { + assert_eq!(self.status, expected, "{}", self.body); + self + } + + fn problem(&self, status: StatusCode, code: &str) { + assert_eq!(self.status, status, "{}", self.body); + assert_eq!(self.body["code"], code); + if status == StatusCode::PRECONDITION_FAILED && code == "precondition.failed" { + assert!(self.body.get("failedCheck").is_none()); + assert!(self.body.get("guardReason").is_none()); + } + } + + fn record_id(&self) -> String { + self.body["data"]["recordIdentifier"] + .as_str() + .unwrap() + .to_owned() + } + + fn etag(&self) -> &str { + self.headers["etag"].to_str().unwrap() + } + + fn normalized_bytes(&self) -> Vec { + let trace = self.body["traceId"].as_str().unwrap(); + let bytes = std::str::from_utf8(&self.bytes).unwrap(); + bytes.replace(trace, &"0".repeat(trace.len())).into_bytes() + } + + fn golden(&self) -> Value { + let headers: std::collections::BTreeMap<_, _> = self + .headers + .iter() + .map(|(key, value)| (key.as_str(), value.to_str().unwrap())) + .collect(); + json!({ + "status":self.status.as_u16(), + "headers":headers, + "body":serde_json::from_slice::(&self.normalized_bytes()).unwrap() + }) + } + + fn assert_same_problem_except_check(&self, other: &Self) { + let without_check = |reply: &Self| { + let mut answer = reply.golden(); + answer["body"] + .as_object_mut() + .unwrap() + .remove("failedCheck"); + answer["headers"] + .as_object_mut() + .unwrap() + .remove("content-length"); + answer + }; + assert_eq!(without_check(self), without_check(other)); + } + + fn assert_same_problem(&self, other: &Self) { + assert_eq!(self.status, other.status); + assert_eq!(self.headers, other.headers); + assert_eq!(self.normalized_bytes(), other.normalized_bytes()); + } +} + +async fn request( + app: &axum::Router, + token: &str, + method: Method, + path: &str, + profile: &str, + body: Value, + if_match: Option<&str>, +) -> Reply { + request_with_key( + app, + token, + method, + path, + profile, + body, + if_match, + &Uuid::new_v4().to_string(), + ) + .await +} + +#[allow(clippy::too_many_arguments)] // Each value corresponds to a request member. +async fn request_with_key( + app: &axum::Router, + token: &str, + method: Method, + path: &str, + profile: &str, + body: Value, + if_match: Option<&str>, + key: &str, +) -> Reply { + let content_type = if method == Method::PATCH { + "application/json-patch+json" + } else { + "application/json" + }; + let mut builder = Request::builder() + .method(method) + .uri(format!("{path}?accessProfile={profile}")) + .header("authorization", format!("Bearer {token}")); + if !path.contains("/ingestion-runs") { + builder = builder.header("idempotency-key", key); + } + if !body.is_null() { + builder = builder.header("content-type", content_type); + } + if let Some(value) = if_match { + builder = builder.header("if-match", value); + } + let body = if body.is_null() { + Body::empty() + } else { + Body::from(body.to_string()) + }; + let (parts, body) = app + .clone() + .oneshot(builder.body(body).unwrap()) + .await + .unwrap() + .into_parts(); + let bytes = to_bytes(body, 1024 * 1024).await.unwrap().to_vec(); + let mut headers = parts.headers; + for name in ["traceparent", "x-request-id", "date"] { + headers.remove(name); + } + Reply { + status: parts.status, + headers, + body: if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap() + }, + bytes, + } +} + +fn record(id: &str) -> String { + format!("{RECORDS}/{id}") +} + +fn patch(field: &str, value: impl Into) -> Value { + json!([{"op":"replace","path":format!("/data/{field}"),"value":value.into()}]) +} + +async fn action(app: &axum::Router, token: &str, path: &str, profile: &str, input: Value) -> Reply { + request( + app, + token, + Method::POST, + &format!("/v1/actions/{path}"), + profile, + json!({"input":input}), + None, + ) + .await +} + +#[tokio::test] +async fn a_member_writes_in_their_key() { + let fixture = Fixture::create(Duration::from_secs(2)).await; + let member = fixture.member(); + let new = |key: &str, label: &str| json!({"data":{"organization":key,"label":label}}); + let before = fixture.durable_state().await; + let created = request( + &fixture.app, + &member, + Method::POST, + RECORDS, + MEMBER, + new(&fixture.keys.allowed, "direct-create"), + None, + ) + .await + .success(StatusCode::CREATED); + assert_eq!(created.body["data"]["revisionIdentifier"], "1"); + let path = record(&created.record_id()); + let same_key = request( + &fixture.app, + &member, + Method::PATCH, + &path, + MEMBER, + patch("label", "direct-patch"), + Some(created.etag()), + ) + .await + .success(StatusCode::OK); + assert_eq!(same_key.body["data"]["revisionIdentifier"], "2"); + let cross_key = request( + &fixture.app, + &member, + Method::PATCH, + &path, + MEMBER, + patch("organization", fixture.keys.second.as_str()), + Some(same_key.etag()), + ) + .await + .success(StatusCode::OK); + assert_eq!(cross_key.body["data"]["revisionIdentifier"], "3"); + assert_eq!( + cross_key.body["data"]["domainData"]["organization"], + fixture.keys.second + ); + let deleted = request( + &fixture.app, + &member, + Method::DELETE, + &path, + MEMBER, + Value::Null, + Some(cross_key.etag()), + ) + .await + .success(StatusCode::OK); + assert_eq!(deleted.body["data"]["revisionIdentifier"], "4"); + + let batch = request( + &fixture.app, &member, Method::POST, &format!("{RECORDS}:batch"), MEMBER, + json!({"items":[ + {"operation":"create","data":{"organization":fixture.keys.second,"label":"batch-create"}}, + {"operation":"create","data":{"organization":fixture.keys.allowed,"label":"open"}} + ]}), None, + ).await.success(StatusCode::OK); + assert_eq!(batch.body["results"].as_array().unwrap().len(), 2); + let open = batch.body["results"][1]["recordIdentifier"] + .as_str() + .unwrap(); + let linked = action( + &fixture.app, + &member, + "register-facility", + MEMBER, + json!({"organization":fixture.keys.allowed,"related":open,"label":"action-create"}), + ) + .await + .success(StatusCode::OK); + assert_eq!(linked.body["results"]["register"]["revision"], 1); + let linked_id = linked.body["results"]["register"]["recordId"] + .as_str() + .unwrap(); + let read = request( + &fixture.app, + &member, + Method::GET, + &record(linked_id), + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(read.body["data"]["domainData"]["related"], open); + let closed = action( + &fixture.app, + &member, + "close-facility", + MEMBER, + json!({"facility":open}), + ) + .await + .success(StatusCode::OK); + assert_eq!(closed.body["results"]["close"]["revision"], 2); + + let (run_path, chunk) = + announce_ingestion(&fixture, &member, &fixture.keys.allowed, "ingested").await; + let submitted = request( + &fixture.app, + &member, + Method::POST, + &format!("{run_path}/chunks"), + MEMBER, + chunk, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(submitted.body["run"]["status"], "complete"); + assert_eq!(submitted.body["run"]["committedItems"], 1); + let after = fixture.durable_state().await; + assert_eq!(after[1].as_i64().unwrap() - before[1].as_i64().unwrap(), 9); + assert_eq!(after[2].as_i64().unwrap() - before[2].as_i64().unwrap(), 9); + fixture.database.cleanup().await; +} + +async fn announce_ingestion( + fixture: &Fixture, + token: &str, + key: &str, + label: &str, +) -> (String, Value) { + let items = json!([{"operation":"create","data":{"organization":key,"label":label}}]); + let mut source = registry_platform_canonical_json::canonicalize_json(&items[0]).unwrap(); + source.push(b'\n'); + let prefix = hex::encode(Sha256::digest(&source)); + let digest = hex::encode(Sha256::digest( + registry_platform_canonical_json::canonicalize_json(&json!({"items":items})).unwrap(), + )); + let created = request( + &fixture.app, + token, + Method::POST, + &format!("{RECORDS}/ingestion-runs"), + MEMBER, + json!({ + "operation":"create","profileId":MEMBER, + "packageRevision":fixture.identity.package_digest, + "schemaFingerprint":fixture.identity.schema_fingerprint, + "inputDigest":prefix,"inputLength":source.len(),"itemCount":1,"chunkCount":1, + "chunkAlgorithmVersion":"greedy-canonical-http-batch-v1" + }), + None, + ) + .await + .success(StatusCode::CREATED); + let run_id = created.body["run"]["runId"].as_str().unwrap(); + ( + format!("{RECORDS}/ingestion-runs/{run_id}"), + json!({"chunkIndex":0,"items":items,"digest":digest,"prefixDigest":prefix}), + ) +} + +#[tokio::test] +async fn membership_refusals_match_the_claim_boundary_answer_at_each_step() { + let fixture = Fixture::create(Duration::from_secs(2)).await; + let member = fixture.member(); + let claimed = fixture.claimed(); + let unknown = Uuid::new_v4().to_string(); + let outside = fixture.seed(Some(&fixture.keys.foreign), "foreign").await; + let inactive = fixture.seed(Some(&fixture.keys.inactive), "inactive").await; + let removed = fixture + .seed(Some(&fixture.keys.tombstoned), "removed") + .await; + let null = fixture.seed(None, "null-key").await; + let visible = fixture.seed(Some(&fixture.keys.allowed), "visible").await; + let before = fixture.durable_state().await; + let outside_id = outside.record_id(); + let mut answers = std::collections::BTreeMap::new(); + for (posture, app) in [ + ("production", &fixture.app), + ("development", &fixture.development), + ] { + for id in [ + outside_id.clone(), + inactive.record_id(), + removed.record_id(), + null.record_id(), + ] { + for (method, body, status, code) in [ + ( + Method::GET, + Value::Null, + StatusCode::NOT_FOUND, + "resource.not-found", + ), + ( + Method::PATCH, + patch("label", "attempted-patch"), + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ( + Method::DELETE, + Value::Null, + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ] { + let etag = (method != Method::GET).then_some(outside.etag()); + let refusal = request( + app, + &member, + method.clone(), + &record(&id), + MEMBER, + body.clone(), + etag, + ) + .await; + let claim_refusal = request( + app, + &claimed, + method.clone(), + &record(&outside_id), + CLAIMED, + body.clone(), + etag, + ) + .await; + let missing = + request(app, &member, method, &record(&unknown), MEMBER, body, etag).await; + refusal.problem(status, code); + refusal.assert_same_problem(&claim_refusal); + refusal.assert_same_problem(&missing); + } + for (endpoint, status, code) in [ + ( + "move-facility/target-conditions", + StatusCode::NOT_FOUND, + "resource.not-found", + ), + ( + "close-facility", + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ] { + let refusal = action(app, &member, endpoint, MEMBER, json!({"facility":id})).await; + let claim_refusal = action( + app, + &claimed, + endpoint, + CLAIMED, + json!({"facility":outside_id}), + ) + .await; + let missing = + action(app, &member, endpoint, MEMBER, json!({"facility":unknown})).await; + refusal.problem(status, code); + refusal.assert_same_problem(&claim_refusal); + refusal.assert_same_problem(&missing); + } + let availability = + |facility: &str| json!({"targetInput":"facility","input":{"facility":facility}}); + let path = "/v1/actions/close-facility/availability"; + let refusal = request( + app, + &member, + Method::POST, + path, + "observer", + availability(&id), + None, + ) + .await; + let claim_refusal = request( + app, + &claimed, + Method::POST, + path, + "claim-observer", + availability(&outside_id), + None, + ) + .await; + let missing = request( + app, + &member, + Method::POST, + path, + "observer", + availability(&unknown), + None, + ) + .await; + refusal.problem(StatusCode::NOT_FOUND, "resource.not-found"); + missing.problem(StatusCode::NOT_FOUND, "resource.not-found"); + answers.insert(format!("{posture}-availability"), refusal.golden()); + answers.insert( + format!("{posture}-availability-claim"), + claim_refusal.golden(), + ); + answers.insert(format!("{posture}-availability-missing"), missing.golden()); + if posture == "development" { + assert_eq!(refusal.body["failedCheck"], "membership"); + assert_eq!(claim_refusal.body["failedCheck"], "row-boundary"); + refusal.assert_same_problem_except_check(&claim_refusal); + assert_eq!(missing.body["failedCheck"], "visibility"); + } else { + refusal.assert_same_problem(&missing); + refusal.assert_same_problem(&claim_refusal); + } + let undisclosed = request( + app, + &member, + Method::POST, + path, + "limited", + availability(&id), + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(undisclosed.body["availability"]["available"], Value::Null); + assert_eq!(undisclosed.body["availability"]["reason"], "not-disclosed"); + } + + let create = |id: Option<&str>| json!({"data":{"organization":id,"label":"denied-create"}}); + let claim_refusal = request( + app, + &claimed, + Method::POST, + RECORDS, + CLAIMED, + create(Some(&fixture.keys.foreign)), + None, + ) + .await; + let missing = request( + app, + &member, + Method::POST, + RECORDS, + MEMBER, + create(Some(&unknown)), + None, + ) + .await; + answers.insert(format!("{posture}-create-claim"), claim_refusal.golden()); + answers.insert(format!("{posture}-create-missing"), missing.golden()); + for body in [ + create(Some(&fixture.keys.foreign)), + create(Some(&fixture.keys.inactive)), + create(Some(&fixture.keys.tombstoned)), + create(None), + json!({"data":{"label":"missing-optional-key"}}), + ] { + let refusal = request(app, &member, Method::POST, RECORDS, MEMBER, body, None).await; + refusal.problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + if posture == "development" { + assert_eq!(refusal.body["failedCheck"], "membership"); + assert_eq!(claim_refusal.body["failedCheck"], "row-boundary"); + refusal.assert_same_problem_except_check(&claim_refusal); + } else { + refusal.assert_same_problem(&claim_refusal); + } + refusal.assert_same_problem(&missing); + } + + let denied = json!({"organization":fixture.keys.foreign,"label":"denied-action"}); + let observed = action(app, &member, "register-facility", MEMBER, denied.clone()).await; + let twin = action(app, &claimed, "register-facility", CLAIMED, denied).await; + observed.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + observed.assert_same_problem(&twin); + answers.insert( + format!("{posture}-observed-precondition"), + observed.golden(), + ); + + let guard = |id: &str| json!({"facility":id}); + let visible_id = visible.record_id(); + let disclosed = action( + app, + &member, + "close-facility", + "observer", + guard(&visible_id), + ) + .await; + disclosed.problem(StatusCode::PRECONDITION_FAILED, "action.guard-failed"); + assert_eq!(disclosed.body["guardReason"], "facility-not-open"); + let claim_disclosed = + action(app, &claimed, "close-facility", CLAIMED, guard(&visible_id)).await; + disclosed.assert_same_problem(&claim_disclosed); + let concealed = action( + app, + &member, + "close-facility", + "limited", + guard(&visible_id), + ) + .await; + let missing = action(app, &member, "close-facility", "limited", guard(&unknown)).await; + concealed.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + concealed.assert_same_problem(&missing); + answers.insert( + format!("{posture}-generic-precondition"), + concealed.golden(), + ); + } + let answers = serde_json::to_value(answers).unwrap(); + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/golden/membership_refusals.json" + ); + if std::env::var_os("REGISTRY_BREG_WRITE_GOLDEN").is_some() { + std::fs::write( + path, + format!("{}\n", serde_json::to_string_pretty(&answers).unwrap()), + ) + .unwrap(); + } else { + let recorded: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(answers, recorded); + } + assert_eq!(fixture.durable_state().await, before); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn availability_checks_the_action_boundary_before_conditional_field_disclosure() { + let mut project = membership_write_project::project(); + project["recordTypes"]["facility"] + .as_object_mut() + .unwrap() + .remove("constraints"); + project["recordTypes"]["facility"]["disclosureConditions"] = json!({ + "withhold-organization":{ + "when":[{"type":"field-equals","field":"label","value":"sealed"}], + "withhold":"fields","fields":["organization"], + "exemptProfiles":["member","claimed","steward","claim-observer"] + } + }); + let fixture = + Fixture::configured(Duration::from_secs(2), project, vec![], |service| service).await; + let member = fixture.member(); + let inside = fixture.seed(Some(&fixture.keys.allowed), "sealed").await; + let outside = fixture.seed(Some(&fixture.keys.foreign), "sealed").await; + let before = fixture.durable_state().await; + let path = "/v1/actions/close-facility/availability"; + let input = |id| json!({"targetInput":"facility","input":{"facility":id}}); + let refused = request( + &fixture.app, + &member, + Method::POST, + path, + "observer", + input(outside.record_id()), + None, + ) + .await; + let missing = request( + &fixture.app, + &member, + Method::POST, + path, + "observer", + input(Uuid::new_v4().to_string()), + None, + ) + .await; + refused.problem(StatusCode::NOT_FOUND, "resource.not-found"); + refused.assert_same_problem(&missing); + + // The same disclosure condition continues to withhold details on a target + // covered by the selected Action grant. + let observed = request( + &fixture.app, + &member, + Method::POST, + path, + "observer", + input(inside.record_id()), + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(observed.body["availability"]["reason"], "not-disclosed"); + assert_eq!( + observed.body["availability"]["observedRevision"], + Value::Null + ); + assert_eq!(fixture.durable_state().await, before); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn patch_validation_and_tests_precede_proposed_membership_denial() { + let mut project = membership_write_project::project(); + project["recordTypes"]["facility"]["fields"][0]["required"] = json!(true); + let fixture = + Fixture::configured(Duration::from_secs(2), project, vec![], |service| service).await; + let member = fixture.member(); + let claimed = fixture.claimed(); + let row = fixture + .seed(Some(&fixture.keys.allowed), "patch-precedence") + .await; + let path = record(&row.record_id()); + let before = fixture.durable_state().await; + let foreign = &fixture.keys.foreign; + let cases = [ + (patch("organization", "invalid-reference"), Some("/0/value")), + (patch("organization", Value::Null), Some("/0/value")), + ( + json!([{"op":"remove","path":"/data/organization"}]), + Some("/0/op"), + ), + ( + json!([ + {"op":"replace","path":"/data/organization","value":foreign}, + {"op":"replace","path":"/data/label","value":false} + ]), + Some("/1/value"), + ), + ( + json!([ + {"op":"test","path":"/data/label","value":"different-label"}, + {"op":"replace","path":"/data/organization","value":foreign} + ]), + None, + ), + ]; + for app in [&fixture.app, &fixture.development] { + let member_get = request(app, &member, Method::GET, &path, MEMBER, Value::Null, None) + .await + .success(StatusCode::OK); + let claim_get = request( + app, + &claimed, + Method::GET, + &path, + CLAIMED, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + for (body, field_path) in &cases { + let expected = request( + app, + &claimed, + Method::PATCH, + &path, + CLAIMED, + body.clone(), + Some(claim_get.etag()), + ) + .await; + let actual = request( + app, + &member, + Method::PATCH, + &path, + MEMBER, + body.clone(), + Some(member_get.etag()), + ) + .await; + if let Some(field_path) = field_path { + expected.problem(StatusCode::BAD_REQUEST, "request.invalid"); + assert_eq!(expected.body["fieldPath"], *field_path); + } else { + expected.problem(StatusCode::CONFLICT, "mutation.conflict"); + } + actual.assert_same_problem(&expected); + } + } + assert_eq!(fixture.durable_state().await, before); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_patch_moving_a_row_to_a_key_the_caller_is_not_a_member_of_is_refused() { + let fixture = Fixture::create(Duration::from_secs(2)).await; + let member = fixture.member(); + let claimed = fixture.claimed(); + let row = fixture.seed(Some(&fixture.keys.allowed), "movable").await; + let path = record(&row.record_id()); + let before = fixture.durable_state().await; + let mut results = Vec::new(); + let unknown = Uuid::new_v4().to_string(); + for (profile, token, key) in [ + (MEMBER, &member, &fixture.keys.foreign), + (CLAIMED, &claimed, &fixture.keys.foreign), + (MEMBER, &member, &unknown), + ] { + let get = request( + &fixture.app, + token, + Method::GET, + &path, + profile, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + results.push( + request( + &fixture.app, + token, + Method::PATCH, + &path, + profile, + patch("organization", key.as_str()), + Some(get.etag()), + ) + .await, + ); + } + results[0].problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + results[0].assert_same_problem(&results[1]); + results[0].assert_same_problem(&results[2]); + let condition = action( + &fixture.app, + &member, + "move-facility/target-conditions", + MEMBER, + json!({"facility":row.record_id()}), + ) + .await + .success(StatusCode::OK); + for key in [&fixture.keys.foreign, &unknown] { + request( + &fixture.app, + &member, + Method::POST, + "/v1/actions/move-facility", + MEMBER, + json!({ + "input":{"organization":key,"facility":row.record_id()}, + "preconditions":condition.body["preconditions"] + }), + None, + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + } + let get = request( + &fixture.app, + &member, + Method::GET, + &path, + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + let removed_key = request( + &fixture.app, + &member, + Method::PATCH, + &path, + MEMBER, + json!([{"op":"remove","path":"/data/organization"}]), + Some(get.etag()), + ) + .await; + removed_key.assert_same_problem(&results[0]); + assert_eq!(fixture.durable_state().await, before); + request( + &fixture.app, + &member, + Method::PATCH, + &path, + MEMBER, + patch("label", "after-condition"), + Some(get.etag()), + ) + .await + .success(StatusCode::OK); + let after_edit = fixture.durable_state().await; + let stale = request( + &fixture.app, + &member, + Method::PATCH, + &path, + MEMBER, + patch("organization", fixture.keys.foreign.as_str()), + Some(get.etag()), + ) + .await; + stale.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, after_edit); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_membership_refusal_never_answers_service_unavailable() { + let fixture = Fixture::create(Duration::from_secs(2)).await; + let member = fixture.member(); + let row = fixture + .seed(Some(&fixture.keys.allowed), "existing-label") + .await; + let outside = fixture + .seed(Some(&fixture.keys.foreign), "outside-label") + .await; + let before = fixture.durable_state().await; + let refused_create = json!({"operation":"create","data":{"organization":fixture.keys.foreign,"label":"existing-label"}}); + let missing_patch = json!({ + "operation":"patch","recordIdentifier":Uuid::new_v4(),"ifMatch":row.etag(), + "patch":patch("label", "missing") + }); + for (items, status, code) in [ + ( + json!([refused_create, missing_patch]), + StatusCode::FORBIDDEN, + "write.outside-boundary", + ), + ( + json!([missing_patch, refused_create]), + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ( + json!([ + {"operation":"create","data":{"organization":fixture.keys.allowed,"label":"rolled-back"}}, + refused_create + ]), + StatusCode::FORBIDDEN, + "write.outside-boundary", + ), + ] { + request( + &fixture.app, + &member, + Method::POST, + &format!("{RECORDS}:batch"), + MEMBER, + json!({"items":items}), + None, + ) + .await + .problem(status, code); + assert_eq!(fixture.durable_state().await, before); + } + request( + &fixture.app, + &member, + Method::POST, + RECORDS, + MEMBER, + json!({"data":refused_create["data"]}), + None, + ) + .await + .problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + + for input in [ + json!({"organization":fixture.keys.foreign,"label":"existing-label"}), + json!({"organization":fixture.keys.allowed,"related":outside.record_id(),"label":"existing-label"}), + ] { + action(&fixture.app, &member, "register-facility", MEMBER, input) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + } + action( + &fixture.app, + &member, + "register-pair", + MEMBER, + json!({"first":fixture.keys.allowed,"second":fixture.keys.foreign}), + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, before); + + let (run_path, chunk) = + announce_ingestion(&fixture, &member, &fixture.keys.foreign, "resumable").await; + let chunk_path = format!("{run_path}/chunks"); + request( + &fixture.app, + &member, + Method::POST, + &chunk_path, + MEMBER, + chunk.clone(), + None, + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, before); + let open = request( + &fixture.app, + &member, + Method::GET, + &run_path, + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(open.body["run"]["status"], "open"); + assert_eq!(open.body["run"]["nextChunkIndex"], 0); + request( + &fixture.app, + &fixture.steward(), + Method::POST, + "/v1/records/memberships", + MEMBERSHIP_WRITER, + json!({"data":{"organization":fixture.keys.foreign,"principal":MEMBER,"active":true}}), + None, + ) + .await + .success(StatusCode::CREATED); + let resumed = request( + &fixture.app, + &member, + Method::POST, + &chunk_path, + MEMBER, + chunk, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(resumed.body["run"]["status"], "complete"); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_fresh_principal_with_no_membership_lists_empty_and_cannot_write() { + let fixture = Fixture::create(Duration::from_secs(2)).await; + let guest = mint(&fixture.idp, "fresh", "", &[]); + let row = fixture.seed(Some(&fixture.keys.allowed), "open").await; + let path = record(&row.record_id()); + let listed = request( + &fixture.app, + &guest, + Method::GET, + RECORDS, + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(listed.body["items"], json!([])); + request( + &fixture.app, + &guest, + Method::GET, + &path, + MEMBER, + Value::Null, + None, + ) + .await + .problem(StatusCode::NOT_FOUND, "resource.not-found"); + request( + &fixture.app, + &guest, + Method::POST, + RECORDS, + MEMBER, + json!({"data":{"organization":fixture.keys.allowed,"label":"fresh"}}), + None, + ) + .await + .problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + for (method, body) in [ + (Method::PATCH, patch("label", "fresh")), + (Method::DELETE, Value::Null), + ] { + request( + &fixture.app, + &guest, + method, + &path, + MEMBER, + body, + Some(row.etag()), + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + } + action( + &fixture.app, + &guest, + "close-facility", + MEMBER, + json!({"facility":row.record_id()}), + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + fixture.database.cleanup().await; +} + +async fn wait_for_blocker(database: &TestDatabase, blocker: i32) -> i32 { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(row) = database.admin.query_opt( + "SELECT pid FROM pg_catalog.pg_stat_activity + WHERE datname = current_database() AND $1 = ANY(pg_catalog.pg_blocking_pids(pid))", + &[&blocker], + ).await.unwrap() { + return row.get(0); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }).await.expect("the expected transaction reached its lock wait") +} + +fn table(fixture: &Fixture, entity: &str) -> String { + format!( + "registry_data.\"{}\"", + fixture.registry.entities()[entity].physical_table + ) +} + +async fn hold_row(transaction: &tokio_postgres::Transaction<'_>, table: &str, id: &str) -> i32 { + transaction + .query_one( + &format!("SELECT pg_backend_pid() FROM {table} WHERE record_id=$1 FOR UPDATE"), + &[&Uuid::parse_str(id).unwrap()], + ) + .await + .unwrap() + .get(0) +} + +fn spawn_create(fixture: &Fixture, key: &str, label: &str) -> tokio::task::JoinHandle { + let app = fixture.app.clone(); + let token = fixture.member(); + let body = json!({"data":{"organization":key,"label":label}}); + tokio::spawn( + async move { request(&app, &token, Method::POST, RECORDS, MEMBER, body, None).await }, + ) +} + +#[tokio::test] +async fn a_write_holding_the_lock_makes_the_removal_wait() { + assert_write_makes_removal_wait(false).await; +} + +#[tokio::test] +async fn record_write_first_makes_the_removal_wait() { + assert_write_makes_removal_wait(true).await; +} + +async fn assert_write_makes_removal_wait(use_steward_api: bool) { + let lock_timeout = Duration::from_secs(10); + let fixture = if use_steward_api { + // An ordinary steward Patch uses the PostgreSQL role default. Use + // READ COMMITTED for both HTTP requests so they can commit in order. + Fixture::configured_with_isolation( + lock_timeout, + membership_write_project::project(), + Vec::new(), + "read committed", + |service| service, + ) + .await + } else { + Fixture::create(lock_timeout).await + }; + let row = fixture + .seed(Some(&fixture.keys.allowed), "before-write") + .await; + let path = record(&row.record_id()); + let member = fixture.member(); + let member_row = request( + &fixture.app, + &member, + Method::GET, + &path, + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + let (mut admin, admin_connection) = fixture.database.connect_admin().await; + let blocker = admin.transaction().await.unwrap(); + let blocker_pid = hold_row(&blocker, &table(&fixture, "facility"), &row.record_id()).await; + let app = fixture.app.clone(); + let writer = tokio::spawn(async move { + request( + &app, + &member, + Method::PATCH, + &path, + MEMBER, + patch("label", "committed-before-removal"), + Some(member_row.etag()), + ) + .await + }); + let writer_pid = wait_for_blocker(&fixture.database, blocker_pid).await; + let removal = if use_steward_api { + let path = format!("/v1/records/memberships/{}", fixture.keys.membership); + let app = fixture.app.clone(); + let steward = fixture.steward(); + let current = request( + &app, + &steward, + Method::GET, + &path, + MEMBERSHIP_WRITER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + tokio::spawn(async move { + let revoked = request( + &app, + &steward, + Method::PATCH, + &path, + MEMBERSHIP_WRITER, + patch("active", false), + Some(current.etag()), + ) + .await + .success(StatusCode::OK); + assert_eq!(revoked.body["data"]["domainData"]["active"], false); + }) + } else { + // A separate READ COMMITTED transaction isolates the membership wait + // from the ordinary mutation journal's revision clock. The bounded + // writer still uses the runtime role's REPEATABLE READ default. + let (remover, removal_connection) = fixture.database.connect_admin().await; + let membership = &fixture.registry.entities()["membership"]; + let sql = format!( + "UPDATE {} SET \"{}\"=false WHERE record_id=$1", + table(&fixture, "membership"), + membership.fields["active"].physical_name, + ); + let membership_id = Uuid::parse_str(&fixture.keys.membership).unwrap(); + tokio::spawn(async move { + assert_eq!(remover.execute(&sql, &[&membership_id]).await.unwrap(), 1); + removal_connection.abort(); + }) + }; + wait_for_blocker(&fixture.database, writer_pid).await; + blocker.commit().await.unwrap(); + writer.await.unwrap().success(StatusCode::OK); + removal.await.unwrap(); + admin_connection.abort(); + request( + &fixture.app, + &fixture.member(), + Method::GET, + &record(&row.record_id()), + MEMBER, + Value::Null, + None, + ) + .await + .problem(StatusCode::NOT_FOUND, "resource.not-found"); + let committed = request( + &fixture.app, + &fixture.steward(), + Method::GET, + &record(&row.record_id()), + MEMBERSHIP_WRITER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!( + committed.body["data"]["domainData"]["label"], + "committed-before-removal" + ); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn record_removal_first_refuses_the_write() { + let fixture = Fixture::create(Duration::from_secs(10)).await; + let before = fixture.durable_state().await; + let app = fixture.app.clone(); + let member = fixture.member(); + let body = + json!({"data":{"organization":fixture.keys.allowed,"label":"revoked-before-create"}}); + after_steward_removal(&fixture, async move { + request(&app, &member, Method::POST, RECORDS, MEMBER, body, None).await + }) + .await + .problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + // The steward records its own removal. The refused writer creates no facility. + assert_eq!(fixture.durable_state().await[0], before[0]); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_lock_wait_past_lock_timeout_answers_service_unavailable() { + let fixture = Fixture::create(Duration::from_millis(250)).await; + let (mut admin, connection) = fixture.database.connect_admin().await; + let blocker = admin.transaction().await.unwrap(); + hold_row( + &blocker, + &table(&fixture, "membership"), + &fixture.keys.membership, + ) + .await; + let before = fixture.durable_state().await; + spawn_create(&fixture, &fixture.keys.allowed, "bounded-lock-wait") + .await + .unwrap() + .problem(StatusCode::SERVICE_UNAVAILABLE, "service.unavailable"); + assert_eq!(fixture.durable_state().await, before); + blocker.rollback().await.unwrap(); + spawn_create(&fixture, &fixture.keys.allowed, "bounded-lock-wait") + .await + .unwrap() + .success(StatusCode::CREATED); + connection.abort(); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn an_action_cannot_invalidate_its_own_membership_proof() { + let fixture = Fixture::create(Duration::from_secs(2)).await; + let maintainer = mint(&fixture.idp, MEMBER, "records:retire", &[]); + let before = fixture.durable_state().await; + for action_id in [ + "register-and-retire-membership", + "retire-membership-and-register", + ] { + action( + &fixture.app, &maintainer, action_id, "maintainer", + json!({"organization":fixture.keys.allowed,"membership":fixture.keys.membership,"label":"rolled-back-action"}), + ).await.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, before); + } + + action( + &fixture.app, + &maintainer, + "register-in-created-organization", + "maintainer", + json!({"label":"reserved-reference"}), + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, before); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn package_admission_precedes_sorted_membership_locks() { + let fixture = Fixture::create(Duration::from_secs(10)).await; + let (mut admin, connection) = fixture.database.connect_admin().await; + let package = admin.transaction().await.unwrap(); + let package_key = RegistryLockKey::derive(PACKAGE).unwrap().get(); + package + .query_one("SELECT pg_advisory_xact_lock($1)", &[&package_key]) + .await + .unwrap(); + let package_pid = package + .query_one("SELECT pg_backend_pid()", &[]) + .await + .unwrap() + .get(0); + + let membership_table = table(&fixture, "membership"); + let key_column = + &fixture.registry.entities()["membership"].fields["organization"].physical_name; + let key_for = |key: &str| Uuid::parse_str(key).unwrap(); + let mut keys = [ + key_for(&fixture.keys.allowed), + key_for(&fixture.keys.second), + ]; + keys.sort(); + let (mut last, last_connection) = fixture.database.connect_admin().await; + let last = last.transaction().await.unwrap(); + let last_pid = last.query_one( + &format!("SELECT pg_backend_pid() FROM {membership_table} WHERE \"{key_column}\"=$1 FOR UPDATE"), + &[&keys[1]], + ).await.unwrap().get(0); + + let app = fixture.app.clone(); + let member = fixture.member(); + let batch = + tokio::spawn(async move { + request( + &app, &member, Method::POST, &format!("{RECORDS}:batch"), MEMBER, + json!({"items":[ + {"operation":"create","data":{"organization":keys[1],"label":"lock-order-last"}}, + {"operation":"create","data":{"organization":keys[0],"label":"lock-order-first"}} + ]}), None, + ).await + }); + let writer_pid = wait_for_blocker(&fixture.database, package_pid).await; + let nowait = + format!("SELECT 1 FROM {membership_table} WHERE \"{key_column}\"=$1 FOR UPDATE NOWAIT"); + fixture + .database + .admin + .query_one(&nowait, &[&keys[0]]) + .await + .unwrap(); + package.commit().await.unwrap(); + assert_eq!( + wait_for_blocker(&fixture.database, last_pid).await, + writer_pid + ); + let error = fixture + .database + .admin + .query_one(&nowait, &[&keys[0]]) + .await + .unwrap_err(); + assert_eq!( + error.code(), + Some(&tokio_postgres::error::SqlState::LOCK_NOT_AVAILABLE) + ); + last.commit().await.unwrap(); + batch.await.unwrap().success(StatusCode::OK); + last_connection.abort(); + connection.abort(); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn action_rechecks_drifted_keys_for_current_revision_and_unconditioned_links() { + let fixture = Fixture::create(Duration::from_secs(10)).await; + for is_link in [false, true] { + let row = fixture.seed(Some(&fixture.keys.allowed), "open").await; + let (mut target_owner, target_connection) = fixture.database.connect_admin().await; + let move_key = target_owner.transaction().await.unwrap(); + let facility = &fixture.registry.entities()["facility"]; + let organization = &facility.fields["organization"].physical_name; + let target_pid = move_key + .query_one( + &format!( + "UPDATE {} SET \"{organization}\"=$1, record_revision=record_revision+1 + WHERE record_id=$2 RETURNING pg_backend_pid()", + table(&fixture, "facility") + ), + &[ + &Uuid::parse_str(&fixture.keys.second).unwrap(), + &Uuid::parse_str(&row.record_id()).unwrap(), + ], + ) + .await + .unwrap() + .get(0); + + let membership = &fixture.registry.entities()["membership"]; + let key = &membership.fields["organization"].physical_name; + let active = &membership.fields["active"].physical_name; + let (mut membership_owner, membership_connection) = fixture.database.connect_admin().await; + let disabling_destination = membership_owner.transaction().await.unwrap(); + let destination_pid = disabling_destination + .query_one( + &format!( + "UPDATE {} SET \"{active}\"=false WHERE \"{key}\"=$1 RETURNING pg_backend_pid()", + table(&fixture, "membership") + ), + &[&Uuid::parse_str(&fixture.keys.second).unwrap()], + ) + .await + .unwrap() + .get(0); + let app = fixture.app.clone(); + let member = fixture.member(); + let source = fixture.keys.allowed.clone(); + let target = row.record_id(); + let requested = tokio::spawn(async move { + if is_link { + action( + &app, + &member, + "register-facility", + MEMBER, + json!({"organization":source,"related":target,"label":"linked-after-move"}), + ) + .await + } else { + action( + &app, + &member, + "close-facility", + MEMBER, + json!({"facility":target}), + ) + .await + } + }); + let writer_pid = wait_for_blocker(&fixture.database, target_pid).await; + move_key.commit().await.unwrap(); + assert_eq!( + wait_for_blocker(&fixture.database, destination_pid).await, + writer_pid + ); + disabling_destination.commit().await.unwrap(); + requested + .await + .unwrap() + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + let steward = fixture.steward(); + let path = record(&row.record_id()); + let get = request( + &fixture.app, + &steward, + Method::GET, + &path, + MEMBERSHIP_WRITER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(get.body["data"]["domainData"]["label"], "open"); + assert_eq!(get.body["data"]["revisionIdentifier"], "2"); + fixture + .database + .admin + .execute( + &format!( + "UPDATE {} SET \"{active}\"=true WHERE \"{key}\"=$1", + table(&fixture, "membership") + ), + &[&Uuid::parse_str(&fixture.keys.second).unwrap()], + ) + .await + .unwrap(); + request( + &fixture.app, + &steward, + Method::PATCH, + &path, + MEMBERSHIP_WRITER, + patch("label", format!("moved-{is_link}")), + Some(get.etag()), + ) + .await + .success(StatusCode::OK); + target_connection.abort(); + membership_connection.abort(); + } + fixture.database.cleanup().await; +} + +fn with_evidence() -> (Value, Vec) { + let mut project = membership_write_project::project(); + project["evidenceProviders"] = json!({ + "farmer-registry":{ + "contracts":"evidence/farmer-contracts.json", + "subjectResolution":"trusted-provider-exact-selector" + } + }); + let original = project["actions"]["register-facility"].clone(); + let grant = project["accessProfiles"]["member"]["permissions"]["actions"][0].clone(); + for id in [ + "register-with-commit-evidence", + "register-with-function-evidence", + ] { + let mut action = original.clone(); + action["inputs"] = json!([ + original["inputs"][0].clone(), + original["inputs"][2].clone(), + {"id":"farmer-number","type":"string","minimumLength":3,"maximumLength":77, + "required":true,"classification":"internal"} + ]); + let mut permission = grant.clone(); + permission["action"] = json!(id); + if id == "register-with-commit-evidence" { + action["plan"]["effects"][0]["set"] + .as_object_mut() + .unwrap() + .remove("related"); + action["commitGuards"] = json!({"evidence":[{ + "id":"farmer-status","provider":"farmer-registry", + "requirement":"urn:example:farmer:status-v1", + "subjects":{"farmer":{"profile":"farmer-number-v1", + "selectors":{"farmer-number":{"type":"input","input":"farmer-number"}}}}, + "requires":[{"output":"active","equals":true}], "maximumObservationAgeSeconds":60 + }]}); + } else { + action["plan"] = json!({"type":"function","function":"register-with-evidence", + "inputs":["organization","label","farmer-number"], + "writes":[{"id":"register","target":{"recordType":"facility"},"operation":"create", + "fields":["organization","label"]}] + }); + action["evidence"] = json!([{ + "id":"farmer-status","provider":"farmer-registry", + "requirement":"urn:example:farmer:status-v1", + "subjects":{"farmer":{"profile":"farmer-number-v1"}}, + "outputs":["active"],"maximumObservationAgeSeconds":60 + }]); + } + project["actions"][id] = action; + project["accessProfiles"]["member"]["permissions"]["actions"] + .as_array_mut() + .unwrap() + .push(permission); + } + project["functions"] = json!({ + "register-with-evidence":{ + "runtime":"rhai","source":"scripts/register-with-evidence.rhai", + "entrypoint":"plan","abi":"registry.action-plan/v1","capabilities":["evidence"] + } + }); + let assets = [ + ( + "evidence/farmer-contracts.json", + include_bytes!("../../../../products/breg/acceptance/farmer-landholding-evidence/evidence/farmer-contracts.json").as_slice(), + ), + ( + "scripts/register-with-evidence.rhai", + br#"fn plan(ctx) { + let subjects = #{farmer: #{"farmer-number": ctx.inputs["farmer-number"]}}; + evidence::resolve("farmer-status", subjects); + #{effects: [#{id:"register", set: #{ + organization: #{fromInput:"organization"}, label: ctx.inputs["label"] + }}]} + }"#.as_slice(), + ), + ].into_iter().map(|(path, bytes)| ModuleAssetSource { + module: None, path: path.to_owned(), bytes: bytes.to_vec(), + }).collect(); + (project, assets) +} + +#[tokio::test] +async fn evidence_admission_refuses_unsatisfiable_membership_and_replays_without_acquisition() { + use registry_breg::action_evidence::ActionEvidenceEvaluator; + use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; + + let key = generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap(); + let provider = super::action_evidence_provider::EvidenceProvider::start_with_key(key).await; + let (project, assets) = with_evidence(); + let fixture = Fixture::configured(Duration::from_secs(2), project, assets, |service| { + service.with_evidence_evaluator(Arc::new(ActionEvidenceEvaluator::new(provider.client()))) + }) + .await; + let member = fixture.member(); + let before = fixture.durable_state().await; + for action_id in [ + "register-with-commit-evidence", + "register-with-function-evidence", + ] { + let input = |organization: &str| { + json!({ + "organization":organization,"label":action_id,"farmerNumber":"DEMO-1" + }) + }; + let calls = provider.calls(); + action( + &fixture.app, + &member, + action_id, + MEMBER, + input(&fixture.keys.foreign), + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(provider.calls(), calls); + if calls == 0 { + assert_eq!(fixture.durable_state().await, before); + } + let body = json!({"input":input(&fixture.keys.allowed)}); + let path = format!("/v1/actions/{action_id}"); + let first = request_with_key( + &fixture.app, + &member, + Method::POST, + &path, + MEMBER, + body.clone(), + None, + action_id, + ) + .await + .success(StatusCode::OK); + assert_eq!(provider.calls(), calls + 1); + let replay = request_with_key( + &fixture.app, + &member, + Method::POST, + &path, + MEMBER, + body, + None, + action_id, + ) + .await + .success(StatusCode::OK); + assert_eq!(first.bytes, replay.bytes); + assert_eq!(provider.calls(), calls + 1); + } + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn evidence_admission_requires_a_permitted_value_for_the_only_patch_field() { + use registry_breg::action_evidence::ActionEvidenceEvaluator; + use registry_platform_crypto::{generate_private_jwk, GeneratedKeyAlgorithm}; + + let (mut project, mut assets) = with_evidence(); + let action_id = "move-with-evidence"; + let mut action_source = project["actions"]["move-facility"].clone(); + action_source["inputs"] + .as_array_mut() + .unwrap() + .push(project["actions"]["register-with-function-evidence"]["inputs"][2].clone()); + action_source["evidence"] = + project["actions"]["register-with-function-evidence"]["evidence"].clone(); + action_source["plan"] = json!({ + "type":"function","function":action_id,"inputs":["facility","organization","farmer-number"], + "writes":[{"id":"move","target":{"fromInput":"facility"},"operation":"patch", + "fields":["organization"]}] + }); + project["actions"][action_id] = action_source; + let member_actions = project["accessProfiles"]["member"]["permissions"]["actions"] + .as_array_mut() + .unwrap(); + let mut grant = member_actions + .iter() + .find(|grant| grant["action"] == "move-facility") + .unwrap() + .clone(); + grant["action"] = json!(action_id); + member_actions.push(grant); + let script = "scripts/move-with-evidence.rhai"; + project["functions"][action_id] = json!({ + "runtime":"rhai","source":script,"entrypoint":"plan", + "abi":"registry.action-plan/v1","capabilities":["evidence"] + }); + assets.push(ModuleAssetSource { + module: None, + path: script.to_owned(), + bytes: br#"fn plan(ctx) { + let subjects = #{farmer: #{"farmer-number": ctx.inputs["farmer-number"]}}; + evidence::resolve("farmer-status", subjects); + #{effects: [#{id:"move", set: #{organization: #{fromInput:"organization"}}}]} + }"# + .to_vec(), + }); + + let key = generate_private_jwk(GeneratedKeyAlgorithm::Es256).unwrap(); + let provider = super::action_evidence_provider::EvidenceProvider::start_with_key(key).await; + let fixture = Fixture::configured(Duration::from_secs(2), project, assets, |service| { + service.with_evidence_evaluator(Arc::new(ActionEvidenceEvaluator::new(provider.client()))) + }) + .await; + let member = fixture.member(); + let row = fixture + .seed(Some(&fixture.keys.allowed), "evidence-move") + .await; + let id = row.record_id(); + let conditions = action( + &fixture.app, + &member, + "move-with-evidence/target-conditions", + MEMBER, + json!({"facility":id}), + ) + .await + .success(StatusCode::OK); + let body = |organization| { + json!({ + "input":{"facility":id,"organization":organization,"farmerNumber":"DEMO-1"}, + "preconditions":conditions.body["preconditions"] + }) + }; + let path = "/v1/actions/move-with-evidence"; + let before = fixture.durable_state().await; + request( + &fixture.app, + &member, + Method::POST, + path, + MEMBER, + body(&fixture.keys.foreign), + None, + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(provider.calls(), 0); + assert_eq!(fixture.durable_state().await, before); + request( + &fixture.app, + &member, + Method::POST, + path, + MEMBER, + body(&fixture.keys.second), + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(provider.calls(), 1); + fixture.database.cleanup().await; +} + +const MEMBERSHIP_FILE: &[u8] = b"fixture attachment"; +const FILE_ACTION: &str = "/v1/actions/register-facility"; + +fn membership_file_project(with_proposal: bool) -> Value { + let mut project = if with_proposal { + membership_write_project::proposal_project() + } else { + membership_write_project::project() + }; + let slot = json!({ + "id":"support","maximumBytes":4096,"contentTypes":["text/plain"], + "classification":"restricted" + }); + let mut record_slot = slot.clone(); + record_slot["writeOnce"] = json!(true); + project["recordTypes"]["facility"]["attachments"] = json!([record_slot]); + let promotion = json!({"support":{"fromAttachment":"support"}}); + project["actions"]["register-facility"]["plan"]["effects"][0]["attachments"] = + promotion.clone(); + if with_proposal { + // A shared sequence would serialize the creates before the file work. + project["recordTypes"]["facility"]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| field["id"] != "number"); + for profile in project["accessProfiles"] + .as_object_mut() + .unwrap() + .values_mut() + { + if let Some(grants) = profile["permissions"]["records"].as_array_mut() { + for grant in grants + .iter_mut() + .filter(|grant| grant["recordType"] == "facility") + { + if let Some(fields) = grant["readableFields"].as_array_mut() { + fields.retain(|field| field != "number"); + } + } + } + } + let mut proposal_slot = slot; + proposal_slot["required"] = json!(true); + project["actions"]["propose-facility"]["execution"]["proposal"]["attachments"] = + json!([proposal_slot]); + project["actions"]["propose-facility"]["plan"]["effects"][0]["attachments"] = promotion; + for profile in ["member", "claimed"] { + let grants = project["accessProfiles"][profile]["permissions"]["proposals"] + .as_array_mut() + .unwrap(); + let grant = grants + .iter_mut() + .find(|grant| grant["action"] == "propose-facility") + .unwrap(); + grant["readableAttachments"] = json!(["support"]); + grant["writableAttachments"] = json!(["support"]); + } + } + project +} + +#[derive(Default)] +struct MembershipPutObserver { + entered: tokio::sync::Notify, + resume: tokio::sync::Notify, +} + +struct MembershipS3 { + storage: registry_breg::attachment_storage::AttachmentStorage, + requests: Arc, + puts: Arc, + server: tokio::task::JoinHandle<()>, +} + +impl Drop for MembershipS3 { + fn drop(&mut self) { + self.server.abort(); + } +} + +async fn membership_s3(put_observer: Option>) -> MembershipS3 { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let requests = Arc::new(AtomicUsize::new(0)); + let calls = requests.clone(); + let puts = Arc::new(AtomicUsize::new(0)); + let put_count = puts.clone(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let bytes = Arc::new(tokio::sync::Mutex::new(Vec::new())); + let app = axum::Router::new().fallback(move | + method: Method, uri: axum::extract::OriginalUri, body: axum::body::Bytes, + | { + let calls = calls.clone(); + let bytes = bytes.clone(); + let put_count = put_count.clone(); + let put_observer = put_observer.clone(); + async move { + calls.fetch_add(1, Ordering::SeqCst); + match method { + Method::GET if uri.query().is_some() => ( + StatusCode::OK, + b"".to_vec(), + ), + Method::PUT => { + put_count.fetch_add(1, Ordering::SeqCst); + if let Some(observer) = put_observer { + observer.entered.notify_one(); + observer.resume.notified().await; + } + *bytes.lock().await = body.to_vec(); + (StatusCode::OK, Vec::new()) + } + Method::GET => (StatusCode::OK, bytes.lock().await.clone()), + _ => (StatusCode::METHOD_NOT_ALLOWED, Vec::new()), + } + } + }); + axum::serve(listener, app).await.unwrap(); + }); + let directory = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); + for name in ["access", "key"] { + write_test_secret( + &directory.path().join(name), + Uuid::new_v4().simple().to_string().as_bytes(), + ); + } + let config = runtime_fixture(directory.path()); + let config = format!( + "{config}\nattachmentStorage:\n type: s3\n url: {endpoint}\n bucket: member-files\n region: us-east-1\n accessKeyIdRef: secret:file/access\n secretAccessKeyRef: secret:file/key\n" + ); + let config = registry_breg::runtime_config::parse_runtime_config( + &config, + DeclaredPosture { + posture: Posture::Production, + source: PostureSource::Flag, + }, + ) + .unwrap(); + let storage = config.activate_attachment_storage(PACKAGE).await.unwrap(); + MembershipS3 { + storage, + requests, + puts, + server, + } +} + +fn membership_file_body(organization: &str, label: &str) -> Value { + use base64::{engine::general_purpose::STANDARD, Engine as _}; + + json!({ + "input":{"organization":organization,"label":label}, + "attachments":{"support":{"contentType":"text/plain", + "sha256":hex::encode(Sha256::digest(MEMBERSHIP_FILE)), + "content":STANDARD.encode(MEMBERSHIP_FILE) + }} + }) +} + +#[tokio::test] +async fn a_membership_refusal_leaves_s3_staging_unchanged() { + use std::sync::atomic::Ordering; + + let s3 = membership_s3(None).await; + let fixture = Fixture::configured( + Duration::from_secs(2), + membership_file_project(false), + vec![], + |service| service.with_attachment_storage(s3.storage.clone()), + ) + .await; + + let durable_before = fixture.durable_state().await; + let calls_before = s3.requests.load(Ordering::SeqCst); + request( + &fixture.app, + &fixture.member(), + Method::POST, + FILE_ACTION, + MEMBER, + membership_file_body(&fixture.keys.foreign, "attachment-refusal"), + None, + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(s3.requests.load(Ordering::SeqCst), calls_before); + assert_eq!(fixture.durable_state().await, durable_before); + let row = fixture + .database + .admin + .query_one( + "SELECT (SELECT count(*) FROM registry_internal.registry_attachment_blobs), + (SELECT count(*) FROM registry_internal.registry_record_attachments)", + &[], + ) + .await + .unwrap(); + assert_eq!((row.get::<_, i64>(0), row.get::<_, i64>(1)), (0, 0)); + let valid_body = membership_file_body(&fixture.keys.allowed, "attachment-accepted"); + let token = fixture.member(); + let endpoint = FILE_ACTION; + let first = request_with_key( + &fixture.app, + &token, + Method::POST, + endpoint, + MEMBER, + valid_body.clone(), + None, + "attachment-accepted", + ) + .await + .success(StatusCode::OK); + let calls_after_write = s3.requests.load(Ordering::SeqCst); + assert!(calls_after_write > calls_before); + let replay = request_with_key( + &fixture.app, + &token, + Method::POST, + endpoint, + MEMBER, + valid_body, + None, + "attachment-accepted", + ) + .await + .success(StatusCode::OK); + assert_eq!(first.bytes, replay.bytes); + assert_eq!(s3.requests.load(Ordering::SeqCst), calls_after_write); + let state: String = fixture + .database + .admin + .query_one( + "SELECT state FROM registry_internal.registry_attachment_blobs", + &[], + ) + .await + .unwrap() + .get(0); + assert_eq!(state, "live"); + fixture.database.cleanup().await; +} + +async fn membership_file_action(fixture: &Fixture, token: &str, body: &Value, key: &str) -> Reply { + request_with_key( + &fixture.app, + token, + Method::POST, + FILE_ACTION, + MEMBER, + body.clone(), + None, + key, + ) + .await +} + +async fn file_commit_state(fixture: &Fixture) -> (i64, i64, i64, i64) { + let row = fixture + .database + .admin + .query_one( + "SELECT latest_position, + (SELECT count(*) FROM registry_internal.registry_record_attachments), + (SELECT count(*) FROM registry_internal.registry_idempotency), + (SELECT count(*) FROM registry_internal.registry_proposal_applications) + FROM registry_internal.registry_commit_head", + &[], + ) + .await + .unwrap(); + (row.get(0), row.get(1), row.get(2), row.get(3)) +} + +async fn assert_file_commit_members( + fixture: &Fixture, + previous_position: i64, + expected: i64, +) -> Vec { + let hash = hex::encode(Sha256::digest(MEMBERSHIP_FILE)); + let rows = fixture + .database + .admin + .query( + "SELECT m.record_id::text, m.record_revision, m.commit_position, a.sha256, b.state + FROM registry_internal.registry_revision_commit_members m + JOIN registry_internal.registry_record_attachments a + ON (a.entity_id, a.record_id, a.attached_revision) = + (m.entity_id, m.record_id, m.record_revision) + JOIN registry_internal.registry_attachment_blobs b ON b.sha256 = a.sha256 + WHERE m.entity_id = 'facility' AND a.slot_id = 'support' AND a.erased_at IS NULL + AND m.commit_position > $1 + ORDER BY m.commit_position", + &[&previous_position], + ) + .await + .unwrap(); + assert_eq!(rows.len() as i64, expected); + rows.iter() + .enumerate() + .map(|(index, row)| { + assert_eq!(row.get::<_, i64>(1), 1); + assert_eq!(row.get::<_, i64>(2), previous_position + index as i64 + 1); + assert_eq!(row.get::<_, String>(3), hash); + assert_eq!(row.get::<_, String>(4), "live"); + row.get(0) + }) + .collect() +} + +#[tokio::test] +async fn membership_file_action_commits_and_replays_with_one_ordinary_connection() { + use std::sync::atomic::Ordering; + + let observer = Arc::new(MembershipPutObserver::default()); + let s3 = membership_s3(Some(observer.clone())).await; + let fixture = Fixture::configured_with_pool( + Duration::from_secs(2), + membership_file_project(false), + vec![], + "repeatable read", + 1, + |service| service.with_attachment_storage(s3.storage.clone()), + ) + .await; + let token = fixture.member(); + let before = file_commit_state(&fixture).await; + let durable_before = fixture.durable_state().await; + let body = membership_file_body(&fixture.keys.allowed, "one-connection"); + let key = "one-connection-file"; + let (reply, ()) = tokio::time::timeout(Duration::from_secs(12), async { + tokio::join!( + membership_file_action(&fixture, &token, &body, key), + async { + observer.entered.notified().await; + let state: String = fixture + .database + .admin + .query_one( + "SELECT state FROM registry_internal.registry_attachment_blobs", + &[], + ) + .await + .unwrap() + .get(0); + assert_eq!(state, "staged"); + assert_eq!(file_commit_state(&fixture).await, before); + assert_eq!(fixture.durable_state().await, durable_before); + observer.resume.notify_one(); + }, + ) + }) + .await + .expect("the single ordinary connection and staging connection settle"); + let reply = reply.success(StatusCode::OK); + let committed = (before.0 + 1, before.1 + 1, before.2 + 1, before.3); + assert_eq!(file_commit_state(&fixture).await, committed); + let ids = assert_file_commit_members(&fixture, before.0, 1).await; + assert_eq!(reply.body["results"]["register"]["recordId"], ids[0]); + assert_eq!(s3.puts.load(Ordering::SeqCst), 1); + + let replay = tokio::time::timeout( + Duration::from_secs(5), + membership_file_action(&fixture, &token, &body, key), + ) + .await + .expect("the receipt replays without waiting for another PUT") + .success(StatusCode::OK); + assert_eq!(replay.bytes, reply.bytes); + assert_eq!(file_commit_state(&fixture).await, committed); + assert_eq!(s3.puts.load(Ordering::SeqCst), 1); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn membership_file_action_rolls_back_after_a_completed_put() { + use registry_breg::mutation::MutationFaultPoint; + use std::sync::atomic::Ordering; + + let s3 = membership_s3(None).await; + let fixture = Fixture::configured( + Duration::from_secs(2), + membership_file_project(false), + vec![], + |service| service.with_attachment_storage(s3.storage.clone()), + ) + .await; + let faulted = Arc::new( + (*fixture.mutations) + .clone() + .with_fault_for_test(MutationFaultPoint::BeforeCommit), + ); + let faulted_app = authenticated_router( + Arc::new((*fixture.service).clone().with_postgres_mutations(faulted)), + fixture.authenticator.clone(), + ); + let before = file_commit_state(&fixture).await; + let durable_before = fixture.durable_state().await; + let body = membership_file_body(&fixture.keys.allowed, "rolled-back-file"); + let token = fixture.member(); + let key = "rolled-back-file"; + let reply = request_with_key( + &faulted_app, + &token, + Method::POST, + FILE_ACTION, + MEMBER, + body.clone(), + None, + key, + ) + .await; + assert_eq!( + reply.status, + StatusCode::SERVICE_UNAVAILABLE, + "{}", + reply.body + ); + assert_eq!(s3.puts.load(Ordering::SeqCst), 1); + assert_eq!(file_commit_state(&fixture).await, before); + assert_eq!(fixture.durable_state().await, durable_before); + let state: String = fixture + .database + .admin + .query_one( + "SELECT state FROM registry_internal.registry_attachment_blobs", + &[], + ) + .await + .unwrap() + .get(0); + assert_eq!(state, "staged"); + let retry = membership_file_action(&fixture, &token, &body, key) + .await + .success(StatusCode::OK); + let committed = (before.0 + 1, before.1 + 1, before.2 + 1, before.3); + assert_eq!(file_commit_state(&fixture).await, committed); + let ids = assert_file_commit_members(&fixture, before.0, 1).await; + assert_eq!(retry.body["results"]["register"]["recordId"], ids[0]); + assert_eq!(s3.puts.load(Ordering::SeqCst), 2); + let replay = membership_file_action(&fixture, &token, &body, key) + .await + .success(StatusCode::OK); + assert_eq!(retry.bytes, replay.bytes); + assert_eq!(file_commit_state(&fixture).await, committed); + assert_eq!(s3.puts.load(Ordering::SeqCst), 2); + drop(faulted_app); + + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn database_membership_file_action_records_bytes_with_its_revision() { + let fixture = Fixture::configured( + Duration::from_secs(2), + membership_file_project(false), + vec![], + |service| service, + ) + .await; + let before = file_commit_state(&fixture).await; + let body = membership_file_body(&fixture.keys.allowed, "database-file"); + let reply = membership_file_action(&fixture, &fixture.member(), &body, "database-file") + .await + .success(StatusCode::OK); + assert_eq!( + file_commit_state(&fixture).await, + (before.0 + 1, before.1 + 1, before.2 + 1, before.3) + ); + let ids = assert_file_commit_members(&fixture, before.0, 1).await; + assert_eq!(reply.body["results"]["register"]["recordId"], ids[0]); + let content: Vec = fixture.database.admin.query_one( + "SELECT content FROM registry_internal.registry_attachment_blobs WHERE backend_id = 'database'", + &[], + ).await.unwrap().get(0); + assert_eq!(content, MEMBERSHIP_FILE); + fixture.database.cleanup().await; +} + +async fn freeze_membership_file_proposal(fixture: &Fixture, token: &str) -> Reply { + let draft = action( + &fixture.app, + token, + "propose-facility/proposals", + MEMBER, + json!({"organization":fixture.keys.allowed,"label":"proposed-file"}), + ) + .await + .success(StatusCode::CREATED); + let id = draft.body["id"].as_str().unwrap(); + let upload_etag = draft.body["attachments"]["support"]["links"]["upload"]["ifMatch"] + .as_str() + .expect("the authorized draft exposes an upload precondition"); + let upload = Request::builder() + .method(Method::PATCH) + .uri(format!( + "/v1/proposals/{id}/attachments/support?accessProfile={MEMBER}" + )) + .header("authorization", format!("Bearer {token}")) + .header("idempotency-key", "upload-shared-membership-file") + .header("if-match", upload_etag) + .header("content-type", "text/plain") + .body(Body::from(MEMBERSHIP_FILE)) + .unwrap(); + let (parts, body) = fixture + .app + .clone() + .oneshot(upload) + .await + .unwrap() + .into_parts(); + let bytes = to_bytes(body, 1024 * 1024).await.unwrap().to_vec(); + let uploaded = Reply { + status: parts.status, + headers: parts.headers, + body: serde_json::from_slice(&bytes).unwrap(), + bytes, + } + .success(StatusCode::OK); + proposal_transition(&fixture.app, token, MEMBER, &uploaded, "submit", json!({})) + .await + .success(StatusCode::OK) +} + +// Run this ordinary overlap against the repaired candidate. The barrier +// releases both requests at entry, with no coordination inside either path. +#[tokio::test] +async fn membership_file_action_and_apply_settle_with_one_shared_blob() { + use std::sync::atomic::Ordering; + + let s3 = membership_s3(None).await; + let fixture = Fixture::configured_with_isolation( + Duration::from_secs(5), + membership_file_project(true), + vec![], + "read committed", + |service| service.with_attachment_storage(s3.storage.clone()), + ) + .await; + let token = fixture.member(); + let submitted = freeze_membership_file_proposal(&fixture, &token).await; + let body = membership_file_body(&fixture.keys.second, "immediate-file"); + let before = file_commit_state(&fixture).await; + let puts_before = s3.puts.load(Ordering::SeqCst); + assert_eq!(puts_before, 1); + + let barrier = tokio::sync::Barrier::new(2); + let (applied, invoked) = tokio::time::timeout(Duration::from_secs(12), async { + tokio::join!( + async { + barrier.wait().await; + proposal_apply_with_key(&fixture.app, &token, &submitted, "apply-shared-file").await + }, + async { + barrier.wait().await; + membership_file_action(&fixture, &token, &body, "invoke-shared-file").await + }, + ) + }) + .await + .expect("both authorized requests settle"); + let applied = applied.success(StatusCode::OK); + let invoked = invoked.success(StatusCode::OK); + assert_eq!(applied.body["state"], "applied"); + let committed = (before.0 + 2, before.1 + 2, before.2 + 2, before.3 + 1); + assert_eq!(file_commit_state(&fixture).await, committed); + let ids = assert_file_commit_members(&fixture, before.0, 2).await; + assert_ne!(ids[0], ids[1]); + let immediate_id = invoked.body["results"]["register"]["recordId"] + .as_str() + .unwrap(); + assert!(ids.iter().any(|id| id == immediate_id)); + for id in ids { + let result = request( + &fixture.app, + &token, + Method::GET, + &record(&id), + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + let label = if id == immediate_id { + "immediate-file" + } else { + "proposed-file" + }; + assert_eq!(result.body["data"]["label"], label); + } + let blobs: i64 = fixture + .database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_attachment_blobs", + &[], + ) + .await + .unwrap() + .get(0); + assert_eq!(blobs, 1); + assert_eq!( + s3.puts.load(Ordering::SeqCst), + puts_before + 1, + "only the Action uploads bytes" + ); + + let apply_replay = + proposal_apply_with_key(&fixture.app, &token, &submitted, "apply-shared-file") + .await + .success(StatusCode::OK); + let action_replay = membership_file_action(&fixture, &token, &body, "invoke-shared-file") + .await + .success(StatusCode::OK); + assert_eq!(apply_replay.bytes, applied.bytes); + assert_eq!(action_replay.bytes, invoked.bytes); + assert_eq!(file_commit_state(&fixture).await, committed); + assert_eq!(s3.puts.load(Ordering::SeqCst), puts_before + 1); + fixture.database.cleanup().await; +} + +async fn proposal_fixture() -> Fixture { + Fixture::configured_with_isolation( + Duration::from_secs(10), + membership_write_project::proposal_project(), + Vec::new(), + "read committed", + |service| service, + ) + .await +} + +async fn proposal_submit(fixture: &Fixture, name: &str, input: Value) -> Reply { + let token = fixture.member(); + let draft = action( + &fixture.app, + &token, + &format!("{name}/proposals"), + MEMBER, + input, + ) + .await + .success(StatusCode::CREATED); + proposal_transition(&fixture.app, &token, MEMBER, &draft, "submit", json!({})) + .await + .success(StatusCode::OK) +} + +async fn proposal_transition( + app: &axum::Router, + token: &str, + profile: &str, + current: &Reply, + transition: &str, + body: Value, +) -> Reply { + let id = current.body["id"].as_str().unwrap(); + request( + app, + token, + Method::POST, + &format!("/v1/proposals/{id}/{transition}"), + profile, + body, + Some(current.etag()), + ) + .await +} + +async fn proposal_apply(app: &axum::Router, token: &str, submitted: &Reply) -> Reply { + proposal_apply_with_key(app, token, submitted, &Uuid::new_v4().to_string()).await +} + +async fn proposal_apply_with_key( + app: &axum::Router, + token: &str, + submitted: &Reply, + key: &str, +) -> Reply { + request_with_key( + app, + token, + Method::POST, + &format!( + "/v1/proposals/{}/apply", + submitted.body["id"].as_str().unwrap() + ), + MEMBER, + json!({ + "submissionVersion":submitted.body["submissionVersion"], + "effectDigest":submitted.body["effectDigest"] + }), + Some(submitted.etag()), + key, + ) + .await +} + +#[tokio::test] +async fn a_member_proposes_and_applies_in_their_key() { + let fixture = proposal_fixture().await; + let submitted = proposal_submit( + &fixture, + "propose-facility", + json!({"organization":fixture.keys.allowed,"label":"proposed"}), + ) + .await; + let applied = proposal_apply(&fixture.app, &fixture.member(), &submitted) + .await + .success(StatusCode::OK); + assert_eq!(applied.body["state"], "applied"); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_removal_between_submit_and_apply_answers_precondition_failed() { + let fixture = proposal_fixture().await; + let submitted = proposal_submit( + &fixture, + "propose-facility", + json!({"organization":fixture.keys.allowed,"label":"proposed"}), + ) + .await; + let steward = fixture.steward(); + let path = format!("/v1/records/memberships/{}", fixture.keys.membership); + let current = request( + &fixture.app, + &steward, + Method::GET, + &path, + MEMBERSHIP_WRITER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + request( + &fixture.app, + &steward, + Method::PATCH, + &path, + MEMBERSHIP_WRITER, + patch("active", false), + Some(current.etag()), + ) + .await + .success(StatusCode::OK); + let before = fixture.durable_state().await; + let member = fixture.member(); + let production = proposal_apply(&fixture.app, &member, &submitted).await; + production.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + let development = proposal_apply(&fixture.development, &member, &submitted).await; + development.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!( + production.normalized_bytes(), + development.normalized_bytes() + ); + assert_eq!(fixture.durable_state().await, before); + let id = submitted.body["id"].as_str().unwrap(); + for (app, check) in [ + (&fixture.app, Value::Null), + (&fixture.development, json!("membership")), + ] { + for path in [ + format!("/v1/proposals/{id}"), + format!("/v1/proposals/{id}/submissions/1"), + ] { + let read = request(app, &member, Method::GET, &path, MEMBER, Value::Null, None).await; + read.problem(StatusCode::NOT_FOUND, "resource.not-found"); + assert_eq!(read.body["failedCheck"], check); + } + let listed = request( + app, + &member, + Method::GET, + "/v1/proposals", + MEMBER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + assert_eq!(listed.body["items"], json!([])); + } + let recorded = fixture.database.admin.query_one( + "SELECT workflow_revision, blocked_reason FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&Uuid::parse_str(id).unwrap()], + ).await.unwrap(); + assert_eq!( + recorded.get::<_, i64>(0), + submitted.body["revision"].as_i64().unwrap() + ); + assert_eq!(recorded.get::<_, Option>(1), None); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_membership_refusals_match_the_claim_boundary_answer() { + let fixture = proposal_fixture().await; + let visible = fixture + .seed(Some(&fixture.keys.allowed), "proposal-visible") + .await; + let hidden = fixture + .seed(Some(&fixture.keys.foreign), "proposal-hidden") + .await; + for app in [&fixture.app, &fixture.development] { + let mut observed = Vec::new(); + for (profile, token) in [(MEMBER, fixture.member()), (CLAIMED, fixture.claimed())] { + let moved = |facility: &Reply| { + json!({ + "facility":facility.record_id(),"organization":fixture.keys.second, + }) + }; + let denied_start = action( + app, + &token, + "propose-move/proposals", + profile, + moved(&hidden), + ) + .await; + let draft = action( + app, + &token, + "propose-move/proposals", + profile, + moved(&visible), + ) + .await + .success(StatusCode::CREATED); + let denied_edit = proposal_transition( + app, + &token, + profile, + &draft, + "edit", + json!({"input":moved(&hidden)}), + ) + .await; + let pending = action( + app, + &token, + "propose-facility/proposals", + profile, + json!({"organization":fixture.keys.foreign,"label":"proposed-denied"}), + ) + .await + .success(StatusCode::CREATED); + let before_create = fixture.durable_state().await; + let denied_submit = + proposal_transition(app, &token, profile, &pending, "submit", json!({})).await; + assert_eq!(fixture.durable_state().await, before_create); + let pending_move = action( + app, + &token, + "propose-move/proposals", + profile, + json!({"facility":visible.record_id(),"organization":fixture.keys.foreign}), + ) + .await + .success(StatusCode::CREATED); + let before_move = fixture.durable_state().await; + let denied_move = + proposal_transition(app, &token, profile, &pending_move, "submit", json!({})).await; + assert_eq!(fixture.durable_state().await, before_move); + let refusals = [denied_start, denied_edit, denied_submit, denied_move]; + for refusal in &refusals { + refusal.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + } + observed.push(refusals); + } + for (membership, claim) in observed[0].iter().zip(&observed[1]) { + membership.assert_same_problem(claim); + } + } + fixture.database.cleanup().await; +} + +async fn steward_removal(fixture: &Fixture, membership_id: &str) -> tokio::task::JoinHandle { + let path = format!("/v1/records/memberships/{membership_id}"); + let app = fixture.app.clone(); + let steward = fixture.steward(); + let current = request( + &app, + &steward, + Method::GET, + &path, + MEMBERSHIP_WRITER, + Value::Null, + None, + ) + .await + .success(StatusCode::OK); + tokio::spawn(async move { + request( + &app, + &steward, + Method::PATCH, + &path, + MEMBERSHIP_WRITER, + patch("active", false), + Some(current.etag()), + ) + .await + }) +} + +#[tokio::test] +async fn action_write_first_makes_the_removal_wait() { + assert_action_or_proposal_write_first(false).await; +} + +#[tokio::test] +async fn proposal_write_first_makes_the_removal_wait() { + assert_action_or_proposal_write_first(true).await; +} + +async fn assert_action_or_proposal_write_first(proposal: bool) { + let fixture = proposal_fixture().await; + let row = fixture.seed(Some(&fixture.keys.allowed), "open").await; + let record_id = row.record_id(); + let submitted = if proposal { + Some( + proposal_submit( + &fixture, + "propose-move", + json!({"facility":record_id,"organization":fixture.keys.second}), + ) + .await, + ) + } else { + None + }; + let (mut admin, connection) = fixture.database.connect_admin().await; + let blocker = admin.transaction().await.unwrap(); + let blocker_pid = hold_row(&blocker, &table(&fixture, "facility"), &record_id).await; + let app = fixture.app.clone(); + let token = fixture.member(); + let writer = tokio::spawn(async move { + match submitted { + Some(submitted) => proposal_apply(&app, &token, &submitted).await, + None => { + action( + &app, + &token, + "close-facility", + MEMBER, + json!({"facility":record_id}), + ) + .await + } + } + }); + let writer_pid = wait_for_blocker(&fixture.database, blocker_pid).await; + let removal = steward_removal(&fixture, &fixture.keys.membership).await; + wait_for_blocker(&fixture.database, writer_pid).await; + blocker.commit().await.unwrap(); + writer.await.unwrap().success(StatusCode::OK); + removal.await.unwrap().success(StatusCode::OK); + connection.abort(); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn action_removal_first_refuses_the_write() { + let fixture = Fixture::create(Duration::from_secs(10)).await; + let row = fixture.seed(Some(&fixture.keys.allowed), "open").await; + let app = fixture.app.clone(); + let member = fixture.member(); + after_steward_removal(&fixture, async move { + action( + &app, + &member, + "close-facility", + MEMBER, + json!({"facility":row.record_id()}), + ) + .await + }) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_removal_first_refuses_the_write() { + let fixture = Fixture::configured( + Duration::from_secs(10), + membership_write_project::proposal_project(), + Vec::new(), + |service| service, + ) + .await; + let submitted = proposal_submit( + &fixture, + "propose-facility", + json!({"organization":fixture.keys.allowed,"label":"pending-removal"}), + ) + .await; + let app = fixture.app.clone(); + let member = fixture.member(); + after_steward_removal(&fixture, async move { + proposal_apply(&app, &member, &submitted).await + }) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + fixture.database.cleanup().await; +} + +async fn after_steward_removal( + fixture: &Fixture, + write: impl std::future::Future + Send + 'static, +) -> Reply { + let (mut admin, connection) = fixture.database.connect_admin().await; + let blocker = admin.transaction().await.unwrap(); + // The steward locks and updates the membership row before appending its + // commit. Hold the journal head to keep that update open while the caller + // reaches the membership lock. + let blocker_pid: i32 = blocker.query_one( + "SELECT pg_backend_pid() FROM registry_internal.registry_commit_head WHERE singleton FOR UPDATE", + &[], + ).await.unwrap().get(0); + let removal = steward_removal(fixture, &fixture.keys.membership).await; + let remover_pid = wait_for_blocker(&fixture.database, blocker_pid).await; + let writer = tokio::spawn(write); + wait_for_blocker(&fixture.database, remover_pid).await; + blocker.commit().await.unwrap(); + removal.await.unwrap().success(StatusCode::OK); + let reply = writer.await.unwrap(); + connection.abort(); + reply +} + +#[tokio::test] +async fn proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted() { + let fixture = proposal_fixture().await; + let row = fixture + .seed(Some(&fixture.keys.allowed), "move-proposal") + .await; + let submitted = proposal_submit( + &fixture, + "propose-move", + json!({"facility":row.record_id(),"organization":fixture.keys.second}), + ) + .await; + steward_removal(&fixture, &fixture.keys.second_membership) + .await + .await + .unwrap() + .success(StatusCode::OK); + let before = fixture.durable_state().await; + let member = fixture.member(); + let claim = mint( + &fixture.idp, + MEMBER, + "records:claim", + &[&fixture.keys.allowed], + ); + let path = format!("/v1/proposals/{}", submitted.body["id"].as_str().unwrap()); + for (app, development) in [(&fixture.app, false), (&fixture.development, true)] { + let claimed_view = request(app, &claim, Method::GET, &path, CLAIMED, Value::Null, None) + .await + .success(StatusCode::OK); + let membership = proposal_apply(app, &member, &submitted).await; + let twin = proposal_transition( + app, + &claim, + CLAIMED, + &claimed_view, + "apply", + json!({ + "submissionVersion":submitted.body["submissionVersion"], + "effectDigest":submitted.body["effectDigest"], + }), + ) + .await; + membership.problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + twin.problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + if development { + assert_eq!(membership.body["failedCheck"], "membership"); + assert_eq!(twin.body["failedCheck"], "row-boundary"); + membership.assert_same_problem_except_check(&twin); + } else { + membership.assert_same_problem(&twin); + } + } + assert_eq!(fixture.durable_state().await, before); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_cannot_invalidate_its_own_membership_proof() { + let mut project = membership_write_project::project(); + let actions = [ + "register-and-retire-membership", + "retire-membership-and-register", + ]; + for id in actions { + let action = &mut project["actions"][id]; + action["execution"] = json!({"mode":"proposal","proposal":{ + "review":{"type":"none"},"application":{"mode":"manual"},"retention":{"mode":"operator-erase"} + }}); + } + let permissions = &mut project["accessProfiles"]["maintainer"]["permissions"]; + let mut proposals = Vec::new(); + for action in permissions["actions"].as_array_mut().unwrap() { + let id = action["action"].as_str().unwrap(); + if !actions.contains(&id) { + continue; + } + proposals.push(json!({"action":id,"operations":["get","submit","apply"], + "ownership":"caller","targets":action["targets"]})); + action["operations"] = json!(["start"]); + action.as_object_mut().unwrap().remove("results"); + } + permissions["proposals"] = json!(proposals); + let fixture = Fixture::configured(Duration::from_secs(10), project, Vec::new(), |service| { + service + }) + .await; + let maintainer = mint(&fixture.idp, MEMBER, "records:retire", &[]); + for id in actions { + let draft = action( + &fixture.app, &maintainer, &format!("{id}/proposals"), "maintainer", + json!({"organization":fixture.keys.allowed,"membership":fixture.keys.membership,"label":"proposal-rollback"}), + ).await.success(StatusCode::CREATED); + let submitted = proposal_transition( + &fixture.app, + &maintainer, + "maintainer", + &draft, + "submit", + json!({}), + ) + .await + .success(StatusCode::OK); + let before = fixture.durable_state().await; + let markers = fixture.proposal_markers(&submitted).await; + proposal_transition(&fixture.app, &maintainer, "maintainer", &submitted, "apply", json!({ + "submissionVersion":submitted.body["submissionVersion"],"effectDigest":submitted.body["effectDigest"] + })).await.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, before); + assert_eq!(fixture.proposal_markers(&submitted).await, markers); + } + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn automatic_worker_keeps_system_authority_and_human_apply_has_a_source_lock() { + let mut project = membership_write_project::proposal_project(); + project["actions"]["propose-facility"]["execution"]["proposal"]["application"] = + json!({"mode":"automatic","maximumAttempts":3}); + let targets = + project["accessProfiles"]["member"]["permissions"]["proposals"][0]["targets"].clone(); + project["accessProfiles"]["human-recovery"] = json!({ + "principalClaim":"sub","actorKind":"human","requiredScopes":["proposal:recover"], + "permissions":{"proposals":[{"action":"propose-facility","operations":["apply"], + "ownership":"caller","targets":targets}]} + }); + let fixture = Fixture::configured(Duration::from_secs(10), project, Vec::new(), |service| { + service + }) + .await; + let source = &fixture.registry.entities()["membership"].physical_table; + assert!(fixture + .database + .admin + .query_one( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_policies + WHERE schemaname='registry_data' AND tablename=$1 AND cmd='UPDATE' + AND qual LIKE '%membership_lock_%' AND qual LIKE '%human-recovery%')", + &[source], + ) + .await + .unwrap() + .get::<_, bool>(0)); + let submitted = proposal_submit( + &fixture, + "propose-facility", + json!({"organization":fixture.keys.allowed,"label":"system-application"}), + ) + .await; + steward_removal(&fixture, &fixture.keys.membership) + .await + .await + .unwrap() + .success(StatusCode::OK); + assert!(fixture + .mutations + .run_automatic_proposal_once_for_test() + .await + .unwrap()); + let id = Uuid::parse_str(submitted.body["id"].as_str().unwrap()).unwrap(); + let state: String = fixture + .database + .admin + .query_one( + "SELECT state FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + assert_eq!(state, "applied"); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_apply_rechecks_the_locked_key_of_an_unconditioned_link() { + let mut project = membership_write_project::proposal_project(); + let immediate = project["actions"]["register-facility"].clone(); + let proposal = &mut project["actions"]["propose-facility"]; + proposal["inputs"] = immediate["inputs"].clone(); + proposal["plan"] = immediate["plan"].clone(); + for profile in ["member", "claimed"] { + project["accessProfiles"][profile]["permissions"]["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("related")); + } + let fixture = Fixture::configured(Duration::from_secs(10), project, Vec::new(), |service| { + service + }) + .await; + let row = fixture + .seed(Some(&fixture.keys.allowed), "link-target") + .await; + let linked = Uuid::parse_str(&row.record_id()).unwrap(); + let submitted = proposal_submit( + &fixture, + "propose-facility", + json!({ + "organization":fixture.keys.allowed,"related":linked,"label":"link-application" + }), + ) + .await; + let markers = fixture.proposal_markers(&submitted).await; + let (mut target_owner, connection) = fixture.database.connect_admin().await; + let moving = target_owner.transaction().await.unwrap(); + let organization = + &fixture.registry.entities()["facility"].fields["organization"].physical_name; + let blocker: i32 = moving + .query_one( + &format!( + "UPDATE {} SET \"{organization}\"=$1,record_revision=record_revision+1 + WHERE record_id=$2 RETURNING pg_backend_pid()", + table(&fixture, "facility") + ), + &[&Uuid::parse_str(&fixture.keys.second).unwrap(), &linked], + ) + .await + .unwrap() + .get(0); + let app = fixture.app.clone(); + let member = fixture.member(); + let apply = tokio::spawn(async move { + let reply = proposal_apply(&app, &member, &submitted).await; + (submitted, reply) + }); + wait_for_blocker(&fixture.database, blocker).await; + moving.commit().await.unwrap(); + let (submitted, reply) = apply.await.unwrap(); + reply.problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.proposal_markers(&submitted).await, markers); + // A fresh Apply can admit the unconditioned Link under its current key. + proposal_apply(&fixture.app, &fixture.member(), &submitted) + .await + .success(StatusCode::OK); + connection.abort(); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_candidate_admission_precedes_all_effect_groups() { + let mut project = membership_write_project::proposal_project(); + project["actions"]["propose-move"]["inputs"] + .as_array_mut() + .unwrap() + .push(json!({ + "id":"initial","type":"reference","target":"organization","required":true, + "classification":"internal" + })); + for profile in [MEMBER, CLAIMED] { + project["accessProfiles"][profile]["permissions"]["proposals"][1]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("initial")); + } + project["actions"]["propose-move"]["plan"]["effects"] + .as_array_mut() + .unwrap() + .insert( + 0, + json!({ + "id":"first","target":{"recordType":"facility"},"operation":"create", + "set":{"organization":{"fromInput":"initial"},"label":{"value":"reserved-label"}} + }), + ); + let fixture = Fixture::configured(Duration::from_secs(10), project, Vec::new(), |service| { + service + }) + .await; + let row = fixture + .seed(Some(&fixture.keys.allowed), "movable-base") + .await; + let submitted = proposal_submit(&fixture, "propose-move", json!({ + "facility":row.record_id(),"organization":fixture.keys.second,"initial":fixture.keys.allowed + })).await; + fixture + .seed(Some(&fixture.keys.allowed), "reserved-label") + .await; + steward_removal(&fixture, &fixture.keys.second_membership) + .await + .await + .unwrap() + .success(StatusCode::OK); + let markers = fixture.proposal_markers(&submitted).await; + let before = fixture.durable_state().await; + proposal_apply(&fixture.app, &fixture.member(), &submitted) + .await + .problem(StatusCode::FORBIDDEN, "write.outside-boundary"); + assert_eq!(fixture.proposal_markers(&submitted).await, markers); + assert_eq!(fixture.durable_state().await, before); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_guard_reason_requires_current_target_disclosure() { + let mut project = membership_write_project::proposal_project(); + project["actions"]["propose-move"]["commitGuards"]["targets"] + .as_array_mut() + .unwrap() + .push(json!({ + "input":"facility","field":"label","equals":"open","reason":"facility-not-open" + })); + let fixture = Fixture::configured(Duration::from_secs(10), project, Vec::new(), |service| { + service + }) + .await; + let row = fixture.seed(Some(&fixture.keys.allowed), "closed").await; + let member = fixture.member(); + let draft = action( + &fixture.app, + &member, + "propose-move/proposals", + MEMBER, + json!({ + "facility":row.record_id(),"organization":fixture.keys.second + }), + ) + .await + .success(StatusCode::CREATED); + let admitted = + proposal_transition(&fixture.app, &member, MEMBER, &draft, "submit", json!({})).await; + assert_eq!(admitted.body["guardReason"], "facility-not-open"); + steward_removal(&fixture, &fixture.keys.membership) + .await + .await + .unwrap() + .success(StatusCode::OK); + proposal_transition( + &fixture.development, + &member, + MEMBER, + &draft, + "submit", + json!({}), + ) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn proposal_target_revision_change_keeps_the_rebase_recovery() { + let fixture = proposal_fixture().await; + let row = fixture + .seed(Some(&fixture.keys.allowed), "revision-base") + .await; + let submitted = proposal_submit( + &fixture, + "propose-move", + json!({ + "facility":row.record_id(),"organization":fixture.keys.second + }), + ) + .await; + request( + &fixture.app, + &fixture.steward(), + Method::PATCH, + &record(&row.record_id()), + MEMBERSHIP_WRITER, + patch("label", "revised-base"), + Some(row.etag()), + ) + .await + .success(StatusCode::OK); + let before = fixture.durable_state().await; + proposal_apply(&fixture.app, &fixture.member(), &submitted) + .await + .problem(StatusCode::PRECONDITION_FAILED, "precondition.failed"); + assert_eq!(fixture.durable_state().await, before); + assert_eq!( + fixture.proposal_markers(&submitted).await.1.as_deref(), + Some("application-rebase") + ); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn membership_diagnostics_count_only_observed_denials() { + use registry_breg::metrics::{metrics_app, Metrics}; + use registry_platform_testing::CapturedDiagnosticLogs; + use std::collections::BTreeMap; + use tracing::instrument::WithSubscriber; + + // The request counters and log budgets are process-wide. Observe exact + // deltas in one test process with no other requests using the recorder. + const CHILD: &str = "BREG_TEST_MEMBERSHIP_DIAGNOSTICS_CHILD"; + if std::env::var_os(CHILD).is_none() { + let outcome = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "membership_write_journeys::membership_diagnostics_count_only_observed_denials", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&outcome.stdout); + assert!( + outcome.status.success() && stdout.contains("1 passed; 0 failed"), + "{stdout}" + ); + return; + } + + async fn counts() -> BTreeMap { + let response = metrics_app( + Arc::new(Metrics::without_pool_for_test()), + Posture::Production, + ) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .unwrap(); + std::str::from_utf8(&bytes) + .unwrap() + .lines() + .filter_map(|line| { + let sample = line.strip_prefix("breg_request_refusals_total{check=\"")?; + let (label, value) = sample.split_once("\"} ").unwrap(); + Some((label.to_owned(), value.parse().unwrap())) + }) + .collect() + } + + let fixture = proposal_fixture().await; + let outside = fixture + .seed(Some(&fixture.keys.foreign), "outside-member-signal") + .await + .record_id(); + let submitted = proposal_submit( + &fixture, + "propose-facility", + json!({"organization":fixture.keys.second,"label":"member-signal-value"}), + ) + .await; + proposal_submit( + &fixture, + "propose-facility", + json!({"organization":fixture.keys.second,"label":"second-member-signal"}), + ) + .await; + steward_removal(&fixture, &fixture.keys.second_membership) + .await + .await + .unwrap() + .success(StatusCode::OK); + let member = fixture.member(); + let target = format!("{RECORDS}/{outside}"); + let proposal_id = submitted.body["id"].as_str().unwrap(); + let proposal = format!("/v1/proposals/{proposal_id}"); + let apply = format!("{proposal}/apply"); + for (method, path, profile, body, status, code, check) in [ + ( + Method::POST, + RECORDS, + MEMBER, + json!({"data":{"organization":fixture.keys.foreign,"label":"member-signal-value"}}), + StatusCode::FORBIDDEN, + "write.outside-boundary", + Some("membership"), + ), + ( + Method::POST, + "/v1/actions/close-facility/availability", + "observer", + json!({"targetInput":"facility","input":{"facility":outside}}), + StatusCode::NOT_FOUND, + "resource.not-found", + Some("membership"), + ), + ( + Method::POST, + "/v1/actions/register-facility", + MEMBER, + json!({"input":{"organization":fixture.keys.foreign,"label":"member-signal-value"}}), + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + Some("membership"), + ), + ( + Method::GET, + target.as_str(), + MEMBER, + Value::Null, + StatusCode::NOT_FOUND, + "resource.not-found", + Some("visibility"), + ), + ( + Method::POST, + "/v1/actions/close-facility", + MEMBER, + json!({"input":{"facility":outside}}), + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + None, + ), + ( + Method::GET, + proposal.as_str(), + MEMBER, + Value::Null, + StatusCode::NOT_FOUND, + "resource.not-found", + Some("membership"), + ), + ( + Method::GET, + "/v1/proposals", + MEMBER, + Value::Null, + StatusCode::OK, + "", + None, + ), + ( + Method::POST, + apply.as_str(), + MEMBER, + json!({ + "submissionVersion":submitted.body["submissionVersion"], + "effectDigest":submitted.body["effectDigest"], + }), + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + Some("membership"), + ), + ] { + let before = counts().await; + let capture = CapturedDiagnosticLogs::default(); + let etag = (path == apply).then_some(submitted.etag()); + let reply = request(&fixture.app, &member, method, path, profile, body, etag) + .with_subscriber(capture.subscriber()) + .await; + let trace = reply.body["traceId"].as_str().map(str::to_owned); + if status == StatusCode::OK { + assert_eq!(reply.success(status).body, json!({"items":[]})); + } else { + reply.problem(status, code); + } + let changed: BTreeMap<_, _> = counts() + .await + .into_iter() + .filter_map(|(label, value)| { + let delta = value - before[&label]; + (delta > 0).then_some((label, delta)) + }) + .collect(); + let expected = check + .into_iter() + .map(|label| (label.to_owned(), 1)) + .collect(); + assert_eq!(changed, expected, "{path}"); + let logs = capture.text(); + for value in [ + outside.as_str(), + fixture.keys.foreign.as_str(), + fixture.keys.second.as_str(), + proposal_id, + "member-signal-value", + "second-member-signal", + ] { + assert!( + !logs.contains(value), + "{path}: a compared value reached the logs" + ); + } + let checks: Vec<_> = logs + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .filter(|event| event["fields"]["message"] == "request refused") + .map(|event| { + assert!(event["fields"]["trace_id"].as_str() == trace.as_deref()); + event["fields"]["failed_check"].as_str().unwrap().to_owned() + }) + .collect(); + assert_eq!( + checks, + check.into_iter().map(str::to_owned).collect::>(), + "{path}" + ); + } + fixture.database.cleanup().await; +} diff --git a/crates/registry-breg/tests/support/membership_write_project.rs b/crates/registry-breg/tests/support/membership_write_project.rs new file mode 100644 index 0000000000..9be5e1831b --- /dev/null +++ b/crates/registry-breg/tests/support/membership_write_project.rs @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: Apache-2.0 + +use serde_json::{json, Value}; + +pub(super) fn project() -> Value { + let mut project = super::membership_fixture::source("facility"); + project["project"]["id"] = json!("membership-writes"); + project["package"] = json!({"sourceRevision":"membership-writes-fixture"}); + project["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + project["recordTypes"]["membership"]["tombstone"] = json!(true); + project["recordTypes"]["organization"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"owner","type":"string","maximumLength":80,"classification":"internal"})); + let facility = &mut project["recordTypes"]["facility"]; + facility["tombstone"] = json!(true); + facility["batch"] = json!({"maximumItems":4,"maximumBytes":8192}); + facility["constraints"] = json!([{"type":"unique","fields":["label"]}]); + facility["hooks"] = json!([ + {"phase":"after","id":"facility-created","trigger":"created","projection":["label"],"handler":{"type":"url","destinationId":"record-events"}}, + {"phase":"after","id":"facility-patched","trigger":"patched","projection":["label"],"handler":{"type":"url","destinationId":"record-events"}}, + {"phase":"after","id":"facility-tombstoned","trigger":"tombstoned","projection":["label"],"handler":{"type":"url","destinationId":"record-events"}} + ]); + facility["fields"][0]["required"] = json!(false); + facility["fields"].as_array_mut().unwrap().extend([ + json!({"id":"number","type":"string","maximumLength":32,"required":true, + "classification":"internal","generate":{"type":"sequence","prefix":"FAC-","minimumDigits":4}}), + json!({"id":"related","type":"reference","target":"facility","classification":"internal"}), + ]); + let membership = json!([{"field":"organization","membership":"membership"}]); + let claim = json!([{"field":"organization","claim":"organization","operator":"in"}]); + let writable = json!(["organization", "label", "related"]); + let readable = json!(["organization", "label", "related", "number"]); + let operations = json!(["get", "list", "create", "patch", "tombstone", "batch"]); + project["accessProfiles"]["member"] = json!({ + "principalClaim":"sub","actorKind":"human","requiredScopes":"unrestricted", + "permissions":{"records":[{ + "recordType":"facility","rowBoundaries": membership.clone(), + "operations": operations.clone(),"readableFields":readable.clone(), + "writableFields":writable.clone() + }]} + }); + project["accessProfiles"]["claimed"] = json!({ + "principalClaim":"sub","actorKind":"human","requiredScopes":["records:claim"], + "permissions":{"records":[{ + "recordType":"facility","rowBoundaries":claim.clone(),"operations":operations, + "readableFields":readable.clone(),"writableFields":writable.clone() + }]} + }); + for (id, fields) in [ + ("observer", json!(["organization", "label"])), + ("limited", json!(["label"])), + ] { + project["accessProfiles"][id] = json!({ + "principalClaim":"sub","actorKind":"human","requiredScopes":"unrestricted", + "permissions":{"records":[{ + "recordType":"facility","rowBoundaries":"unrestricted", + "operations":["get"],"readableFields": fields + }]} + }); + } + let steward = &mut project["accessProfiles"]["steward"]; + steward["principalClaim"] = json!("sub"); + steward["permissions"]["records"][0]["writableFields"] = json!(["name", "owner"]); + steward["permissions"]["records"][1]["operations"] = + json!(["create", "get", "patch", "tombstone"]); + steward["permissions"]["records"][2]["readableFields"] = readable; + steward["permissions"]["records"][2]["writableFields"] = writable; + let reference = |id: &str, target: &str, required| { + json!({"id":id,"type":"reference","target":target,"required":required, + "classification":"internal"}) + }; + let label = || { + json!({"id":"label","type":"string","maximumLength":80,"required":true, + "classification":"internal"}) + }; + project["actions"] = json!({ + "register-facility": { + "execution":{"mode":"immediate"}, + "inputs":[reference("organization","organization",true),reference("related","facility",false),label()], + "plan":{"type":"fixed","effects":[{"id":"register","target":{"recordType":"facility"}, + "operation":"create","set":{"organization":{"fromInput":"organization"}, + "related":{"fromInput":"related"},"label":{"fromInput":"label"}}}]} + }, + "close-facility": { + "execution":{"mode":"immediate","concurrency":"current-revision"}, + "inputs":[reference("facility","facility",true)], + "commitGuards":{"targets":[{"input":"facility","field":"label","equals":"open", + "reason":"facility-not-open"}]}, + "plan":{"type":"fixed","effects":[{"id":"close","target":{"fromInput":"facility"}, + "operation":"patch","set":{"label":{"value":"closed"}}}]} + }, + "move-facility": { + "execution":{"mode":"immediate"}, + "inputs":[reference("facility","facility",true),reference("organization","organization",true)], + "commitGuards":{"targets":[{"input":"facility","revision":"unchanged"}]}, + "plan":{"type":"fixed","effects":[{"id":"move","target":{"fromInput":"facility"}, + "operation":"patch","set":{"organization":{"fromInput":"organization"}}}]} + } + }); + project["actions"]["register-pair"] = json!({ + "execution":{"mode":"immediate"}, + "inputs":[reference("first","organization",true),reference("second","organization",true)], + "plan":{"type":"fixed","effects":[ + {"id":"first","target":{"recordType":"facility"},"operation":"create", + "set":{"organization":{"fromInput":"first"},"label":{"value":"existing-label"}}}, + {"id":"second","target":{"recordType":"facility"},"operation":"create", + "set":{"organization":{"fromInput":"second"},"label":{"value":"pair-second"}}} + ]} + }); + project["actions"]["retire-membership-and-register"] = json!({ + "execution":{"mode":"immediate","concurrency":"current-revision"}, + "inputs":[reference("organization","organization",true), reference("membership","membership",true), label()], + "commitGuards":{"targets":[{"input":"membership","field":"active","equals":true}]}, + "plan":{"type":"fixed","effects":[ + {"id":"register","target":{"recordType":"facility"},"operation":"create", + "set":{"organization":{"fromInput":"organization"},"label":{"fromInput":"label"}}}, + {"id":"retire","target":{"fromInput":"membership"},"operation":"patch", + "set":{"active":{"value":false}}} + ]} + }); + let register_then_retire = project["actions"]["retire-membership-and-register"].clone(); + project["actions"]["retire-membership-and-register"]["plan"]["effects"] + .as_array_mut() + .unwrap() + .swap(0, 1); + project["actions"]["register-and-retire-membership"] = register_then_retire; + project["actions"]["register-in-created-organization"] = json!({ + "execution":{"mode":"immediate"}, + "inputs":[label()], + "plan":{"type":"fixed","effects":[ + {"id":"organization","target":{"recordType":"organization"},"operation":"create", + "set":{"name":{"fromInput":"label"}}}, + {"id":"register","target":{"recordType":"facility"},"operation":"create", + "set":{"organization":{"fromEffect":"organization"},"label":{"fromInput":"label"}}} + ]} + }); + project["accessProfiles"]["maintainer"] = json!({ + "principalClaim":"sub","actorKind":"human","requiredScopes":["records:retire"], + "permissions":{"actions":[ + {"action":"retire-membership-and-register","operations":["invoke"],"results":["register","retire"], + "targets":[ + {"recordType":"facility","rowBoundaries":membership.clone()}, + {"recordType":"membership","rowBoundaries":"unrestricted"}, + {"recordType":"organization","rowBoundaries":"unrestricted"} + ]}, + {"action":"register-in-created-organization","operations":["invoke"],"results":["organization","register"], + "targets":[ + {"recordType":"facility","rowBoundaries":membership.clone()}, + {"recordType":"organization","rowBoundaries":"unrestricted"} + ]} + ]} + }); + let mut register_then_retire = + project["accessProfiles"]["maintainer"]["permissions"]["actions"][0].clone(); + register_then_retire["action"] = json!("register-and-retire-membership"); + project["accessProfiles"]["maintainer"]["permissions"]["actions"] + .as_array_mut() + .unwrap() + .push(register_then_retire); + for (id, bounds) in [ + ("member", membership.clone()), + ("claimed", claim.clone()), + ("observer", membership.clone()), + ("limited", membership), + ] { + project["accessProfiles"][id]["permissions"]["actions"] = Value::Array( + [ + ("register-facility", "register", true), + ("close-facility", "close", false), + ("move-facility", "move", true), + ] + .into_iter() + .map(|(action, result, uses_organization)| { + let mut targets = vec![json!({"recordType":"facility","rowBoundaries":bounds})]; + if uses_organization { + let owner = json!([{"field":"owner","claim":"sub","operator":"equals"}]); + targets.push(json!({"recordType":"organization","rowBoundaries":owner})); + } + json!({"action":action,"operations":["invoke"],"targets":targets,"results":[result]}) + }) + .collect(), + ); + } + let mut claim_observer = project["accessProfiles"]["observer"].clone(); + claim_observer["requiredScopes"] = json!(["records:claim"]); + claim_observer["permissions"]["actions"] = json!([{ + "action":"close-facility","operations":["invoke"],"results":["close"], + "targets":[{"recordType":"facility","rowBoundaries":claim}] + }]); + project["accessProfiles"]["claim-observer"] = claim_observer; + project["accessProfiles"]["member"]["permissions"]["actions"].as_array_mut().unwrap().push( + json!({"action":"register-pair","operations":["invoke"],"results":["first","second"], + "targets":[{"recordType":"facility","rowBoundaries":[{"field":"organization","membership":"membership"}]}, + {"recordType":"organization","rowBoundaries":[{"field":"owner","claim":"sub","operator":"equals"}]}]}), + ); + project +} + +/// The write fixture with the same membership and claim twins on Proposal grants. +pub(super) fn proposal_project() -> Value { + let mut project = project(); + for (immediate, proposal) in [ + ("register-facility", "propose-facility"), + ("move-facility", "propose-move"), + ] { + let mut action = project["actions"][immediate].clone(); + if immediate == "register-facility" { + action["inputs"] + .as_array_mut() + .unwrap() + .retain(|input| input["id"] != "related"); + action["plan"]["effects"][0]["set"] + .as_object_mut() + .unwrap() + .remove("related"); + } + let inputs: Vec<_> = action["inputs"] + .as_array() + .unwrap() + .iter() + .map(|input| input["id"].clone()) + .collect(); + action["execution"] = json!({ + "mode":"proposal","proposal":{ + "review":{"type":"none"},"application":{"mode":"manual"}, + "retention":{"mode":"operator-erase"} + } + }); + project["actions"][proposal] = action; + for profile in ["member", "claimed"] { + let permissions = project["accessProfiles"][profile]["permissions"] + .as_object_mut() + .unwrap(); + let targets = permissions["actions"] + .as_array() + .unwrap() + .iter() + .find(|grant| grant["action"] == immediate) + .unwrap()["targets"] + .clone(); + permissions + .get_mut("actions") + .unwrap() + .as_array_mut() + .unwrap() + .push(json!({ + "action":proposal,"operations":["start"],"targets":targets + })); + permissions + .entry("proposals") + .or_insert_with(|| json!([])) + .as_array_mut() + .unwrap() + .push(json!({ + "action":proposal, + "operations":["get","list","edit","submit","cancel","apply"], + "ownership":"caller","readableInputs":inputs,"targets":targets + })); + } + } + project +} diff --git a/crates/registry-breg/tests/support/pilot_acceptance_harness.rs b/crates/registry-breg/tests/support/pilot_acceptance_harness.rs index 5991d6f3ce..7044c43920 100644 --- a/crates/registry-breg/tests/support/pilot_acceptance_harness.rs +++ b/crates/registry-breg/tests/support/pilot_acceptance_harness.rs @@ -212,6 +212,8 @@ impl PilotHarness { } } + // Individual suites use only the token helpers their callers need. + #[allow(dead_code)] pub fn token(&self, purpose: &str, row_boundary_claims: &[(&str, Value)]) -> String { self.token_with_scopes(purpose, row_boundary_claims, &[]) } diff --git a/crates/registry-breg/tests/support/postgres_membership_writes.rs b/crates/registry-breg/tests/support/postgres_membership_writes.rs new file mode 100644 index 0000000000..94c47f6dda --- /dev/null +++ b/crates/registry-breg/tests/support/postgres_membership_writes.rs @@ -0,0 +1,583 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use registry_breg::model::CompiledEntity; +use registry_breg::package::CompiledRegistryMigrationBaseline; +use tokio_postgres::{error::SqlState, Transaction}; +use uuid::Uuid; + +const MEMBER_KEY: Uuid = Uuid::from_u128(1); +const INACTIVE_KEY: Uuid = Uuid::from_u128(2); +const OTHER_KEY: Uuid = Uuid::from_u128(3); +const MEMBER_CHILD: Uuid = Uuid::from_u128(4); +const OTHER_CHILD: Uuid = Uuid::from_u128(5); + +struct MembershipFixture { + database: postgres_harness::TestDatabase, + registry: registry_breg::CompiledRegistry, +} + +impl MembershipFixture { + async fn create(with_steward: bool) -> Self { + let (registry, actions) = membership_targets::immediate(with_steward); + let mut baseline = CompiledRegistryMigrationBaseline::from_compiled("fixture", ®istry); + baseline.actions = actions; + let registry = registry.with_migration_baseline_schema(&baseline); + let database = postgres_harness::TestDatabase::create(2).await; + let (migration, task) = database.connect_migration().await; + install_compiled_schema(&migration, ®istry, &database.runtime_role) + .await + .unwrap(); + let catalog = ExpectedManagedCatalog::compiled(®istry); + registry_breg::postgres::managed_schema_fingerprint( + &migration, + &database.runtime_role, + &catalog, + ) + .await + .expect("the compiled membership functions, policies and ACLs form a closed catalog"); + task.abort(); + + let parent = ®istry.entities()["parent"]; + let membership = ®istry.entities()["membership"]; + let child = ®istry.entities()["child"]; + let parent_table = relation(parent); + let membership_table = relation(membership); + let child_table = relation(child); + database.admin.batch_execute(&format!( + "SELECT set_config('registry.active_package_revision', 'fixture', false); + INSERT INTO {parent_table} (record_id, {}, {}) VALUES + ('{MEMBER_KEY}', 'active', 'test'), ('{INACTIVE_KEY}', 'active', 'test'), ('{OTHER_KEY}', 'active', 'test'); + INSERT INTO {membership_table} (record_id, {}, {}, {}) VALUES + (gen_random_uuid(), '{MEMBER_KEY}', 'member-a', true), + (gen_random_uuid(), '{INACTIVE_KEY}', 'member-a', false); + INSERT INTO {child_table} (record_id, {}, {}) VALUES + ('{MEMBER_CHILD}', '{MEMBER_KEY}', 'member child'), + ('{OTHER_CHILD}', '{OTHER_KEY}', 'other child')", + column(parent, "status"), + column(parent, "zone"), + column(membership, "organization"), + column(membership, "principal"), + column(membership, "active"), + column(child, "parent"), + column(child, "label"), + )).await.unwrap(); + + Self { database, registry } + } + + fn helper(&self, prefix: &str) -> ®istry_breg::generated_ddl::DdlFunction { + self.registry + .ddl() + .functions + .iter() + .find(|function| function.name.starts_with(prefix)) + .unwrap() + } + + fn lock(&self) -> ®istry_breg::generated_ddl::DdlFunction { + self.helper("membership_lock_") + } + + fn ordinary(&self) -> ®istry_breg::generated_ddl::DdlFunction { + self.helper("membership_target_") + } + + async fn set_target(&self, tx: &Transaction<'_>, id: Uuid) { + let action = &self.registry.actions().actions[0]; + let context = json!({ + "version": 1, + "actionId": action.id, + "contractFingerprint": action.definition_revision, + "activePackageRevision": "fixture", + "selectedAccessProfile": "registrar", + "principal": "member-a", + "purpose": null, + "effectIds": ["child"], + "applicationId": Uuid::from_u128(6), + "targetEntityId": "child", + "targetRecordId": id, + "operation": "create", + "fields": ["label", "parent"], + "expectedRevision": null, + "lockOnly": false, + "targetRowBoundaries": [], + }); + tx.query_one( + "SELECT set_config('registry.immediate_action_target_context', $1, true)", + &[&context.to_string()], + ) + .await + .unwrap(); + } +} + +fn relation(entity: &CompiledEntity) -> String { + format!("registry_data.\"{}\"", entity.physical_table) +} + +fn column(entity: &CompiledEntity, field: &str) -> String { + format!("\"{}\"", entity.fields[field].physical_name) +} + +async fn select_profile(tx: &Transaction<'_>) { + tx.batch_execute( + "SELECT set_config('registry.access_profile', 'registrar', true), + set_config('registry.principal', 'member-a', true), + set_config('registry.active_package_revision', 'fixture', true)", + ) + .await + .unwrap(); +} + +async fn probe( + tx: &Transaction<'_>, + function: ®istry_breg::generated_ddl::DdlFunction, + key: Option, +) -> Result, tokio_postgres::Error> { + tx.query_one( + &format!("SELECT registry_context.\"{}\"($1)", function.name), + &[&key], + ) + .await + .map(|row| row.get(0)) +} + +#[tokio::test] +async fn the_target_load_of_a_row_outside_the_callers_memberships_returns_no_row() { + let fixture = MembershipFixture::create(false).await; + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + let child = relation(&fixture.registry.entities()["child"]); + for (id, visible) in [(MEMBER_CHILD, true), (OTHER_CHILD, false)] { + fixture.set_target(&tx, id).await; + let row = tx + .query_opt( + &format!("SELECT record_id FROM {child} WHERE record_id = $1"), + &[&id], + ) + .await + .unwrap(); + assert_eq!(row.is_some(), visible); + } + tx.rollback().await.unwrap(); + drop(client); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_create_outside_the_callers_memberships_fails_row_security_with_42501() { + let fixture = MembershipFixture::create(false).await; + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let child = &fixture.registry.entities()["child"]; + let sql = format!( + "INSERT INTO {} (record_id, {}, {}) VALUES ($1, $2, 'child')", + relation(child), + column(child, "parent"), + column(child, "label") + ); + let id = Uuid::from_u128(7); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + fixture.set_target(&tx, id).await; + assert_eq!(tx.execute(&sql, &[&id, &MEMBER_KEY]).await.unwrap(), 1); + tx.rollback().await.unwrap(); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + fixture.set_target(&tx, id).await; + let err = tx.execute(&sql, &[&id, &OTHER_KEY]).await.unwrap_err(); + assert_eq!(err.code(), Some(&SqlState::INSUFFICIENT_PRIVILEGE)); + assert!(err + .as_db_error() + .unwrap() + .message() + .contains("row-level security")); + tx.rollback().await.unwrap(); + drop(client); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn the_lock_helper_answers_true_for_a_member_and_false_for_an_inactive_or_unknown_key() { + let fixture = MembershipFixture::create(false).await; + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + let marker = "prior-marker"; + tx.query_one( + "SELECT set_config('registry.membership_probe', $1, true)", + &[&marker], + ) + .await + .unwrap(); + for (key, answer) in [ + (Some(MEMBER_KEY), Some(true)), + (Some(INACTIVE_KEY), Some(false)), + (Some(Uuid::nil()), Some(false)), + (None, None), + ] { + assert_eq!(probe(&tx, fixture.lock(), key).await.unwrap(), answer); + let restored: String = tx + .query_one("SELECT current_setting('registry.membership_probe')", &[]) + .await + .unwrap() + .get(0); + assert_eq!(restored, marker); + } + tx.rollback().await.unwrap(); + drop(client); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn the_membership_lock_policy_exists() { + let fixture = MembershipFixture::create(false).await; + let source = relation(&fixture.registry.entities()["membership"]); + let runtime = fixture.database.runtime_role.as_str(); + let migration = fixture.database.migration_role.as_str(); + let lock_name = &fixture.lock().name; + assert_ne!(migration, runtime); + let row = fixture + .database + .admin + .query_one( + "SELECT c.relrowsecurity AND c.relforcerowsecurity, + r.rolname, p.polpermissive, p.polcmd::text, + pg_get_expr(p.polqual, p.polrelid), pg_get_expr(p.polwithcheck, p.polrelid), + NOT (r.rolsuper OR r.rolbypassrls) + FROM pg_policy p JOIN pg_class c ON c.oid = p.polrelid + JOIN pg_roles r ON p.polroles = ARRAY[r.oid] + WHERE c.oid = $1::text::regclass AND p.polname = $2", + &[&source, &format!("registry_{lock_name}_update")], + ) + .await + .unwrap(); + assert!(row.get::<_, bool>(0)); + assert_eq!(row.get::<_, String>(1), runtime); + assert!(row.get::<_, bool>(2)); + assert_eq!(row.get::<_, String>(3), "w"); + let guard: String = row.get(4); + for value in [ + lock_name.as_str(), + "registry.membership_probe", + "registry.access_profile", + "registrar", + "registry.principal", + "IS TRUE", + "record_lifecycle", + ] { + assert!(guard.contains(value), "{guard}"); + } + assert_eq!(row.get::<_, String>(5), "false"); + assert!(row.get::<_, bool>(6)); + for (helper, volatility) in [(fixture.ordinary(), "s"), (fixture.lock(), "v")] { + let signature = format!("registry_context.{}(uuid)", helper.name); + let row = fixture + .database + .admin + .query_one( + "SELECT r.rolname, NOT (r.rolsuper OR r.rolbypassrls), + l.lanname, p.provolatile::text, p.proisstrict, + NOT (p.prosecdef OR p.proleakproof OR p.proretset), + p.proconfig, p.prorettype = 'boolean'::regtype + FROM pg_proc p JOIN pg_roles r ON r.oid = p.proowner + JOIN pg_language l ON l.oid = p.prolang + WHERE p.oid = $1::text::regprocedure", + &[&signature], + ) + .await + .unwrap(); + assert_eq!(row.get::<_, String>(0), migration); + assert!(row.get::<_, bool>(1)); + assert_eq!(row.get::<_, String>(2), "plpgsql"); + assert_eq!(row.get::<_, String>(3), volatility); + assert!(row.get::<_, bool>(4)); + assert!(row.get::<_, bool>(5)); + assert_eq!(row.get::<_, Vec>(6), ["search_path=pg_catalog"]); + assert!(row.get::<_, bool>(7)); + } + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn the_runtime_role_can_lock_a_membership_row_it_cannot_update() { + let fixture = MembershipFixture::create(false).await; + let membership = &fixture.registry.entities()["membership"]; + let source = relation(membership); + let active = column(membership, "active"); + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let row = client + .query_one( + "SELECT has_table_privilege($1, 'SELECT'), has_table_privilege($1, 'UPDATE'), + has_column_privilege($1, 'record_id', 'UPDATE')", + &[&source], + ) + .await + .unwrap(); + assert!(row.get::<_, bool>(0)); + assert!(!row.get::<_, bool>(1)); + assert!(row.get::<_, bool>(2)); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + assert_eq!( + probe(&tx, fixture.lock(), Some(MEMBER_KEY)).await.unwrap(), + Some(true) + ); + tx.commit().await.unwrap(); + for sql in [ + format!("UPDATE {source} SET {active} = false"), + format!("INSERT INTO {source} (record_id) VALUES (gen_random_uuid())"), + ] { + let error = client.execute(&sql, &[]).await.unwrap_err(); + assert_eq!(error.code(), Some(&SqlState::INSUFFICIENT_PRIVILEGE)); + } + drop(client); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn the_lock_helper_is_refused_in_a_read_only_transaction() { + let fixture = MembershipFixture::create(false).await; + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let tx = client + .build_transaction() + .read_only(true) + .start() + .await + .unwrap(); + select_profile(&tx).await; + assert_eq!( + probe(&tx, fixture.ordinary(), Some(MEMBER_KEY)) + .await + .unwrap(), + Some(true) + ); + let error = probe(&tx, fixture.lock(), Some(MEMBER_KEY)) + .await + .unwrap_err(); + assert_eq!(error.code(), Some(&SqlState::READ_ONLY_SQL_TRANSACTION)); + tx.rollback().await.unwrap(); + drop(client); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn a_membership_table_no_write_locks_gets_no_update_privilege() { + let mut source = membership_fixture::source("facility"); + source["accessProfiles"]["steward"]["permissions"]["records"] + .as_array_mut() + .unwrap() + .remove(1); + let registry = membership_fixture::compile(&source).unwrap(); + let database = postgres_harness::TestDatabase::create(1).await; + let (migration, task) = database.connect_migration().await; + install_compiled_schema(&migration, ®istry, &database.runtime_role) + .await + .unwrap(); + let pool = database.runtime_config.build_pool().unwrap(); + let client = pool.get_for_test().await.unwrap(); + let table = relation(®istry.entities()["membership"]); + let row = client + .query_one( + "SELECT has_table_privilege($1, 'SELECT'), has_table_privilege($1, 'UPDATE'), + has_column_privilege($1, 'record_id', 'UPDATE')", + &[&table], + ) + .await + .unwrap(); + assert!(row.get::<_, bool>(0)); + assert!(!row.get::<_, bool>(1)); + assert!(!row.get::<_, bool>(2)); + assert!(registry + .ddl() + .functions + .iter() + .all(|function| !function.name.starts_with("membership_lock_"))); + drop(client); + task.abort(); + database.cleanup().await; +} + +#[tokio::test] +async fn the_lock_blocks_a_removal_until_the_writer_commits() { + let fixture = MembershipFixture::create(true).await; + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + let writer_pid: i32 = tx + .query_one("SELECT pg_backend_pid()", &[]) + .await + .unwrap() + .get(0); + assert_eq!( + probe(&tx, fixture.lock(), Some(MEMBER_KEY)).await.unwrap(), + Some(true) + ); + let mut remover = pool.get_for_test().await.unwrap(); + let removal = remover.transaction().await.unwrap(); + removal + .batch_execute( + "SELECT set_config('registry.access_profile', 'steward', true), + set_config('registry.principal', 'steward', true), + set_config('registry.row_boundaries', '[]', true), + set_config('registry.active_package_revision', 'fixture', true)", + ) + .await + .unwrap(); + let remover_pid: i32 = removal + .query_one("SELECT pg_backend_pid()", &[]) + .await + .unwrap() + .get(0); + let membership = &fixture.registry.entities()["membership"]; + let removal_sql = format!( + "UPDATE {} SET {} = false WHERE {} = $1 AND {} = 'member-a'", + relation(membership), + column(membership, "active"), + column(membership, "organization"), + column(membership, "principal") + ); + { + let remove = removal.execute(&removal_sql, &[&MEMBER_KEY]); + tokio::pin!(remove); + let observe = async { + loop { + let blocked: bool = tx + .query_one( + "SELECT $1 = ANY(pg_blocking_pids($2))", + &[&writer_pid, &remover_pid], + ) + .await + .unwrap() + .get(0); + if blocked { + return; + } + tokio::task::yield_now().await; + } + }; + tokio::select! { + result = &mut remove => panic!("removal finished before writer committed: {result:?}"), + observed = tokio::time::timeout(Duration::from_secs(5), observe) => observed.unwrap(), + } + tx.commit().await.unwrap(); + assert_eq!(remove.await.unwrap(), 1); + } + removal.commit().await.unwrap(); + drop(remover); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + assert_eq!( + probe(&tx, fixture.lock(), Some(MEMBER_KEY)).await.unwrap(), + Some(false) + ); + tx.rollback().await.unwrap(); + drop(client); + fixture.database.cleanup().await; +} + +#[tokio::test] +async fn the_membership_probe_plan_uses_the_generated_index() { + assert_index_plan(false).await; +} + +#[tokio::test] +async fn the_membership_lock_plan_uses_the_generated_index() { + assert_index_plan(true).await; +} + +async fn assert_index_plan(lock: bool) { + let fixture = MembershipFixture::create(false).await; + let membership = &fixture.registry.entities()["membership"]; + let table = relation(membership); + fixture + .database + .admin + .batch_execute(&format!( + "INSERT INTO {table} (record_id, {}, {}, {}) + SELECT gen_random_uuid(), '{MEMBER_KEY}', 'other-' || i, i <= 2000 + FROM generate_series(1, 2223) i; + ANALYZE {table}", + column(membership, "organization"), + column(membership, "principal"), + column(membership, "active") + )) + .await + .unwrap(); + + let helper = if lock { + fixture.lock() + } else { + fixture.ordinary() + }; + let ddl = fixture + .registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == helper.id) + .unwrap(); + let body = ddl.sql.split_once(" AS '").unwrap().1.replace("''", "'"); + // The compiler's inner statement is explained under the same profile and + // marker as the helper. PL/pgSQL PERFORM spells SQL SELECT without a result. + let scan = if lock { + body.split_once("PERFORM 1 FROM") + .unwrap() + .1 + .split_once("; authorized") + .unwrap() + .0 + } else { + body.split_once("SELECT EXISTS (SELECT 1 FROM") + .unwrap() + .1 + .split_once(") INTO authorized") + .unwrap() + .0 + }; + let query = format!("EXPLAIN (FORMAT JSON) SELECT 1 FROM{scan}"); + let pool = fixture.database.runtime_config.build_pool().unwrap(); + let mut client = pool.get_for_test().await.unwrap(); + let tx = client.transaction().await.unwrap(); + select_profile(&tx).await; + tx.query_one( + "SELECT set_config('registry.membership_probe', $1, true)", + &[&helper.name], + ) + .await + .unwrap(); + let plan: Value = tx.query_one(&query, &[&MEMBER_KEY]).await.unwrap().get(0); + let index_ddl = fixture + .registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == "entity.membership.membership.key-index") + .unwrap(); + let index = index_ddl.sql.split('"').nth(1).unwrap(); + fn index_node<'a>(node: &'a Value, index: &str) -> Option<&'a Value> { + if node["Index Name"] == index { + return Some(node); + } + node["Plans"] + .as_array()? + .iter() + .find_map(|child| index_node(child, index)) + } + let node = index_node(&plan[0]["Plan"], index).unwrap_or_else(|| panic!("{plan}")); + println!( + "membership {} plan: {}", + if lock { "lock" } else { "probe" }, + node + ); + tx.rollback().await.unwrap(); + drop(client); + fixture.database.cleanup().await; +} diff --git a/crates/registry-breg/tests/task_grant_row_findings.rs b/crates/registry-breg/tests/task_grant_row_findings.rs index a59c1622f6..ee00efc0d8 100644 --- a/crates/registry-breg/tests/task_grant_row_findings.rs +++ b/crates/registry-breg/tests/task_grant_row_findings.rs @@ -148,10 +148,8 @@ fn membership_bound_task_grant_profile_draws_no_finding() { membership_fixture::compile(&source).expect("membership-bound task-grant profile compiles"); assert_eq!(unbound_paths(®istry), Vec::::new()); - source["accessProfiles"]["member"]["permissions"]["records"][0] - .as_object_mut() - .expect("record permission object") - .remove("membershipBoundaries"); + source["accessProfiles"]["member"]["permissions"]["records"][0]["rowBoundaries"] = + serde_json::json!("unrestricted"); let registry = membership_fixture::compile(&source).expect("unbound task-grant profile compiles"); assert_eq!( diff --git a/crates/registry-breg/tests/value_type_consistency.rs b/crates/registry-breg/tests/value_type_consistency.rs index 10d4837096..4f99073912 100644 --- a/crates/registry-breg/tests/value_type_consistency.rs +++ b/crates/registry-breg/tests/value_type_consistency.rs @@ -62,7 +62,7 @@ fn project_source(definition: Value, use_site: &str) -> Value { json!({"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "set-value", "operations": ["invoke"], @@ -339,7 +339,7 @@ fn module_host(with_action_permission: bool) -> RegistryProject { source["accessProfiles"] = json!({"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "set-value", "operations": ["invoke"], diff --git a/crates/registry-breg/tests/wasm_handler_admission.rs b/crates/registry-breg/tests/wasm_handler_admission.rs index 0c20619fba..d4e54cee58 100644 --- a/crates/registry-breg/tests/wasm_handler_admission.rs +++ b/crates/registry-breg/tests/wasm_handler_admission.rs @@ -112,7 +112,7 @@ fn wasm_project() -> Value { }] } }}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"actions":[{ "action":"register-person","operations":["invoke"], "targets":[{"recordType":"person","rowBoundaries":"unrestricted"}], diff --git a/crates/registry-bregctl/src/action_handler_test.rs b/crates/registry-bregctl/src/action_handler_test.rs index ae1e2995a2..fe41dd2d4f 100644 --- a/crates/registry-bregctl/src/action_handler_test.rs +++ b/crates/registry-bregctl/src/action_handler_test.rs @@ -769,7 +769,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] permissions: actions: - action: register-person diff --git a/crates/registry-bregctl/src/check.rs b/crates/registry-bregctl/src/check.rs index a0386cd661..a3ecbcc67e 100644 --- a/crates/registry-bregctl/src/check.rs +++ b/crates/registry-bregctl/src/check.rs @@ -1782,7 +1782,7 @@ fn action_for(code: &str, severity: Severity) -> &'static str { "breg.disclosure.derived-reads-unreadable-source" => "Grant the profile get on the record type the derived SQL reads, with only its link fields readable and the rowBoundaries of the profile's grant on the record type that owns the derived field. Or remove the derived field from the profile.", "breg.disclosure.derived-reads-source-boundary" => "Give the profile's grant on the record type the derived SQL reads the same rowBoundaries as its grant on the record type that owns the derived field, and no requiredPurposes unless they include every purpose that grant requires. Or remove the derived field from the profile.", "breg.disclosure.derived-reads-other-owner-rows" => "Read the record type that owns the derived field once, in the top-level FROM, with its own id as the key, and group or pick DISTINCT ON by nothing or by that id. A read path reader may instead read that record type under the rowBoundaries and requiredPurposes of its grant on the path's root. Or remove the derived field from the profile.", - "breg.disclosure.derived-reads-withheld-source-rows" => "Accept this finding if the derived value should leave out the rows the record condition, membershipBoundaries or requireConsent hides, or that rowBoundaries hide from a subquery that refers to no column of the row. Otherwise add the profile to exemptProfiles of the condition, link the subquery to the row, or remove the derived field from the profile.", + "breg.disclosure.derived-reads-withheld-source-rows" => "Accept this finding if the derived value should leave out the rows the record condition, a membership entry in rowBoundaries or requireConsent hides, or that rowBoundaries hide from a subquery that refers to no column of the row. Otherwise add the profile to exemptProfiles of the condition, link the subquery to the row, or remove the derived field from the profile.", "breg.disclosure.row-boundary-withheld-field" => "Bound the profile's rows by a field no condition withholds from it, or add the profile to exemptProfiles.", "breg.disclosure.membership-boundary-withheld-field" => "Bound the profile's rows by a membership on a field no condition withholds from it, or add the profile to exemptProfiles.", "breg.disclosure.consent-boundary-withheld-field" => "Point requireConsent on at a field no condition withholds from the profile, or add the profile to exemptProfiles.", @@ -2060,7 +2060,7 @@ mod tests { assert_ne!(action, REVIEW_FINDING, "{code}"); for setting in [ "rowBoundaries", - "membershipBoundaries", + "a membership entry in rowBoundaries", "requireConsent", "exemptProfiles", ] { diff --git a/crates/registry-bregctl/src/consent_module/module.yaml b/crates/registry-bregctl/src/consent_module/module.yaml index 560f9108d6..a57d84de80 100644 --- a/crates/registry-bregctl/src/consent_module/module.yaml +++ b/crates/registry-bregctl/src/consent_module/module.yaml @@ -38,6 +38,7 @@ recordTypes: - {id: data-life, type: string, maximumLength: 80, classification: public} - {id: description, type: text, maximumLength: 4000, required: true, classification: public} __SUBJECT__-consent-link: + membership: {key: subject, principal: principal, active: active} primaryDataset: consent route: __SUBJECT__-consent-links mutationMode: mutable diff --git a/crates/registry-bregctl/src/consent_module/profiles.yaml b/crates/registry-bregctl/src/consent_module/profiles.yaml index c7993be117..9ec1ee0af5 100644 --- a/crates/registry-bregctl/src/consent_module/profiles.yaml +++ b/crates/registry-bregctl/src/consent_module/profiles.yaml @@ -4,9 +4,8 @@ __SUBJECT__-consent-self: permissions: records: - recordType: __SUBJECT__-consent-decision - rowBoundaries: unrestricted - membershipBoundaries: - - {field: subject, membershipRecordType: __SUBJECT__-consent-link, membershipKeyField: subject, principalField: principal, activeField: active} + rowBoundaries: + - {field: subject, membership: __SUBJECT__-consent-link} operations: [get, list] readableFields: [subject, notice, clause, recipient, purpose, scope, decision, effective-at, expires-at, channel] - recordType: __SUBJECT__-consent-link diff --git a/crates/registry-bregctl/src/data_lifecycle.rs b/crates/registry-bregctl/src/data_lifecycle.rs index 5ef8a47983..8839d6ffa4 100644 --- a/crates/registry-bregctl/src/data_lifecycle.rs +++ b/crates/registry-bregctl/src/data_lifecycle.rs @@ -1883,7 +1883,7 @@ mod tests { }}, "accessProfiles": {PROFILE: { "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": ENTITY, "operations": operations, @@ -2881,7 +2881,7 @@ mod tests { }}, "accessProfiles": {PROFILE: { "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": ENTITY, "operations": ["create", "batch", "list"], diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index c92441aa94..28c47d4e9d 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -19090,7 +19090,7 @@ recordTypes: accessProfiles: operator: principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] requiredPurposes: [operations] permissions: records: diff --git a/crates/registry-bregctl/tests/cli.rs b/crates/registry-bregctl/tests/cli.rs index bc6449a62b..1140613ebb 100644 --- a/crates/registry-bregctl/tests/cli.rs +++ b/crates/registry-bregctl/tests/cli.rs @@ -1317,14 +1317,14 @@ fn explain_access_names_membership_constraints_instead_of_unrestricted_rows() { let output = bregctl(&["explain", "access", path(&project)]); assert!(output.status.success(), "{output:?}"); let human = String::from_utf8(output.stdout).unwrap(); - let member = human - .split("profile member") - .nth(1) - .expect("the member profile is explained") - .split("profile steward") - .next() - .unwrap(); - let aligned = member.split_whitespace().collect::>().join(" "); + let aligned = human + .lines() + .skip_while(|line| line.trim() != "profile member") + .skip(1) + .take_while(|line| !line.trim_start().starts_with("profile ")) + .flat_map(str::split_whitespace) + .collect::>() + .join(" "); assert!(aligned.contains("row restrictions (all) governed membership required")); assert!(aligned.contains("membership restrictions (all)")); assert!(aligned.contains("membershipRecordType")); @@ -1847,7 +1847,7 @@ accessProfiles: clerk: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [entry:write] permissions: records: - recordType: entry @@ -1933,7 +1933,7 @@ journeys: - id: list-records recordType: record accessProfile: operator - claims: {principal: data-operator} + claims: {principal: data-operator, scopes: [records:write]} request: {type: list} expect: {outcome: success, status: 200, count: 0} "#; @@ -2219,7 +2219,7 @@ accessProfiles: writableFields: [] household-archiver: principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [household:archive] requiredPurposes: [household-archive] permissions: actions: @@ -7179,7 +7179,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [person:register] permissions: actions: - action: register-person @@ -11624,7 +11624,7 @@ fn encrypted_package_module_bytes() -> Vec { } fn data_package_fixture() -> (TestProject, PathBuf) { - let module_bytes = br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{"record": {"primaryDataset":"data-registry","route":"records","mutationMode":"create-only","batch":{"maximumItems":2,"maximumBytes":400},"fields":[{"id":"code","type":"string","minimumLength":2,"maximumLength":16,"required":true,"classification":"internal"}],"accessProfiles":{"operator": {"principalClaim":"principal","operations":["create","batch","list"],"readableFields":["code"],"writableFields":["code"],"allowDataExport":true, "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}}}"#.to_vec(); + let module_bytes = br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{"record": {"primaryDataset":"data-registry","route":"records","mutationMode":"create-only","batch":{"maximumItems":2,"maximumBytes":400},"fields":[{"id":"code","type":"string","minimumLength":2,"maximumLength":16,"required":true,"classification":"internal"}],"accessProfiles":{"operator": {"principalClaim":"principal","operations":["create","batch","list"],"readableFields":["code"],"writableFields":["code"],"allowDataExport":true, "requiredScopes":["records:write"],"rowBoundaries":"unrestricted"}}}}}"#.to_vec(); let module = parse_module_json(&module_bytes).expect("data module parses"); let module_digest = module_digest(&module); let project = TestProject::from_registry_source( diff --git a/crates/registry-bregctl/tests/explain_contract.rs b/crates/registry-bregctl/tests/explain_contract.rs index cfb95544c1..f157ba59b5 100644 --- a/crates/registry-bregctl/tests/explain_contract.rs +++ b/crates/registry-bregctl/tests/explain_contract.rs @@ -1374,3 +1374,40 @@ fn registered_ctl_report_example_matches_current_actions_report() { "{path:?} differs from current report bytes" ); } + +#[test] +fn access_contract_requires_membership_to_report_an_empty_claim_list() { + let fixture = fixture_path("products/breg/fixtures/organization-membership-access"); + let explanation = explain("access", &fixture); + let schema = load_schema("AccessExplanation"); + let path = "/recordTypes/0/profiles/0"; + let profile = explanation.pointer(path).unwrap(); + assert_eq!(profile["rowBoundaries"], json!([])); + assert!(!profile["membershipBoundaries"] + .as_array() + .unwrap() + .is_empty()); + assert!(schema.is_valid(&explanation)); + + let mut no_membership = explanation.clone(); + no_membership + .pointer_mut(path) + .unwrap() + .as_object_mut() + .unwrap() + .remove("membershipBoundaries"); + assert!(!schema.is_valid(&no_membership)); + + let mut empty_membership = explanation.clone(); + empty_membership.pointer_mut(path).unwrap()["membershipBoundaries"] = json!([]); + assert!(!schema.is_valid(&empty_membership)); + + let mut physical = explanation.clone(); + physical.pointer_mut(path).unwrap()["membershipBoundaries"][0]["membershipTable"] = + json!("physical-table"); + assert!(!schema.is_valid(&physical)); + + let mut unrestricted = explanation; + unrestricted.pointer_mut(path).unwrap()["rowBoundaries"] = json!("unrestricted"); + assert!(!schema.is_valid(&unrestricted)); +} diff --git a/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt b/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt index 67cf00d65c..d38f376003 100644 --- a/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt +++ b/crates/registry-evidence-oid4vci/src/observability/golden-scrape.txt @@ -146,6 +146,7 @@ evidence_oid4vci_request_refusals_total{check="task-grant-scope"} 0 evidence_oid4vci_request_refusals_total{check="task-grant-lifetime"} 0 evidence_oid4vci_request_refusals_total{check="task-grant-status"} 0 evidence_oid4vci_request_refusals_total{check="row-boundary"} 0 +evidence_oid4vci_request_refusals_total{check="membership"} 0 evidence_oid4vci_request_refusals_total{check="ownership"} 0 evidence_oid4vci_request_refusals_total{check="visibility"} 0 evidence_oid4vci_request_refusals_total{check="action-guard"} 0 diff --git a/crates/registry-evidence/src/observability/golden-scrape.txt b/crates/registry-evidence/src/observability/golden-scrape.txt index 89d3c341d6..32d2052afe 100644 --- a/crates/registry-evidence/src/observability/golden-scrape.txt +++ b/crates/registry-evidence/src/observability/golden-scrape.txt @@ -113,6 +113,7 @@ evidence_request_refusals_total{check="task-grant-scope"} 0 evidence_request_refusals_total{check="task-grant-lifetime"} 0 evidence_request_refusals_total{check="task-grant-status"} 0 evidence_request_refusals_total{check="row-boundary"} 0 +evidence_request_refusals_total{check="membership"} 0 evidence_request_refusals_total{check="ownership"} 0 evidence_request_refusals_total{check="visibility"} 0 evidence_request_refusals_total{check="action-guard"} 0 diff --git a/crates/registry-platform-authcommon/src/refusal.rs b/crates/registry-platform-authcommon/src/refusal.rs index 25c2543e81..4397cb25ed 100644 --- a/crates/registry-platform-authcommon/src/refusal.rs +++ b/crates/registry-platform-authcommon/src/refusal.rs @@ -153,6 +153,8 @@ failed_checks! { TaskGrantStatus => "task-grant-status", /// The target row is outside the caller's row boundary. RowBoundary => "row-boundary", + /// The target key failed a membership check. + Membership => "membership", /// The target exists and belongs to another caller. Ownership => "ownership", /// The target is absent or not visible to the caller, and the product does not tell which. @@ -210,6 +212,7 @@ impl FailedCheck { | Self::TaskGrantLifetime | Self::TaskGrantStatus | Self::RowBoundary + | Self::Membership | Self::Ownership | Self::Visibility | Self::ActionGuard => RefusalClass::Admission, @@ -574,8 +577,8 @@ mod tests { #[test] fn the_set_is_closed_unique_and_in_declaration_order() { - assert_eq!(FailedCheck::ALL.len(), 45); - assert_eq!(FailedCheck::COUNT, 45); + assert_eq!(FailedCheck::ALL.len(), 46); + assert_eq!(FailedCheck::COUNT, 46); let mut seen = std::collections::HashSet::new(); for (index, check) in FailedCheck::ALL.iter().enumerate() { assert_eq!(*check as usize, index); @@ -636,6 +639,7 @@ mod tests { ("TaskGrantLifetime", "task-grant-lifetime"), ("TaskGrantStatus", "task-grant-status"), ("RowBoundary", "row-boundary"), + ("Membership", "membership"), ("Ownership", "ownership"), ("Visibility", "visibility"), ("ActionGuard", "action-guard"), @@ -697,6 +701,7 @@ mod tests { (FailedCheck::TaskGrantLifetime, Admission), (FailedCheck::TaskGrantStatus, Admission), (FailedCheck::RowBoundary, Admission), + (FailedCheck::Membership, Admission), (FailedCheck::Ownership, Admission), (FailedCheck::Visibility, Admission), (FailedCheck::ActionGuard, Admission), diff --git a/crates/registry-rstack-dev/src/products.rs b/crates/registry-rstack-dev/src/products.rs index f74ab1f501..06e437dffd 100644 --- a/crates/registry-rstack-dev/src/products.rs +++ b/crates/registry-rstack-dev/src/products.rs @@ -3633,6 +3633,89 @@ mod tests { sync::mpsc, }; + #[test] + fn canonical_facility_schema_people_require_exact_scopes_and_assignments() { + const JOURNEY: &str = "bounded-facility-and-batch-validation"; + const NORTH: &str = "facility-operator"; + const SOUTH: &str = "facility-south-operator"; + const FIRST: &str = "create-north-district-facility"; + const CONCEALED: &str = "south-district-claim-cannot-see-north-record"; + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/breg/acceptance/facility") + .canonicalize() + .unwrap(); + let mut plan = plan::load(&root).unwrap().plan; + + let bindings = schema_people(&root, &plan, true).unwrap(); + assert_eq!( + bindings + .iter() + .map(|binding| ( + binding.journey.as_str(), + binding.step.as_str(), + binding.person.as_str(), + )) + .collect::>(), + [ + (JOURNEY, FIRST, NORTH), + (JOURNEY, "get-north-district-facility", NORTH), + (JOURNEY, "rename-north-district-facility", NORTH), + (JOURNEY, "list-north-district-facilities", NORTH), + (JOURNEY, CONCEALED, SOUTH), + (JOURNEY, "batch-refuses-out-of-bounds-installation", NORTH), + ], + ); + for (alias, district) in [(NORTH, "north-district"), (SOUTH, "south-district")] { + let person = &plan.people[alias]; + assert_eq!(person.subject, "synthetic-facility-operator"); + assert_eq!(person.client, "facility-operator"); + let grant = &person.grants[&Product::Breg]; + assert_eq!(grant.scopes, ["registry:facility:operate"]); + assert_eq!(grant.claims["administrative_boundaries"], json!([district])); + } + + let assert_refused = |plan: &Plan, step| { + let Err(refusal) = schema_people(&root, plan, true) else { + panic!("expected the facility schema assignment to fail for {step}"); + }; + assert_eq!( + refusal.to_string(), + format!( + "dev.yaml /schemaTestPeople/{JOURNEY}/{step}: A BReg fixture step must resolve to exactly one test person with matching profile, scopes, and purpose. Next: Add or update a matching BReg grant, or select the matching person in schemaTestPeople." + ) + ); + }; + for (alias, step) in [(NORTH, FIRST), (SOUTH, CONCEALED)] { + let mut plan = plan::load(&root).unwrap().plan; + let grant = plan + .people + .get_mut(alias) + .unwrap() + .grants + .get_mut(&Product::Breg) + .unwrap(); + let scopes = std::mem::take(&mut grant.scopes); + assert_refused(&plan, step); + + let grant = plan + .people + .get_mut(alias) + .unwrap() + .grants + .get_mut(&Product::Breg) + .unwrap(); + grant.scopes = scopes; + grant.scopes.push("registry:facility:extra".to_owned()); + assert_refused(&plan, step); + } + + plan.schema_test_people + .get_mut(JOURNEY) + .unwrap() + .remove(CONCEALED); + assert_refused(&plan, CONCEALED); + } + #[test] fn the_project_copy_is_private_to_the_owner() { let scratch = tempfile::tempdir().unwrap(); diff --git a/docs/site/src/content/docs/configure/breg-access.mdx b/docs/site/src/content/docs/configure/breg-access.mdx index bc4fb718e2..d714ae538a 100644 --- a/docs/site/src/content/docs/configure/breg-access.mdx +++ b/docs/site/src/content/docs/configure/breg-access.mdx @@ -354,23 +354,26 @@ permission, with the reason `required-filters`, and still exports its `get`. ## Require a current membership -A row boundary works when the Record carries the claim value it is compared with. Sometimes the -right to read follows an affiliation that changes over time: a facility belongs to an -organisation, and whoever is currently a member of that organisation may read it. Copying members -into tokens would leave access in place until each token expired. - -`membershipBoundaries` on a record permission puts that rule into the registry. Each entry names -the Record's reference `field`, a `membershipRecordType`, and that type's `membershipKeyField`, -`principalField`, and `activeField`. A row is readable only while a membership Record exists with -the same key, the caller's verified principal, and `active: true`. Memberships are ordinary -Records that a separate steward profile creates and deactivates. A request that starts after a -deactivation commits no longer sees the Records; a read already running may finish. Historical -reads compare against current memberships too, so a past membership cannot restore access. - -A facility stores `organization`, a reference to an `organization` Record type. -A separate `membership` Record type stores an `organization` reference, a string `principal`, and a Boolean `active`. -Its optional descriptive fields can remain private. -Add the boundary to the facility's read grant: +Use a membership boundary when access follows an affiliation that can change. +For example, a facility belongs to an organisation, and its current members may read it. + +Declare the membership fields once on the Record type that holds the affiliation. +In the example, both the facility and the membership Record store an `organization` +reference to the same Record type. Add this declaration under the membership Record type. + +```yaml +recordTypes: + membership: + membership: + key: organization + principal: principal + active: active +``` + +`key` names the stored reference. `principal` names a stored plaintext string or text field. +`active` names a stored Boolean field. Add an entry to `rowBoundaries` on each grant you +want to restrict. The entry's `field` names the protected Record's reference, and +`membership` names the Record type with the declaration. ```yaml accessProfiles: @@ -382,7 +385,9 @@ accessProfiles: permissions: records: - recordType: facility - rowBoundaries: unrestricted + rowBoundaries: + - field: organization + membership: membership operations: - get - list @@ -400,88 +405,121 @@ accessProfiles: lookups: - selector: label valueOrigin: request - membershipBoundaries: - - field: organization - membershipRecordType: membership - membershipKeyField: organization - principalField: principal - activeField: active ``` The `label` lookup selector must already be declared on the facility Record type. -The two organisation fields must be stored references to the same Record type. -`principalField` must be a stored string or text field and `activeField` a stored Boolean. -Only active-lifecycle membership rows with `active: true` and an exact match to the profile's verified principal grant access. -A missing membership, null value, inactive membership, or other principal does not. -Configure a stable identity claim from a trusted issuer, and do not accept caller-submitted principal values as authority. - -Every listed membership boundary and ordinary `rowBoundaries` predicate must hold. -Declare `rowBoundaries` explicitly even when membership is the only row restriction; `rowBoundaries: unrestricted` adds no direct claim predicate and leaves the membership checks in force. -Up to eight membership boundaries are supported. -The declared fields are authorisation inputs, not an additional readable-field grant. -The root profile must satisfy the membership Record type's mandatory scopes and purposes. -The current boundary does not carry additional direct row requirements from that source, so the compiler rejects a membership Record type with mandatory `rowBoundaries`. - -The organisation membership access example project in the repository (at your release tag) holds the complete authored model, including separate steward grants and an index on principal, organisation, and active status. -Run `bregctl check` against that directory to compile it. -The same boundary compiles for facility and document registries without new server code. - -{/* Evidence: crates/registry-breg/src/contract.rs MembershipBoundarySource; - crates/registry-breg/src/membership.rs breg.access.membership-limit, breg.access.membership-key-type, - breg.access.membership-principal-type, breg.access.membership-active-type, - breg.access.membership-source-row-requirement; - crates/registry-breg/tests/membership_access.rs membership_boundaries_compile_for_distinct_registry_models; +The maintained synthetic organisation membership fixture in the repository contains the full +declarations and separate grants for the `member` and `steward` profiles. +To create a membership Record or set its `active` field to `false`, use a profile with a +write grant on the membership Record type for the requested operation and fields. The +fixture's `steward` profile grants both operations. Use the fixture from the +version you are running to check the complete project with `bregctl check`. + +If you have an older project with `membershipBoundaries`, move the source field names into +the Record type's `membership` declaration and replace the old entries with `field` and +`membership` entries in `rowBoundaries`. Claim predicates can share the same list. +Every entry must hold. You can declare up to eight distinct membership entries per grant, +including entries expanded from a row boundary set. + +An active-lifecycle membership Record must match the key and the verified principal exactly, +with `active: true`. A missing match or a null key grants no access. Set `principalClaim` to +a stable identity claim from a trusted issuer. If the profile requires neither scopes nor +requester clients, it must use `sub` for membership. A profile that admits tokens without +scopes cannot write to a Record type that declares membership. An open profile's write target +needs a membership boundary or a claim boundary on its `principalClaim`. + +The grant's profile must satisfy the membership Record type's mandatory scopes and purposes. +Membership inputs remain private unless a separate field grant exposes them. +The compiler refuses membership entries in mandatory access requirements and refuses a +membership source with mandatory row predicates, membership boundaries, or incoming +relationship read paths. + +{/* Evidence: crates/registry-breg/src/contract.rs, MembershipDeclarationSource, MembershipRowBoundarySource; + crates/registry-breg/src/membership.rs, validate_declaration, validate_entries, validate_write_admission, source_predicate; + crates/registry-breg/tests/membership_authoring.rs, claim_and_membership_entries_share_one_row_boundaries_list, + membership_entries_are_limited_and_unique_after_set_expansion, open_profiles_with_membership_must_use_sub, + a_scopeless_profile_with_requester_clients_cannot_write_membership_records, + a_membership_entry_in_access_requirements_is_refused; + crates/registry-breg/tests/membership_access.rs, membership_boundaries_is_refused_with_its_replacement_named; products/breg/fixtures/organization-membership-access/registry.yaml. */} -Membership boundaries apply to reads only: get, lookup, list, count, snapshot, and revisions. -A record grant with a membership boundary cannot also grant writes. -Action and Proposal grants do not accept `membershipBoundaries` and do not inherit membership checks from read grants. -Give record mutations and membership administration to a separate, explicitly authorised steward profile. -Cursor replay on a read re-evaluates live membership, and a read grant never authorises a mutation or its replay. -Spatial bbox permissions use a separate authority role and cannot currently be combined with membership boundaries; ordinary reads of facilities remain available under the membership profile. +You can use membership with these grants: -Membership profiles can protect the root of a relationship read path. -A related Record type's membership rules cannot silently be bypassed by targeting it through a separate root grant, so the compiler rejects such target permissions. -Membership sources must remain leaf Record types without their own membership boundaries or incoming relationship read paths, which prevents recursive row-security policies. +- Record get, lookup, list, count, snapshot, and revisions. Count still requires `allowCount`. +- Record Create, Patch, Tombstone, and Batch. +- Immediate Action targets and Proposal Start and lifecycle targets. Put the boundary on + the target grant. An ordinary Record read grant supplies no Action or Proposal authority. -{/* Evidence: crates/registry-breg/src/membership.rs breg.access.membership-read-only, - breg.access.membership-read-path-target, breg.access.membership-source-recursive, - breg.access.membership-spatial-unsupported; - crates/registry-breg/tests/membership_access.rs membership_boundaries_refuse_unenforced_authority_paths. */} +The compiler refuses membership on Import, spatial bounding-box queries, Action grants used +by hooks, and grants used by timers. Use separately authorised grants for those paths. +A membership boundary can protect the root of a relationship read. The compiler refuses a +relationship read path through or to a Record type with membership-filtered permissions. +Use a direct read of that Record type. -### Revocation and history +{/* Evidence: crates/registry-breg/src/membership.rs, validate_target_entries, refuse_membership_write; + crates/registry-breg/tests/membership_access.rs, membership_boundaries_refuse_unenforced_authority_paths; + crates/registry-breg/tests/membership_authoring.rs, import_grants_refuse_membership_entries, + membership_entries_are_incompatible_with_spatial_queries, + production_admits_a_membership_bound_immediate_action_target, + production_admits_membership_on_proposal_start_and_lifecycle_targets, + a_hook_cannot_use_an_action_grant_with_membership, a_timer_cannot_use_an_action_grant_with_membership. */} -Authorisation queries read current membership Records in PostgreSQL. -A new request issued after a membership deactivation commits is denied or returns an empty authorised collection, including counts, lookups, and cursor continuations. -An already running read can finish from the statement snapshot that preceded revocation. -There is no token membership cache, external authorisation service, or registry-wide authorisation lock. +### Revocation and history -Snapshots and revisions compare the retained Record's organisation with current memberships. -The historical membership state cannot restore access, and deactivation removes access to those historical Records as well. -Moving a facility to another organisation does not by itself remove access to its older revisions from members of the previous organisation. -This preserves the ordinary historical row-boundary contract, and current-owner-only history is a different policy that this feature does not imply. -Erased history remains unavailable. +Authorisation checks use current membership Records in PostgreSQL. After a deactivation commits, +a new request loses access through that membership, including when it continues a list cursor. +An already running read can finish from its earlier statement snapshot. -{/* Evidence: crates/registry-breg/tests/postgres_membership_access.rs - real_postgres_membership_reads_recheck_live_membership_and_hide_processing_inputs. */} -{/* TODO[evidence]: the claim that moving a facility keeps older-revision access for previous members is not asserted by a test I could name. */} +Snapshots and revisions compare the retained Record's key with current memberships. +Erased history remains unavailable. If the caller loses access to a Proposal, the history response +can still return the Record revision while concealing its Proposal link. -### How PostgreSQL enforces it +A Proposal's target membership also applies when filtering its list, disclosing review context +and saved documents, and admitting answers, commands, and attachments. Review context checks +current Record authority and membership for each frozen subject. -PostgreSQL enforces the predicate through generated `SECURITY INVOKER` functions and forced row-level security. -Each generated PL/pgSQL function saves the prior authorisation context, enables only its matching membership probe, and restores the context before returning. -Its exception block rolls back the local context on errors. -It does not grant direct membership endpoints or derived views access to private membership Records. -The logical source views keep `security_invoker`, so the caller's row-level security policies decide every read through them; they are not barrier views. -No additional database role or RLS bypass is required. -PostgreSQL 17 remains the minimum for this surface, and other enabled features can require a newer supported version. +{/* Evidence: crates/registry-breg/tests/postgres_membership_access.rs, + real_postgres_membership_reads_recheck_live_membership_and_hide_processing_inputs; + crates/registry-breg/tests/postgres_proposal.rs, proposal_list_correlates_membership_filtered_page_with_its_journal; + crates/registry-breg/tests/postgres_proposal_security.rs, + review_context_checks_each_frozen_membership_and_saved_document, + submitted_create_membership_controls_attachments_answers_and_commands, + record_history_rechecks_proposal_membership_without_hiding_the_revision. */} -Use `bregctl explain access` to inspect the expanded membership boundary alongside its scopes, purposes, and ordinary row boundaries. -Compiler diagnostics identify the unsupported field or grant and describe the supported alternative. +### How PostgreSQL enforces it -{/* Evidence: crates/registry-breg/src/membership.rs; - crates/registry-breg/tests/postgres_membership_access.rs - real_postgres_membership_reads_recheck_live_membership_and_hide_processing_inputs. */} +PostgreSQL enforces the read predicate through generated `SECURITY INVOKER` functions and +forced row-level security. Each function temporarily enables only the matching membership probe +and restores the prior authorisation context. The check grants no direct access to membership +Records or their private fields. Source views use `security_invoker`. BReg generates a partial +index on key and principal for active membership rows. PostgreSQL 17 remains the minimum +for this surface. + +For membership-bounded Record writes, immediate Actions, and caller Apply, BReg takes shared +locks on the matching membership rows and checks the required keys in the write transaction. +When a write moves a Record between keys, the caller needs membership for both the stored and +proposed keys. If deactivation wins the lock first, the write can lose admission. If the write +locks the membership first, deactivation waits. A lock timeout returns `503 service.unavailable`. +Membership refusal uses the same concealment or generic precondition response as the equivalent +claim boundary. System Apply uses the pinned system grant for the frozen submission and has +no caller membership to lock. + +Use `bregctl explain access` to inspect the expanded predicate. Its output retains the +`membershipBoundaries` property and can show an empty claim-boundary array for a +membership-only grant. + +{/* Evidence: crates/registry-breg/src/generated_ddl.rs, security_invoker; + crates/registry-breg/src/membership.rs, source_guard, source_predicate, index_statement; + crates/registry-breg/src/mutation/membership.rs, verify_locked, authorize_proposed; + crates/registry-breg/src/postgres/proposal_context.rs, locks_membership, SystemApplyAuthority; + crates/registry-breg/tests/support/membership_write_journeys.rs, + record_write_first_makes_the_removal_wait, record_removal_first_refuses_the_write, + a_lock_wait_past_lock_timeout_answers_service_unavailable, + membership_refusals_match_the_claim_boundary_answer_at_each_step, + proposal_membership_refusals_match_the_claim_boundary_answer, + proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted, + automatic_worker_keeps_system_authority_and_human_apply_has_a_source_lock; + products/breg/contracts/explain/AccessExplanation.schema.json, membershipBoundaries. */} ## Require the subject's consent diff --git a/docs/site/src/content/docs/security/breg.mdx b/docs/site/src/content/docs/security/breg.mdx index 898775d3f2..417863fcc6 100644 --- a/docs/site/src/content/docs/security/breg.mdx +++ b/docs/site/src/content/docs/security/breg.mdx @@ -216,13 +216,14 @@ A request batch audits both items as not available, and the metric still counts a_declared_unresolved_problem_logs_a_cause_only_when_a_404_does_not_match_it. */} BReg counts each request it refuses by the check that refused it, in `breg_request_refusals_total{check}` on the private metrics listener. -The `check` label is a closed set of 45 names, every one published at zero, and no caller value becomes a label. +The `check` label is a closed set of 46 names, every one published at zero, and no caller value becomes a label. Each refusal also writes one `request refused` log line with `failed_check` and the request's trace id when it has one, at most five lines per check per minute, with `suppressed` counting what a window held back. In production, a request that BReg answers `404 resource.not-found` because the caller may not see the target reads the same to the caller whatever the reason. The operator can tell the reasons apart: the counter holds the request under the rule that refused it, for example `scope`, `purpose`, `requester-client`, `row-boundary`, `task-grant-binding`, `disclosure` or `visibility`. A refused write the engine answers with `write.outside-boundary` counts under `row-boundary`. Once the route admits the caller, BReg counts a missing or inaccessible Proposal under `visibility`. A successful Proposal review-context batch answers `200` and each concealed item counts once. +An observed membership denial counts under `membership`, including when caller Apply returns the generic `412 precondition.failed`. A `412` for a stale version and a request for an unknown route are not counted. A failed field guard counts under `action-guard`, also when it answers the generic `412`. A refusal on the `scope` check also names the claim that carries scopes, the scope the operation needs and the access profile, each as the configuration or package declares it. @@ -238,7 +239,89 @@ The audit journal's `refusalReason` stays the three values it lists below. crates/registry-breg/tests/postgres_proposal_security.rs, proposal_target_refusals_are_identical_across_routes_and_postures; crates/registry-breg/tests/postgres_proposal.rs, review_context_projects_an_omitted_optional_input_as_null; - crates/registry-breg/src/mutation.rs, MutationError::failed_check. */} + crates/registry-breg/src/mutation.rs, MutationError::failed_check; + crates/registry-platform-authcommon/src/refusal.rs, FailedCheck::COUNT; + crates/registry-breg/tests/support/membership_write_journeys.rs, + membership_refusals_match_the_claim_boundary_answer_at_each_step, + proposal_membership_refusals_match_the_claim_boundary_answer, + membership_diagnostics_count_only_observed_denials. */} + +### Membership boundaries + +A membership boundary limits a grant to target keys for which the authenticated principal has an active membership Record. +To create or deactivate membership Records, the caller needs a profile with a write grant on the membership Record type for the requested operation and fields. +The selected profile also governs which fields the caller can see and which disclosure conditions apply. + +BReg checks current membership when it reads a Record or its history. +A Proposal's start and lifecycle grants can each limit their targets by membership. +BReg checks current target membership when it lists or reads Proposals and when it admits commands, answers, and attachments. +Review context and saved review documents also require current Record disclosure for the Records in the frozen context. + +Record writes, immediate Actions, and caller Apply hold shared locks on the memberships they rely on through the write transaction. +A write that moves a Record to another key must satisfy the applicable membership boundary for both keys. +If removal commits first, the write cannot use the revoked membership. +If the write has already locked the membership, removal waits. +Submitting a Proposal does not reserve membership for later caller Apply. +Automatic Apply uses its own pinned system grant. + +{/* Evidence: crates/registry-breg/src/mutation/membership.rs, + MembershipLocks, RecordMembership; + crates/registry-breg/src/mutation/proposal.rs, + lock_apply_memberships; + crates/registry-breg/src/generated_ddl.rs, + the_membership_lock_helper_is_volatile_and_takes_for_share; + crates/registry-breg/tests/membership_authoring.rs, + production_admits_membership_on_proposal_start_and_lifecycle_targets; + crates/registry-breg/tests/postgres_membership_access.rs, + real_postgres_membership_reads_recheck_live_membership_and_hide_processing_inputs; + crates/registry-breg/tests/postgres_proposal.rs, + proposal_list_correlates_membership_filtered_page_with_its_journal; + crates/registry-breg/tests/postgres_proposal_security.rs, + review_context_checks_each_frozen_membership_and_saved_document, + submitted_create_membership_controls_attachments_answers_and_commands; + crates/registry-breg/tests/support/membership_write_journeys.rs, + record_write_first_makes_the_removal_wait, record_removal_first_refuses_the_write, + action_write_first_makes_the_removal_wait, action_removal_first_refuses_the_write, + proposal_write_first_makes_the_removal_wait, proposal_removal_first_refuses_the_write, + proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted, + automatic_worker_keeps_system_authority_and_human_apply_has_a_source_lock. */} + +### Membership-bound writes + +A membership-bound write uses the verified principal from the selected access profile and the active +membership rows for the configured source Record type. +When an open profile permits a membership-bound write, the project must bind the principal to `sub`. +The operator controls issuer and claim mapping, and the reviewed project defines which separately +authorized writes may change the source Records. +A caller's proposed target key does not supply membership authority. +The database policies and locks described here constrain requests through BReg. +The runtime database credential remains inside the trust boundary described above. + +For Record mutations, immediate Actions and caller Apply, the write transaction acquires source +membership locks before locking target rows. +It checks membership against the keys the operation uses, including proposed keys for a move. +A committed removal that wins the source lock is visible to the waiting writer. +A removal that loses the lock waits for the writer to settle. +Caller Apply checks current membership even after a Proposal has been submitted or approved. +The automatic Apply worker runs under its separate system authority. +A hook callback with a claim-bound or membership-bound target grant is refused. + +For a membership-bound immediate Action with S3 attachments, the runtime holds the write fences and +uses a separate session to commit staging metadata before the primary transaction uploads the bytes. +A membership denial before staging makes no storage call. +Reserve database capacity for one additional staging session per runtime pool using this path. +The shared-content attachment and history lock order remains an open invariant (`BREG-SEC-254`). + +{/* Evidence: crates/registry-breg/src/membership.rs, validate_write_admission; + crates/registry-breg/src/mutation/membership.rs, collect, acquire; + crates/registry-breg/src/mutation/action.rs, stage_membership_action_attachments, hook_target_authority; + crates/registry-breg/src/mutation/proposal.rs, lock_apply_memberships; + crates/registry-breg/tests/support/membership_write_journeys.rs, + record_removal_first_refuses_the_write, record_write_first_makes_the_removal_wait, + action_removal_first_refuses_the_write, proposal_removal_first_refuses_the_write, + proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted, + automatic_worker_keeps_system_authority_and_human_apply_has_a_source_lock, + a_membership_refusal_leaves_s3_staging_unchanged. */} ### Public check export @@ -336,7 +419,8 @@ identifier, the Proposal identifier and the submission version. The member discloses a Proposal identifier only under Proposal read authorization. BReg resolves the link from the Proposal's stored application results, then keeps it only when the selected access profile could read that Proposal: the same grant, ownership and row-boundary check a -Proposal read applies, run by the same code. +Proposal read applies, including current target membership. +When membership fails, BReg can still return the revision under the separate history grant. A profile that reads the Record's history but holds no `get` grant on the Proposal, a caller who does not own a caller-owned Proposal, a caller whose row boundaries exclude a target, a caller under a task grant and a standing agent all receive the revision without the member. @@ -382,6 +466,7 @@ The link has these known limits: record_history_omits_the_proposal_from_a_profile_without_a_proposal_grant, record_history_omits_the_proposal_when_ownership_does_not_match, record_history_omits_the_proposal_outside_the_proposal_row_boundary, + record_history_rechecks_proposal_membership_without_hiding_the_revision, record_history_never_names_the_proposal_to_a_task_grant_caller, record_history_never_names_the_proposal_to_a_standing_agent, record_history_reads_the_link_while_another_session_locks_the_proposal_row, diff --git a/products/breg/AGENTS.md b/products/breg/AGENTS.md index d9150593bf..c37a3acbe5 100644 --- a/products/breg/AGENTS.md +++ b/products/breg/AGENTS.md @@ -42,12 +42,12 @@ The build posture never enters the package. A development-only property of a pac compound identifiers, concrete entity, route, and Rust-type names such as `group-membership` or `GroupMembership`, from `registry-breg`, `registry-bregctl`, and `registry-breg-client` production source. It does not -forbid the bare words `membership` or `memberships`: `membershipBoundaries` is -a generic, configured read-boundary mechanism, a one-hop join predicate over a -configured entity, key field, principal field, and active flag, restricted to -`get`, `lookup`, `list`, `revisions`, and `snapshot`, with at most eight -boundaries per access profile (`crates/registry-breg/src/membership.rs`, -`crates/registry-breg/src/contract.rs`). +forbid the bare words `membership` or `memberships`. A Record type declares +its membership key, principal and active fields under `membership`. A +`rowBoundaries` entry can require current membership through a stored +reference. The compiled one-hop predicate supports `get`, `lookup`, `list`, +`revisions` and `snapshot` with at most eight membership entries per grant +(`crates/registry-breg/src/membership.rs`, `crates/registry-breg/src/contract.rs`). Domain-specific compounds such as `group-membership` remain forbidden. Changing the blocklist is a boundary decision: record it in this file. diff --git a/products/breg/CHANGELOG.md b/products/breg/CHANGELOG.md index 5f688e05c8..eac4ad6ef9 100644 --- a/products/breg/CHANGELOG.md +++ b/products/breg/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- Record Create, Patch, Tombstone, and Batch grants and immediate Action targets accept membership entries. A bounded write commits only while an active membership names the caller for each required key. A lock timeout returns `503 service.unavailable`. A writer may acquire a shared membership lock while a removal waits. +- Generate a partial index over the key and principal of active membership records. A successor package builds it for existing membership declarations. +- Grant the runtime role column-level row-lock privilege only where a compiled write grant needs to lock membership records and table-level update privilege is absent. A successor package reconciles the grant. +- BREAKING: Declare membership fields once on the membership Record type and use membership entries in `rowBoundaries`. Migration: Add `membership: {key, principal, active}` to the membership Record type and replace each authored `membershipBoundaries` entry with `{field, membership}` in `rowBoundaries`. The AccessExplanation schema accepts an empty claim array only when membership boundaries are present. +- Check membership and open-profile write admission with `breg.access.membership-import-unsupported`, `breg.access.membership-access-requirement-unsupported`, `breg.access.membership-hook-unsupported`, `breg.access.membership-timer-unsupported`, `breg.access.open-write-without-principal-boundary`, `breg.access.scopeless-membership-source-write`, and `breg.access.open-membership-principal-not-sub`. +- Proposal Start and lifecycle target grants accept membership entries in `rowBoundaries`. Caller Apply holds shared membership locks through the write. Proposal reads and lifecycle operations check current membership for the targets they authorize. +- Observed membership refusals count under `membership` in `breg_request_refusals_total{check}` and in the refusal log. Generic precondition responses retain their existing body in both postures. + ## 0.49.0 - 2026-12-01 - BREAKING: `bregctl data export` JSONL uses `recordId` and `revisionId` in place of v0.48.0's `recordIdentifier` and `revisionIdentifier`. Migration: Update export file consumers for both keys. Finish an in-progress export with the matching v0.48.0 `bregctl`, serving runtime, and compiled package before upgrading, or start a fresh output and checkpoint pair after upgrading. Convert archived exports on a separate copy to preserve any checkpoint digest. diff --git a/products/breg/acceptance/asset-site-placement/registry.yaml b/products/breg/acceptance/asset-site-placement/registry.yaml index 2baf9236d3..967290ec15 100644 --- a/products/breg/acceptance/asset-site-placement/registry.yaml +++ b/products/breg/acceptance/asset-site-placement/registry.yaml @@ -217,7 +217,7 @@ "asset-operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["asset:manage"], "requiredPurposes": [ "asset-management" ], @@ -308,7 +308,7 @@ }, "site-planner": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["asset:plan"], "requiredPurposes": [ "site-planning" ], diff --git a/products/breg/acceptance/asset-site-placement/tests/journeys.yaml b/products/breg/acceptance/asset-site-placement/tests/journeys.yaml index 66f0278fee..bab216c386 100644 --- a/products/breg/acceptance/asset-site-placement/tests/journeys.yaml +++ b/products/breg/acceptance/asset-site-placement/tests/journeys.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: asset-operator claims: principal: synthetic-asset-operator + scopes: [asset:manage] purpose: asset-management request: type: create @@ -28,6 +29,7 @@ journeys: accessProfile: site-planner claims: principal: synthetic-site-planner + scopes: [asset:plan] purpose: site-planning request: type: get @@ -43,6 +45,7 @@ journeys: accessProfile: site-planner claims: principal: synthetic-site-planner + scopes: [asset:plan] purpose: site-planning request: type: list @@ -55,6 +58,7 @@ journeys: accessProfile: asset-operator claims: principal: synthetic-asset-operator + scopes: [asset:manage] purpose: asset-management request: type: patch @@ -76,6 +80,7 @@ journeys: accessProfile: asset-operator claims: principal: synthetic-asset-operator + scopes: [asset:manage] purpose: asset-management request: type: create @@ -94,6 +99,7 @@ journeys: accessProfile: site-planner claims: principal: synthetic-site-planner + scopes: [asset:plan] purpose: site-planning request: type: get @@ -109,6 +115,7 @@ journeys: accessProfile: site-planner claims: principal: synthetic-site-planner + scopes: [asset:plan] purpose: site-planning request: type: list @@ -121,6 +128,7 @@ journeys: accessProfile: site-planner claims: principal: synthetic-site-planner + scopes: [asset:plan] request: type: get recordCapture: renamed-asset diff --git a/products/breg/acceptance/business/registry.yaml b/products/breg/acceptance/business/registry.yaml index 8bfed90cba..8ff377c63a 100644 --- a/products/breg/acceptance/business/registry.yaml +++ b/products/breg/acceptance/business/registry.yaml @@ -423,7 +423,7 @@ }, "business-registrar": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["business:register"], "requiredPurposes": [ "business-registry" ], diff --git a/products/breg/acceptance/business/tests/journeys.yaml b/products/breg/acceptance/business/tests/journeys.yaml index 1580cd97b2..b9bf555b55 100644 --- a/products/breg/acceptance/business/tests/journeys.yaml +++ b/products/breg/acceptance/business/tests/journeys.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: business-registrar claims: principal: synthetic-business-registrar + scopes: [business:register] purpose: business-registry request: type: create @@ -67,6 +68,7 @@ journeys: accessProfile: business-registrar claims: principal: synthetic-business-registrar + scopes: [business:register] purpose: business-registry request: type: patch @@ -105,6 +107,7 @@ journeys: accessProfile: business-registrar claims: principal: synthetic-business-registrar + scopes: [business:register] request: type: get recordCapture: suspended-business diff --git a/products/breg/acceptance/facility/dev.yaml b/products/breg/acceptance/facility/dev.yaml index 4758d57294..c46cc8a1bd 100644 --- a/products/breg/acceptance/facility/dev.yaml +++ b/products/breg/acceptance/facility/dev.yaml @@ -12,7 +12,7 @@ people: grants: breg: profile: facility-operator - scopes: [] + scopes: [registry:facility:operate] claims: administrative_boundaries: [north-district] registry_actor_kind: human @@ -23,7 +23,7 @@ people: grants: breg: profile: facility-operator - scopes: [] + scopes: [registry:facility:operate] claims: administrative_boundaries: [south-district] registry_actor_kind: human diff --git a/products/breg/acceptance/facility/registry.yaml b/products/breg/acceptance/facility/registry.yaml index 662b706221..594410fba6 100644 --- a/products/breg/acceptance/facility/registry.yaml +++ b/products/breg/acceptance/facility/registry.yaml @@ -413,7 +413,7 @@ "accessProfiles": { "facility-operator": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["registry:facility:operate"], "requiredPurposes": [ "facility-registry" ], diff --git a/products/breg/acceptance/facility/tests/journeys.yaml b/products/breg/acceptance/facility/tests/journeys.yaml index f8c898994d..54b81ae4dc 100644 --- a/products/breg/acceptance/facility/tests/journeys.yaml +++ b/products/breg/acceptance/facility/tests/journeys.yaml @@ -8,8 +8,8 @@ journeys: accessProfile: facility-operator claims: principal: synthetic-facility-operator + scopes: [registry:facility:operate] purpose: facility-registry - scopes: [] directClaims: administrative_boundaries: [north-district] request: @@ -31,8 +31,8 @@ journeys: accessProfile: facility-operator claims: principal: synthetic-facility-operator + scopes: [registry:facility:operate] purpose: facility-registry - scopes: [] directClaims: administrative_boundaries: [north-district] request: @@ -49,8 +49,8 @@ journeys: accessProfile: facility-operator claims: principal: synthetic-facility-operator + scopes: [registry:facility:operate] purpose: facility-registry - scopes: [] directClaims: administrative_boundaries: [north-district] request: @@ -73,8 +73,8 @@ journeys: accessProfile: facility-operator claims: principal: synthetic-facility-operator + scopes: [registry:facility:operate] purpose: facility-registry - scopes: [] directClaims: administrative_boundaries: [north-district] request: @@ -88,8 +88,8 @@ journeys: accessProfile: facility-operator claims: principal: synthetic-facility-operator + scopes: [registry:facility:operate] purpose: facility-registry - scopes: [] directClaims: administrative_boundaries: [south-district] request: @@ -104,8 +104,8 @@ journeys: accessProfile: facility-operator claims: principal: synthetic-facility-operator + scopes: [registry:facility:operate] purpose: facility-registry - scopes: [] directClaims: administrative_boundaries: [north-district] request: diff --git a/products/breg/acceptance/inspection/registry.yaml b/products/breg/acceptance/inspection/registry.yaml index 8a44e04414..b0d643417f 100644 --- a/products/breg/acceptance/inspection/registry.yaml +++ b/products/breg/acceptance/inspection/registry.yaml @@ -310,7 +310,7 @@ "accessProfiles": { "inspection-inspector": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["inspection:manage"], "requiredPurposes": [ "facility-inspection" ], diff --git a/products/breg/acceptance/inspection/tests/journeys.yaml b/products/breg/acceptance/inspection/tests/journeys.yaml index eb83747fca..8afba387f4 100644 --- a/products/breg/acceptance/inspection/tests/journeys.yaml +++ b/products/breg/acceptance/inspection/tests/journeys.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: inspection-inspector claims: principal: synthetic-inspection-inspector + scopes: [inspection:manage] purpose: facility-inspection request: type: create @@ -30,6 +31,7 @@ journeys: accessProfile: inspection-inspector claims: principal: synthetic-inspection-inspector + scopes: [inspection:manage] purpose: facility-inspection request: type: patch @@ -51,6 +53,7 @@ journeys: accessProfile: inspection-inspector claims: principal: synthetic-inspection-inspector + scopes: [inspection:manage] purpose: facility-inspection request: type: get @@ -66,6 +69,7 @@ journeys: accessProfile: inspection-inspector claims: principal: synthetic-inspection-inspector + scopes: [inspection:manage] purpose: facility-inspection request: type: list @@ -78,6 +82,7 @@ journeys: accessProfile: inspection-inspector claims: principal: synthetic-inspection-inspector + scopes: [inspection:manage] purpose: facility-inspection request: type: create @@ -100,6 +105,7 @@ journeys: accessProfile: inspection-inspector claims: principal: synthetic-inspection-inspector + scopes: [inspection:manage] request: type: get recordCapture: closed-inspection diff --git a/products/breg/contracts/explain/AccessExplanation.schema.json b/products/breg/contracts/explain/AccessExplanation.schema.json index c6b3057f19..2371cb0f54 100644 --- a/products/breg/contracts/explain/AccessExplanation.schema.json +++ b/products/breg/contracts/explain/AccessExplanation.schema.json @@ -82,7 +82,7 @@ }, "recordTypes": { "type": "array", - "description": "Per-Record type author inspection. Record grants explicitly report allowCount and render an empty compiled claim-bound row list as unrestricted. Other profile members follow the compiled AccessProfileSource.", + "description": "Per-Record type author inspection. Record grants explicitly report allowCount. A profile with membership and no claim boundaries reports an empty claim list. Other profile members follow the compiled AccessProfileSource.", "items": { "type": "object", "x-registry-passthrough": "EntityAccessExplanation retains compiled authority with inspection-only explicit defaults on its profiles.", @@ -99,44 +99,65 @@ "rowBoundaries", "allowCount" ], + "if": { + "required": [ + "membershipBoundaries" + ] + }, + "then": { + "properties": { + "membershipBoundaries": { + "$ref": "#/$defs/MembershipBoundaries" + }, + "rowBoundaries": { + "type": "array" + } + } + }, + "else": { + "properties": { + "rowBoundaries": { + "oneOf": [ + { + "const": "unrestricted" + }, + { + "type": "array", + "minItems": 1 + } + ] + } + } + }, "properties": { "id": { "$ref": "#/$defs/LocalId" }, "rowBoundaries": { - "description": "Unrestricted means no claim-bound row restriction. Membership and consent boundaries, when present, still apply.", - "oneOf": [ - { - "const": "unrestricted" - }, - { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "additionalProperties": false, - "required": [ - "field", - "claim", - "operator" - ], - "properties": { - "field": { - "type": "string" - }, - "claim": { - "type": "string" - }, - "operator": { - "enum": [ - "equals", - "in" - ] - } - } + "description": "Unrestricted means neither claim nor membership boundaries are present. Consent conditions still apply.", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field", + "claim", + "operator" + ], + "properties": { + "field": { + "type": "string" + }, + "claim": { + "type": "string" + }, + "operator": { + "enum": [ + "equals", + "in" + ] } } - ] + } }, "allowCount": { "type": "boolean" @@ -302,9 +323,12 @@ ], "x-registry-member-names": true }, + "membershipBoundaries": { + "$ref": "#/$defs/MembershipBoundaries" + }, "rowBoundaries": { "type": "array", - "x-registry-passthrough": "The inspector retains the compiler's boundary list exactly; an empty list is the compiled representation of unrestricted row reach." + "x-registry-passthrough": "The inspector retains the claim boundary list. Membership restrictions are carried in membershipBoundaries." } }, "x-registry-passthrough": "bregctl writes each row-reach explanation as the engine holds it; the target Record type, profile, source path, surface, and row boundaries are pinned. Other members follow RowReachExplanation." @@ -751,6 +775,28 @@ } ], "$defs": { + "MembershipBoundaries": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "field", + "membershipRecordType", + "membershipKeyField", + "principalField", + "activeField" + ], + "properties": { + "field": {"$ref": "#/$defs/LocalId"}, + "membershipRecordType": {"$ref": "#/$defs/LocalId"}, + "membershipKeyField": {"$ref": "#/$defs/LocalId"}, + "principalField": {"$ref": "#/$defs/LocalId"}, + "activeField": {"$ref": "#/$defs/LocalId"} + } + } + }, "LocalId": { "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", "pattern": "^[a-z][a-z0-9_-]{0,63}$", diff --git a/products/breg/contracts/security-invariant-matrix.yaml b/products/breg/contracts/security-invariant-matrix.yaml index 7c25b6c224..9711b98c7f 100644 --- a/products/breg/contracts/security-invariant-matrix.yaml +++ b/products/breg/contracts/security-invariant-matrix.yaml @@ -37,7 +37,7 @@ invariants: - {id: BREG-SEC-33, state: enforced, targetWave: W5, threat: "A request with an ambiguous profile selects broader authority implicitly.", enforcementPoint: "compiled optional route default and HTTP profile selection", refusal: "Require an explicit accessProfile when multiple profiles admit the caller and none is an admitting route default. Answer route-wide ambiguity with 400 access-profile.ambiguous and the admitting profile IDs before Record I/O.", negativeId: BREG-NEG-33, negativeTest: {path: crates/registry-breg/tests/http_auth.rs, name: an_ambiguous_route_answers_400_with_the_admitted_profile_ids}} - {id: BREG-SEC-34, state: enforced, targetWave: W5, threat: "Approval from another authority request policy subject proposal version submission or terminal status is substituted for the configured review result.", enforcementPoint: "frozen source policy selection checked by the Review client and submission worker; immutable accepted binding and exact result correlation before application", refusal: "Require the configured authority and policy ID; compare explicit bounded provider producer metadata before accepting the exact submission digest. An explicit disagreement is a distinct configuration failure and never proof that the remote mutation rolled back. ID-only selection delegates concrete version and digest to the provider at first durable acceptance throughout pending delivery and recovery (30 days by default; operator resubmit restarts the window); optional complete pins require an exact match before acceptance. Refuse mismatched acceptance without retaining a binding, preserve an existing exact acceptance across recovery, and require every retained request subject policy proposal submission and approved-status binding before application.", negativeId: BREG-NEG-34, negativeTest: {path: crates/registry-breg/tests/postgres_proposal_review_delivery.rs, name: first_acceptance_refuses_wrong_policy_id_or_exact_pin}} - {id: BREG-SEC-35, state: enforced, targetWave: W5, threat: A related-record acceptance decision races with a referenced record update or bypasses its declared processing authority., enforcementPoint: compiled action requirements and existing ordered target locks before effects, refusal: Refuse an unmet requirement without committing any action effects and preserve its original acceptance result on exact replay., negativeId: BREG-NEG-35, negativeTest: {path: crates/registry-breg/tests/postgres_immediate_action_requirements.rs, name: action_requirements_hold_reference_lock_against_concurrent_inactivation}} - - {id: BREG-SEC-36, state: enforced, targetWave: W5, threat: A revoked membership retains protected read access or a membership probe discloses its processing rows., enforcementPoint: compiled read-only membership boundaries and generated RLS helpers plus explicit historical predicates, refusal: Deny new protected reads after committed revocation and keep membership processing separate from record disclosure., negativeId: BREG-NEG-36, negativeTest: {path: crates/registry-breg/tests/postgres_membership_access.rs, name: real_postgres_membership_reads_recheck_live_membership_and_hide_processing_inputs}} + - {id: BREG-SEC-36, state: enforced, targetWave: W5, threat: A revoked membership retains protected read access or a membership probe discloses its processing rows., enforcementPoint: compiled membership boundaries for reads and generated RLS helpers plus explicit historical predicates, refusal: Deny new protected reads after committed revocation and keep membership processing separate from record disclosure., negativeId: BREG-NEG-36, negativeTest: {path: crates/registry-breg/tests/postgres_membership_access.rs, name: real_postgres_membership_reads_recheck_live_membership_and_hide_processing_inputs}} - {id: BREG-SEC-37, state: enforced, targetWave: W5, threat: A computed action widens a compiled write slot or commits effects outside the caller authority and transaction boundary., enforcementPoint: compiled action candidate verification target contexts native RLS and atomic mutation evidence, refusal: Refuse undeclared effects or authority and recover the original committed receipt without rerunning the handler., negativeId: BREG-NEG-37, negativeTest: {path: crates/registry-breg/tests/postgres_action_handlers.rs, name: action_handlers_compute_refuse_retry_recover_and_preserve_compiled_authority}} - {id: BREG-SEC-38, state: enforced, targetWave: W5, threat: A handler leaks script values through a dynamic business refusal or mixes a refusal with writes., enforcementPoint: exclusive effects-or-refusal decoder and governed code label catalogue, refusal: Refuse unknown codes fields or output details and keep script errors value-free., negativeId: BREG-NEG-38, negativeTest: {path: crates/registry-breg/tests/immediate_action_handler.rs, name: handler_business_refusal_is_exclusive_bounded_and_governed}} - {id: BREG-SEC-39, state: enforced, targetWave: W5, threat: Stored field format integrity is bypassed or activation accepts violating existing rows., enforcementPoint: native PostgreSQL field checks and governed validated migration with retained maintenance recovery, refusal: Refuse invalid stored values and preserve exact-target recovery after a failed activation., negativeId: BREG-NEG-39, negativeTest: {path: crates/registry-breg/tests/postgres_migration.rs, name: native_patterns_validate_empty_tables_existing_rows_and_exact_target_recovery}} @@ -261,3 +261,13 @@ invariants: - {"id":"BREG-SEC-242","state":"enforced","targetWave":"W4","threat":"A claim, ask or decide preflight discloses answers and audits a disclosure nobody displayed.","enforcementPoint":"Single review-context read includes intrinsic answers only with include=answers and existing human review authority.","refusal":"Omit asks and their disclosure marker on preflight; audit actual displayed answers.","negativeId":"BREG-NEG-242","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"only_an_explicit_display_read_serves_and_audits_intrinsic_answers"}} - {"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": "An unauthenticated or misbound caller gains a membership-mediated write.", "enforcementPoint": "Production project compilation checks the principal boundary of open membership-bounded writes.", "refusal": "Refuse open writes that do not bind the principal to sub.", "negativeId": "BREG-NEG-245", "negativeTest": {"path": "crates/registry-breg/tests/membership_authoring.rs", "name": "an_open_membership_target_requires_sub_even_for_immediate_invoke"}} + - {"id": "BREG-SEC-246", "state": "enforced", "targetWave": "W5", "threat": "A Record writer moves a Record to a key outside its membership.", "enforcementPoint": "The mutation transaction checks the existing row and proposed key under the selected profile, with generated Record RLS.", "refusal": "Refuse the move and preserve the existing Record.", "negativeId": "BREG-NEG-246", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_patch_moving_a_row_to_a_key_the_caller_is_not_a_member_of_is_refused"}} + - {"id": "BREG-SEC-247", "state": "enforced", "targetWave": "W5", "threat": "A writer commits on the strength of a membership already revoked by a concurrent transaction.", "enforcementPoint": "The write holds source membership row locks through settlement. A writer waiting behind removal checks the current source row.", "refusal": "Refuse the write when removal takes effect first.", "negativeId": "BREG-NEG-247", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "record_removal_first_refuses_the_write"}} + - {"id": "BREG-SEC-248", "state": "enforced", "targetWave": "W5", "threat": "The serving database role uses the privileges needed to lock membership rows to edit their authority data.", "enforcementPoint": "The generated membership lock helper and row policy permit the lock while normal update authority remains separate.", "refusal": "Allow the matching lock without allowing the same role and context to update the membership row.", "negativeId": "BREG-NEG-248", "negativeTest": {"path": "crates/registry-breg/tests/support/postgres_membership_writes.rs", "name": "the_runtime_role_can_lock_a_membership_row_it_cannot_update"}} + - {"id": "BREG-SEC-249", "state": "enforced", "targetWave": "W5", "threat": "An immediate Action changes the membership proof its own effects rely on.", "enforcementPoint": "The Action acquires the source locks, checks effects under the selected target grant and rechecks used authority after effect execution.", "refusal": "Refuse an Action that invalidates its own membership proof and roll back its effects.", "negativeId": "BREG-NEG-249", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "an_action_cannot_invalidate_its_own_membership_proof"}} + - {"id": "BREG-SEC-250", "state": "enforced", "targetWave": "W5", "threat": "An approved Proposal moves a Record to a key outside the applying caller's membership.", "enforcementPoint": "Caller Apply locks memberships for current and frozen proposed keys and checks the selected caller's target grant before effect settlement.", "refusal": "Refuse the key move if only the old key is admitted.", "negativeId": "BREG-NEG-250", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted"}} + - {"id": "BREG-SEC-251", "state": "enforced", "targetWave": "W5", "threat": "An immediate Action acquires external Evidence without a satisfiable membership-bound effect.", "enforcementPoint": "Evidence preflight checks membership feasibility under the selected Action grant before acquisition; the mutation transaction checks current authority independently.", "refusal": "Refuse an unsatisfiable Action before Evidence acquisition.", "negativeId": "BREG-NEG-251", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "evidence_admission_refuses_unsatisfiable_membership_and_replays_without_acquisition"}} + - {"id": "BREG-SEC-252", "state": "enforced", "targetWave": "W5", "threat": "A denied membership-bound Action stages file bytes or creates a Record attachment reference.", "enforcementPoint": "Immediate Action admission and transaction membership checks precede its S3 staging and primary attachment write.", "refusal": "A membership denial leaves staging, references and external storage calls unchanged.", "negativeId": "BREG-NEG-252", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_membership_refusal_leaves_s3_staging_unchanged"}} + - {"id": "BREG-SEC-253", "state": "enforced", "targetWave": "W5", "threat": "A Proposal hook callback uses a target grant for which it cannot supply a claim or membership boundary.", "enforcementPoint": "Hook target authority requires the reviewed profile's target grants to have neither boundary kind.", "refusal": "Refuse the bounded target grant through the existing hook authority rejection.", "negativeId": "BREG-NEG-253", "negativeTest": {"path": "crates/registry-breg/src/mutation/action.rs", "name": "hooks_refuse_claim_and_membership_boundaries_on_the_same_path"}} + - {"id": "BREG-SEC-254", "state": "planned", "targetWave": "W5", "threat": "An immediate Action and Proposal Apply wait on each other when storing shared attachment content.", "enforcementPoint": "Planned common order for immediate Action staging and attachment writes and Proposal Apply promotion before history allocation, with durable staging before external upload.", "refusal": "Require the shared-content order and bounded failure recovery to preserve transaction effects and replay before treating this invariant as enforced.", "negativeId": "BREG-NEG-254"} diff --git a/products/breg/contracts/security-test-traceability.yaml b/products/breg/contracts/security-test-traceability.yaml index 93605c4fa7..cc8d943c83 100644 --- a/products/breg/contracts/security-test-traceability.yaml +++ b/products/breg/contracts/security-test-traceability.yaml @@ -302,3 +302,13 @@ traceability: - {"id":"BREG-SEC-242","state":"enforced","negativeId":"BREG-NEG-242","negativeTest":{"path":"crates/registry-breg/tests/support/proposal_review_asks_final.rs","name":"only_an_explicit_display_read_serves_and_audits_intrinsic_answers"}} - {"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/membership_authoring.rs", "name": "an_open_membership_target_requires_sub_even_for_immediate_invoke"}} + - {"id": "BREG-SEC-246", "state": "enforced", "negativeId": "BREG-NEG-246", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_patch_moving_a_row_to_a_key_the_caller_is_not_a_member_of_is_refused"}} + - {"id": "BREG-SEC-247", "state": "enforced", "negativeId": "BREG-NEG-247", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "record_removal_first_refuses_the_write"}} + - {"id": "BREG-SEC-248", "state": "enforced", "negativeId": "BREG-NEG-248", "negativeTest": {"path": "crates/registry-breg/tests/support/postgres_membership_writes.rs", "name": "the_runtime_role_can_lock_a_membership_row_it_cannot_update"}} + - {"id": "BREG-SEC-249", "state": "enforced", "negativeId": "BREG-NEG-249", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "an_action_cannot_invalidate_its_own_membership_proof"}} + - {"id": "BREG-SEC-250", "state": "enforced", "negativeId": "BREG-NEG-250", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "proposal_apply_refuses_a_key_move_when_only_the_old_key_is_admitted"}} + - {"id": "BREG-SEC-251", "state": "enforced", "negativeId": "BREG-NEG-251", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "evidence_admission_refuses_unsatisfiable_membership_and_replays_without_acquisition"}} + - {"id": "BREG-SEC-252", "state": "enforced", "negativeId": "BREG-NEG-252", "negativeTest": {"path": "crates/registry-breg/tests/support/membership_write_journeys.rs", "name": "a_membership_refusal_leaves_s3_staging_unchanged"}} + - {"id": "BREG-SEC-253", "state": "enforced", "negativeId": "BREG-NEG-253", "negativeTest": {"path": "crates/registry-breg/src/mutation/action.rs", "name": "hooks_refuse_claim_and_membership_boundaries_on_the_same_path"}} + - {"id": "BREG-SEC-254", "state": "planned", "negativeId": "BREG-NEG-254"} diff --git a/products/breg/fixtures/action-plan-branches/registry.yaml b/products/breg/fixtures/action-plan-branches/registry.yaml index 7cbb8cd479..6380fac401 100644 --- a/products/breg/fixtures/action-plan-branches/registry.yaml +++ b/products/breg/fixtures/action-plan-branches/registry.yaml @@ -58,7 +58,7 @@ accessProfiles: author: default: true principalClaim: sub - requiredScopes: unrestricted + requiredScopes: [entries:write] permissions: actions: - {action: create-entry, operations: [invoke], targets: [{recordType: entry, rowBoundaries: unrestricted}], results: [entry]} diff --git a/products/breg/fixtures/consent-land-registry/modules/consent-tenure-right/module.yaml b/products/breg/fixtures/consent-land-registry/modules/consent-tenure-right/module.yaml index 4770546dac..0f50d9ba18 100644 --- a/products/breg/fixtures/consent-land-registry/modules/consent-tenure-right/module.yaml +++ b/products/breg/fixtures/consent-land-registry/modules/consent-tenure-right/module.yaml @@ -151,6 +151,11 @@ ] }, "tenure-right-consent-link": { + "membership": { + "key": "subject", + "principal": "principal", + "active": "active" + }, "primaryDataset": "consent", "route": "tenure-right-consent-links", "mutationMode": "mutable", diff --git a/products/breg/fixtures/consent-land-registry/registry.yaml b/products/breg/fixtures/consent-land-registry/registry.yaml index 0e6ecc4197..d316dd5417 100644 --- a/products/breg/fixtures/consent-land-registry/registry.yaml +++ b/products/breg/fixtures/consent-land-registry/registry.yaml @@ -67,7 +67,7 @@ ], "distributions": [] }, - "modules": {"consent-land-registry-core":{"digest":"sha256:3b04597b187b7085830952c5b76d14ee8f9d48c6395df0b88f7eeb865906c04f","version":"0.1.0"},"consent-tenure-right":{"digest":"sha256:957c95afa8b02dfb9b02e92e7ca23ad0ee59564ae1c36c4fbffafc9a09dfe1cc","version":"0.1.0"}}, + "modules": {"consent-land-registry-core":{"digest":"sha256:3b04597b187b7085830952c5b76d14ee8f9d48c6395df0b88f7eeb865906c04f","version":"0.1.0"},"consent-tenure-right":{"digest":"sha256:bc22d4efab34bd3a5c9311049c241544137395017b7672776c3f332512c431c8","version":"0.1.0"}}, "recipients": { "organizations": [ { @@ -234,14 +234,10 @@ "records": [ { "recordType": "tenure-right-consent-decision", - "rowBoundaries": "unrestricted", - "membershipBoundaries": [ + "rowBoundaries": [ { "field": "subject", - "membershipRecordType": "tenure-right-consent-link", - "membershipKeyField": "subject", - "principalField": "principal", - "activeField": "active" + "membership": "tenure-right-consent-link" } ], "operations": [ diff --git a/products/breg/fixtures/consent-person-registry/modules/consent-person/module.yaml b/products/breg/fixtures/consent-person-registry/modules/consent-person/module.yaml index 0ea8f27197..242e340e2d 100644 --- a/products/breg/fixtures/consent-person-registry/modules/consent-person/module.yaml +++ b/products/breg/fixtures/consent-person-registry/modules/consent-person/module.yaml @@ -39,6 +39,7 @@ recordTypes: - {id: data-life, type: string, maximumLength: 80, classification: public} - {id: description, type: text, maximumLength: 4000, required: true, classification: public} person-consent-link: + membership: {key: subject, principal: principal, active: active} primaryDataset: consent route: person-consent-links mutationMode: mutable diff --git a/products/breg/fixtures/consent-person-registry/registry.yaml b/products/breg/fixtures/consent-person-registry/registry.yaml index db58c07a07..75d2a6a0c2 100644 --- a/products/breg/fixtures/consent-person-registry/registry.yaml +++ b/products/breg/fixtures/consent-person-registry/registry.yaml @@ -44,7 +44,7 @@ manifestProjection: modules: "consent-person": version: "0.1.0" - digest: "sha256:3ece798eaae6ee97f7e2d946cbf17fb8b7c1dc23bb8382d7aecb423dce755c24" + digest: "sha256:dfeb0408b8a3a5c4959e63377787cd01c558bb33943b6c9d822522950cb8a879" "consent-person-registry-core": version: "0.1.0" digest: "sha256:853a419af5b6fdd4e336a5f334accc754dde3a47eb81fd67c89b7fdfcfc6c7fe" @@ -109,9 +109,8 @@ accessProfiles: permissions: records: - recordType: person-consent-decision - rowBoundaries: unrestricted - membershipBoundaries: - - {field: subject, membershipRecordType: person-consent-link, membershipKeyField: subject, principalField: principal, activeField: active} + rowBoundaries: + - {field: subject, membership: person-consent-link} operations: [get, list] readableFields: [subject, notice, clause, recipient, purpose, scope, decision, effective-at, expires-at, channel] - recordType: person-consent-link diff --git a/products/breg/fixtures/organization-membership-access/registry.yaml b/products/breg/fixtures/organization-membership-access/registry.yaml index 86e4cd74b2..a4526e0146 100644 --- a/products/breg/fixtures/organization-membership-access/registry.yaml +++ b/products/breg/fixtures/organization-membership-access/registry.yaml @@ -23,6 +23,11 @@ ] }, "membership": { + "membership": { + "key": "organization", + "principal": "principal", + "active": "active" + }, "primaryDataset": "test-dataset", "route": "memberships", "mutationMode": "mutable", @@ -114,7 +119,12 @@ "records": [ { "recordType": "facility", - "rowBoundaries": "unrestricted", + "rowBoundaries": [ + { + "field": "organization", + "membership": "membership" + } + ], "operations": [ "get", "list", @@ -138,15 +148,6 @@ "selector": "label", "valueOrigin": "request" } - ], - "membershipBoundaries": [ - { - "field": "organization", - "membershipRecordType": "membership", - "membershipKeyField": "organization", - "principalField": "principal", - "activeField": "active" - } ] } ] diff --git a/products/breg/generated/authoring/registry-module.schema.json b/products/breg/generated/authoring/registry-module.schema.json index 49c574bb84..bc58f0d567 100644 --- a/products/breg/generated/authoring/registry-module.schema.json +++ b/products/breg/generated/authoring/registry-module.schema.json @@ -2885,32 +2885,24 @@ ], "type": "string" }, - "MembershipBoundarySource": { + "MembershipDeclarationSource": { "additionalProperties": false, - "description": "A one-hop current membership requirement, combined with every other row boundary.\nThe root field and membership key must reference the same entity. The active\nfield is Boolean, and principalField matches the profile's verified principal.", + "description": "Stored fields that establish a current membership fact.", "properties": { - "activeField": { - "type": "string" - }, - "field": { - "type": "string" - }, - "membershipKeyField": { - "type": "string" + "active": { + "$ref": "#/$defs/LocalId" }, - "membershipRecordType": { - "type": "string" + "key": { + "$ref": "#/$defs/LocalId" }, - "principalField": { - "type": "string" + "principal": { + "$ref": "#/$defs/LocalId" } }, "required": [ - "field", - "membershipRecordType", - "membershipKeyField", - "principalField", - "activeField" + "key", + "principal", + "active" ], "type": "object" }, @@ -3779,20 +3771,62 @@ "type": "string" }, { - "description": "Reach the rows every listed boundary binds to the caller's claims.", + "description": "Reach the rows bounded by every listed claim or membership entry.", "items": { - "$ref": "#/$defs/RowBoundarySource" + "$ref": "#/$defs/RowBoundaryEntry" }, "minItems": 1, "type": "array" }, { "$ref": "#/$defs/RowBoundarySetReference", - "description": "Reach the rows every boundary of a named set binds to the caller's claims." + "description": "Reach the rows bounded by every entry in a named set." } ], "description": "The rows a permission reaches: the keyword `unrestricted`, a list of at\nleast one row boundary, or a reference to a named list of them." }, + "RowBoundaryEntry": { + "additionalProperties": false, + "description": "A claim entry {field, claim, operator} or a membership entry {field, membership}.", + "else": { + "required": [ + "claim", + "operator" + ] + }, + "if": { + "required": [ + "membership" + ] + }, + "properties": { + "claim": { + "type": "string" + }, + "field": { + "type": "string" + }, + "membership": { + "$ref": "#/$defs/LocalId" + }, + "operator": { + "$ref": "#/$defs/BoundaryOperator" + } + }, + "required": [ + "field" + ], + "then": { + "properties": { + "claim": false, + "field": { + "$ref": "#/$defs/LocalId" + }, + "operator": false + } + }, + "type": "object" + }, "RowBoundarySetReference": { "additionalProperties": false, "description": "A reference to a named list of row boundaries the file declares under\n`rowBoundarySets`. The reader expands a reference into the set's boundaries\nbefore the typed model is decoded, so the compiler never holds one.", @@ -4499,12 +4533,6 @@ }, "type": "array" }, - "membershipBoundaries": { - "items": { - "$ref": "#/$defs/MembershipBoundarySource" - }, - "type": "array" - }, "operations": { "items": { "$ref": "#/$defs/Operation" @@ -4805,12 +4833,6 @@ }, "type": "array" }, - "membershipBoundaries": { - "items": { - "$ref": "#/$defs/MembershipBoundarySource" - }, - "type": "array" - }, "operations": { "items": { "$ref": "#/$defs/Operation" @@ -5060,6 +5082,9 @@ }, "type": "array" }, + "membership": { + "$ref": "#/$defs/MembershipDeclarationSource" + }, "mutationMode": { "$ref": "#/$defs/MutationMode" }, @@ -5109,7 +5134,7 @@ "rowBoundarySets": { "additionalProperties": { "items": { - "$ref": "#/$defs/RowBoundarySource" + "$ref": "#/$defs/RowBoundaryEntry" }, "minItems": 1, "type": "array" diff --git a/products/breg/generated/authoring/registry-project.schema.json b/products/breg/generated/authoring/registry-project.schema.json index 1357ab5c4f..bf2d2792be 100644 --- a/products/breg/generated/authoring/registry-project.schema.json +++ b/products/breg/generated/authoring/registry-project.schema.json @@ -659,7 +659,7 @@ "targets": { "default": [], "items": { - "$ref": "#/$defs/ActionTargetPermissionSource" + "$ref": "#/$defs/AuthoredTargetPermission" }, "type": "array" } @@ -807,23 +807,6 @@ ], "type": "object" }, - "ActionTargetPermissionSource": { - "additionalProperties": false, - "properties": { - "recordType": { - "type": "string" - }, - "rowBoundaries": { - "$ref": "#/$defs/RowBoundaries", - "description": "Row reach: `unrestricted`, or a list of at least one row boundary." - } - }, - "required": [ - "recordType", - "rowBoundaries" - ], - "type": "object" - }, "ActionTargetSource": { "additionalProperties": false, "properties": { @@ -929,6 +912,22 @@ ], "type": "object" }, + "AuthoredTargetPermission": { + "additionalProperties": false, + "properties": { + "recordType": { + "type": "string" + }, + "rowBoundaries": { + "$ref": "#/$defs/RowBoundaries" + } + }, + "required": [ + "recordType", + "rowBoundaries" + ], + "type": "object" + }, "BatchSource": { "additionalProperties": false, "properties": { @@ -2310,14 +2309,6 @@ }, "type": "array" }, - "membershipBoundaries": { - "default": [], - "description": "Current active membership required for each stored reference key.", - "items": { - "$ref": "#/$defs/MembershipBoundarySource" - }, - "type": "array" - }, "operations": { "items": { "$ref": "#/$defs/Operation" @@ -3776,32 +3767,24 @@ ], "type": "object" }, - "MembershipBoundarySource": { + "MembershipDeclarationSource": { "additionalProperties": false, - "description": "A one-hop current membership requirement, combined with every other row boundary.\nThe root field and membership key must reference the same entity. The active\nfield is Boolean, and principalField matches the profile's verified principal.", + "description": "Stored fields that establish a current membership fact.", "properties": { - "activeField": { - "type": "string" - }, - "field": { - "type": "string" - }, - "membershipKeyField": { - "type": "string" + "active": { + "$ref": "#/$defs/LocalId" }, - "membershipRecordType": { - "type": "string" + "key": { + "$ref": "#/$defs/LocalId" }, - "principalField": { - "type": "string" + "principal": { + "$ref": "#/$defs/LocalId" } }, "required": [ - "field", - "membershipRecordType", - "membershipKeyField", - "principalField", - "activeField" + "key", + "principal", + "active" ], "type": "object" }, @@ -4278,7 +4261,7 @@ "targets": { "default": [], "items": { - "$ref": "#/$defs/ProposalTargetPermissionSource" + "$ref": "#/$defs/AuthoredTargetPermission" }, "type": "array" }, @@ -4447,22 +4430,6 @@ } ] }, - "ProposalTargetPermissionSource": { - "additionalProperties": false, - "properties": { - "recordType": { - "type": "string" - }, - "rowBoundaries": { - "$ref": "#/$defs/RowBoundaries" - } - }, - "required": [ - "recordType", - "rowBoundaries" - ], - "type": "object" - }, "ProvenanceFieldSource": { "description": "A member of a revision's `changeContext` a profile may read. Each value\nis spelled as the member it names is (CFG-NAME-2).", "enum": [ @@ -4955,20 +4922,62 @@ "type": "string" }, { - "description": "Reach the rows every listed boundary binds to the caller's claims.", + "description": "Reach the rows bounded by every listed claim or membership entry.", "items": { - "$ref": "#/$defs/RowBoundarySource" + "$ref": "#/$defs/RowBoundaryEntry" }, "minItems": 1, "type": "array" }, { "$ref": "#/$defs/RowBoundarySetReference", - "description": "Reach the rows every boundary of a named set binds to the caller's claims." + "description": "Reach the rows bounded by every entry in a named set." } ], "description": "The rows a permission reaches: the keyword `unrestricted`, a list of at\nleast one row boundary, or a reference to a named list of them." }, + "RowBoundaryEntry": { + "additionalProperties": false, + "description": "A claim entry {field, claim, operator} or a membership entry {field, membership}.", + "else": { + "required": [ + "claim", + "operator" + ] + }, + "if": { + "required": [ + "membership" + ] + }, + "properties": { + "claim": { + "type": "string" + }, + "field": { + "type": "string" + }, + "membership": { + "$ref": "#/$defs/LocalId" + }, + "operator": { + "$ref": "#/$defs/BoundaryOperator" + } + }, + "required": [ + "field" + ], + "then": { + "properties": { + "claim": false, + "field": { + "$ref": "#/$defs/LocalId" + }, + "operator": false + } + }, + "type": "object" + }, "RowBoundarySetReference": { "additionalProperties": false, "description": "A reference to a named list of row boundaries the file declares under\n`rowBoundarySets`. The reader expands a reference into the set's boundaries\nbefore the typed model is decoded, so the compiler never holds one.", @@ -6412,12 +6421,6 @@ }, "type": "array" }, - "membershipBoundaries": { - "items": { - "$ref": "#/$defs/MembershipBoundarySource" - }, - "type": "array" - }, "operations": { "items": { "$ref": "#/$defs/Operation" @@ -6667,6 +6670,9 @@ }, "type": "array" }, + "membership": { + "$ref": "#/$defs/MembershipDeclarationSource" + }, "mutationMode": { "$ref": "#/$defs/MutationMode" }, @@ -6746,7 +6752,7 @@ "rowBoundarySets": { "additionalProperties": { "items": { - "$ref": "#/$defs/RowBoundarySource" + "$ref": "#/$defs/RowBoundaryEntry" }, "minItems": 1, "type": "array" diff --git a/products/breg/scripts/test-adopter-workflow.sh b/products/breg/scripts/test-adopter-workflow.sh index ddefecdd82..396a19edf8 100755 --- a/products/breg/scripts/test-adopter-workflow.sh +++ b/products/breg/scripts/test-adopter-workflow.sh @@ -165,8 +165,9 @@ write_jwt() { local key_id=$2 local principal=$3 local purpose=$4 - local output=$5 - python3 - "$key_id" "$principal" "$purpose" "$output.signing-input" <<'PY' + local scope=$5 + local output=$6 + python3 - "$key_id" "$principal" "$purpose" "$scope" "$output.signing-input" <<'PY' import base64 import json import sys @@ -185,12 +186,13 @@ claims = { "jti": f"adopter-{now}-{sys.argv[2]}-{sys.argv[3] or 'none'}", "registry_actor_kind": "service", "registry_principal": sys.argv[2], + "scope": sys.argv[4], "sub": sys.argv[2], } if sys.argv[3]: claims["registry_purpose"] = sys.argv[3] header = {"alg": "EdDSA", "kid": sys.argv[1], "typ": "JWT"} -open(sys.argv[4], "w", encoding="ascii").write(f"{b64(header)}.{b64(claims)}") +open(sys.argv[5], "w", encoding="ascii").write(f"{b64(header)}.{b64(claims)}") PY openssl pkeyutl -sign -rawin -inkey "$private_key" -in "$output.signing-input" -out "$output.signature" python3 - "$output.signing-input" "$output.signature" "$output" <<'PY' @@ -577,9 +579,9 @@ chmod 600 "$temporary_root/oidc-signer.pem" write_public_jwk "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "$temporary_root/oidc-signer.public.jwk" write_jwks "$temporary_root/oidc-signer.public.jwk" "$temporary_root/secrets/oidc-jwks" -write_jwt "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "synthetic-asset-operator" "asset-management" "$temporary_root/secrets/operator-token" -write_jwt "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "synthetic-site-planner" "site-planning" "$temporary_root/secrets/planner-token" -write_jwt "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "synthetic-site-planner" "" "$temporary_root/secrets/planner-no-purpose-token" +write_jwt "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "synthetic-asset-operator" "asset-management" "asset:manage" "$temporary_root/secrets/operator-token" +write_jwt "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "synthetic-site-planner" "site-planning" "asset:plan" "$temporary_root/secrets/planner-token" +write_jwt "$temporary_root/oidc-signer.pem" "adopter-oidc-key" "synthetic-site-planner" "" "asset:plan" "$temporary_root/secrets/planner-no-purpose-token" cat >"$temporary_root/schema-test-credentials.yaml" <<'EOF' apiVersion: id.registrystack.org/formats/breg/schema-test-credentials/v1 diff --git a/products/breg/scripts/test_validate_product.py b/products/breg/scripts/test_validate_product.py index 7db7fbf2dc..2adbd82941 100644 --- a/products/breg/scripts/test_validate_product.py +++ b/products/breg/scripts/test_validate_product.py @@ -74,16 +74,17 @@ 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, 245) if index not in {61, 62}], + [f"BREG-NEG-{index:02d}" for index in range(25, 255) if index not in {61, 62}], [invariant["negativeId"] for invariant in extension_rows], ) for invariant in extension_rows: with self.subTest(invariant=invariant["id"]): - self.assertEqual("enforced", invariant["state"]) + planned = invariant["id"] == "BREG-SEC-254" + self.assertEqual("planned" if planned else "enforced", invariant["state"]) + self.assertEqual(not planned, "negativeTest" in invariant) self.assertTrue(invariant["threat"]) self.assertTrue(invariant["enforcementPoint"]) self.assertTrue(invariant["refusal"]) - self.assertIn("negativeTest", invariant) def test_w0_crate_boundary_includes_clients_and_opt_in_runtime(self) -> None: root = tomllib.loads( diff --git a/products/breg/scripts/validate_product.py b/products/breg/scripts/validate_product.py index c8d8b8949d..3e3f173ce7 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, 245) if index not in {61, 62}) +SECURITY_INVARIANT_IDS = tuple(f"BREG-SEC-{index:02d}" for index in range(1, 255) 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/platform/CHANGELOG.md b/products/platform/CHANGELOG.md index baf1093fbc..2104d6babd 100644 --- a/products/platform/CHANGELOG.md +++ b/products/platform/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- The closed set of refusal checks includes `membership` in the admission class. + ## 0.49.0 - 2026-12-01 ### Operator and application changes From bcb61fc21f4f2155b747567b17c4ce32a9995222 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 06:58:46 +0000 Subject: [PATCH 2/4] test(breg): pin the steward revision on public main Regenerate the compiled artifact revision on the successor base. The DDL digest and exact DDL and access inventories reproduce without changes. Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/golden/membership-revision.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/registry-breg/tests/golden/membership-revision.txt b/crates/registry-breg/tests/golden/membership-revision.txt index c3e9fef05b..2cea5b6f72 100644 --- a/crates/registry-breg/tests/golden/membership-revision.txt +++ b/crates/registry-breg/tests/golden/membership-revision.txt @@ -1 +1 @@ -sha256:4fee679a2a23b6314291f46f7e460bbf736a485af06ff3210ec7d7fbed6db000 +sha256:be8ea3aa3cea6f0e238fc92c316096d58e9150341d287643a69372846072947c From 9a5dbd55561c06ecf7216f8d3ffb40426a872f3c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 07:23:06 +0000 Subject: [PATCH 3/4] test(breg): align steward migration and catalog pins Pin the pre-index SQL for the canonical steward fixture. Refresh identifier provenance for the changed BReg schema inputs. Signed-off-by: Jeremi Joslin --- crates/registry-breg/tests/compiled_ddl_pins.rs | 2 +- products/identifiers/generated/catalog.v1.json | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/registry-breg/tests/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index f5da8a3060..729ee4f0e2 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -330,7 +330,7 @@ fn an_unchanged_membership_declaration_acquires_its_index_over_a_pre_index_basel let old_digest = format!("sha256:{}", sha256(old_ddl.script().as_bytes())); assert_eq!( old_digest, - "sha256:345e560f7390867c94444d031fd5d231bb55e720f3f14a1ede9bd215f98245b4" + "sha256:88ce9380a31f7201ccda598870579c46fba1352db5598b0eb667bbb23bf68042" ); baseline.generated_ddl_sha256 = Some(old_digest); let changes = compiled_registry_change_set_from_baseline(&baseline, ®istry, "prior"); diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index f5aaa75664..4650484fe2 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -30,7 +30,7 @@ "description": "Base Registry Engine fixed Proposal lifecycle event schema, reproduced byte-for-byte from its packaged artifact.", "source": { "path": "crates/registry-breg/src/proposal_hooks.rs", - "sha256": "8536d155fb4b4007e70122255cbac89bc40ae0aaf42c60366c5c49e0d21caff6" + "sha256": "e2a0019995d7307a8b865de7c6a2cf1dd16e8853e8321bd377b6dc6d24749206" }, "artifact": { "path": "products/breg/generated/event-schemas/proposal-lifecycle.schema.json", @@ -5461,11 +5461,11 @@ "description": "Base Registry Engine bregctl explain output JSON Schemas, written by hand and held to bregctl's output by its contract test.", "source": { "path": "products/breg/contracts/explain/AccessExplanation.schema.json", - "sha256": "7c8c696f2da9b62b8043cdc4b3584c479374a6c31b29899de4a07a1ce278bdc3" + "sha256": "1f6853a1f2295586bb3dd1aa241089b3b5ffb037a165c50a2adc1f1b5837503f" }, "artifact": { "path": "products/breg/contracts/explain/AccessExplanation.schema.json", - "sha256": "7c8c696f2da9b62b8043cdc4b3584c479374a6c31b29899de4a07a1ce278bdc3", + "sha256": "1f6853a1f2295586bb3dd1aa241089b3b5ffb037a165c50a2adc1f1b5837503f", "mediaType": "application/schema+json" } }, @@ -5497,7 +5497,7 @@ "description": "Base Registry Engine portable Action contract export schema, reproduced from the canonical compiled project.", "source": { "path": "crates/registry-breg/src/artifacts.rs", - "sha256": "c520ecb0fa494f0d49d63d34b8cc45f6ec4744f77285401b884cece3320690c6" + "sha256": "93276c24b0c1ef85e6f891403bba41f1445d0a8bac1ef0bc36e808ad142da8c4" }, "artifact": { "path": "products/breg/generated/facility/generated/action-contracts.schema.json", @@ -5717,7 +5717,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-module.schema.json", - "sha256": "543316774c84e783eda4a79f87a037ecc2c94d2df14a906feaacdd9552cfc7e0", + "sha256": "7a8e736d7940fb0de0b16230ef88beb0bb3b702e7172516dc913416c76fe7de2", "mediaType": "application/schema+json" } }, @@ -5735,7 +5735,7 @@ }, "artifact": { "path": "products/breg/generated/authoring/registry-project.schema.json", - "sha256": "940c6e30dadf260f209ad059d9bc21239f43fe7d3b58fdbc9f941bf91aa28822", + "sha256": "00522c8216d5423fd88b1753b7773ced81af323cd9abf84a2bd85051db6246b5", "mediaType": "application/schema+json" } }, From eb788d95bf81ef79fe272f412131c970a14da8f2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 08:13:11 +0000 Subject: [PATCH 4/4] test(casework): scope native asset fixture seeding Signed-off-by: Jeremi Joslin --- .../src/task_grants/native_exchange_tests.rs | 11 ++++++----- .../src/task_grants/native_resource.rs | 10 +++++++--- 2 files changed, 13 insertions(+), 8 deletions(-) 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..72764f1018 100644 --- a/crates/registry-casework/src/task_grants/native_exchange_tests.rs +++ b/crates/registry-casework/src/task_grants/native_exchange_tests.rs @@ -555,7 +555,7 @@ fn prepare_issuer( ], ) .unwrap(); - let mut seed_client = client("seed-client", seed, Some("service"), &["records:get"]); + let mut seed_client = client("seed-client", seed, Some("service"), &["records:seed"]); seed_client.claims.extend([ ("tenant_claim".into(), "tenant-a".into()), ("registry_purpose".into(), "maintain".into()), @@ -564,7 +564,7 @@ fn prepare_issuer( "other-seed-client", other_seed, Some("service"), - &["records:get"], + &["records:seed"], ); other_seed_client.claims.extend([ ("tenant_claim".into(), "tenant-b".into()), @@ -581,8 +581,9 @@ fn prepare_issuer( vec![seed_client, other_seed_client], ) .unwrap(); - let source_resource = target.resource_servers[0].id.clone(); description.resource_servers.extend(target.resource_servers); + let source_resource = + local::declare_resource(&mut description, BREG_RESOURCE, &["records:get".into()]).unwrap(); // The reviewer needs a separate source-scoped token for the same subject. // The Casework staff scope grants no permissions in the BReg audience. let reviewer = description @@ -1988,7 +1989,7 @@ async fn approved_casework_tasks_reach_evidence_breg_and_scheduling_through_stoc "seed-client", &seed_key, BREG_RESOURCE, - "records:get", + "records:seed", ) .bearer_token() .await @@ -2001,7 +2002,7 @@ async fn approved_casework_tasks_reach_evidence_breg_and_scheduling_through_stoc "other-seed-client", &other_seed_key, BREG_RESOURCE, - "records:get", + "records:seed", ) .bearer_token() .await diff --git a/crates/registry-casework/src/task_grants/native_resource.rs b/crates/registry-casework/src/task_grants/native_resource.rs index 3681ad0cb3..340e26335b 100644 --- a/crates/registry-casework/src/task_grants/native_resource.rs +++ b/crates/registry-casework/src/task_grants/native_resource.rs @@ -30,9 +30,13 @@ journeys: - id: empty-site-list steps: - id: list-sites - entity: asset-site + recordType: asset-site accessProfile: steward - claims: {sub: fixture-steward, tenant_claim: fixture} + claims: + principal: fixture-steward + scopes: [records:seed] + directClaims: + tenant_claim: fixture request: {type: list} expect: {outcome: success, status: 200, count: 0} "#; @@ -84,7 +88,7 @@ pub(super) const PROJECT: &str = r#"{ "steward":{ "default":true, "principalClaim":"sub", - "requiredScopes":"unrestricted", + "requiredScopes":["records:seed"], "permissions":{ "records":[ {