Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 70 additions & 28 deletions crates/registry-breg/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -114,28 +115,42 @@ pub(crate) fn check_profile(
path: &str,
errors: &mut Vec<Diagnostic>,
) {
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<String>,
required_purposes: &crate::contract::UniqueSet<String>,
path: &str,
errors: &mut Vec<Diagnostic>,
) {
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";
Expand Down Expand Up @@ -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
Expand All @@ -392,16 +407,16 @@ 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
),
)
})
});
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)
Expand Down Expand Up @@ -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);
Expand All @@ -879,7 +894,7 @@ pub struct RowReachExplanation {
pub rows: &'static str,
pub row_boundaries: Vec<RowBoundarySource>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub membership_boundaries: Vec<MembershipBoundarySource>,
pub membership_boundaries: Vec<ExpandedMembershipBoundarySource>,
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.
Expand Down Expand Up @@ -911,13 +926,40 @@ fn row_reach(
entities: &BTreeMap<String, CompiledEntity>,
actions: &CompiledActionInventory,
) -> Vec<RowReachExplanation> {
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<ExpandedMembershipBoundarySource>,
owner,
action_target_authority| {
reach.push(RowReachExplanation {
Expand All @@ -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,
});
Expand All @@ -946,7 +988,7 @@ fn row_reach(
format!("{path}.rowBoundaries"),
"record",
&profile.row_boundaries,
&profile.membership_boundaries,
record_memberships(&profile.membership_boundaries),
false,
None,
);
Expand All @@ -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,
);
Expand All @@ -979,7 +1021,7 @@ fn row_reach(
),
"action_target",
&target.row_boundaries,
&[],
target_memberships(&target.membership_boundaries),
false,
Some(ActionTargetAuthorityExplanation {
enforcement: "runtime_enforced",
Expand Down Expand Up @@ -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,
);
Expand Down
18 changes: 18 additions & 0 deletions crates/registry-breg/src/api/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()],
Expand Down Expand Up @@ -563,6 +575,9 @@ pub(super) async fn dispatch(
}
}
}
Err(MutationError::MembershipPreconditionFailed) => {
membership_precondition_problem(&correlation)
}
Err(error) => mutation_problem(error),
}
}
Expand All @@ -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),
}
}
Expand Down
34 changes: 34 additions & 0 deletions crates/registry-breg/src/api/actions/availability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use super::*;
use crate::contract::FieldTypeSource;
use crate::postgres::ActionTargetMembershipObservation;

pub(super) enum Availability {
Satisfied {
Expand Down Expand Up @@ -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?
Expand Down Expand Up @@ -184,6 +191,7 @@ pub(in crate::api) async fn observe_target(
record_id: &str,
guard_fields: &BTreeSet<String>,
boundaries: &[crate::postgres::RowBoundaryContext],
memberships: &[crate::model::CompiledMembershipBoundary],
correlation: &RequestCorrelation,
) -> Result<Option<ObservedTarget>, Response> {
let target = &entity.id;
Expand All @@ -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::<BTreeSet<_>>();
let Some(route) = service
.registry
Expand All @@ -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 {
Expand Down Expand Up @@ -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 }))
}

Expand Down
24 changes: 24 additions & 0 deletions crates/registry-breg/src/api/attachments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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),
}
Expand Down Expand Up @@ -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),
}
Expand Down
16 changes: 16 additions & 0 deletions crates/registry-breg/src/api/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,7 @@ pub struct AuthorizedActionContext {
purpose: Option<String>,
selected_profile: String,
target_authority: BTreeMap<String, Vec<VerifiedRowBoundary>>,
target_memberships: BTreeMap<String, Vec<crate::model::CompiledMembershipBoundary>>,
result_effects: BTreeSet<String>,
audit_context: Option<crate::audit::RequestAuditContext>,
task_grant: Option<TaskGrantBinding>,
Expand All @@ -647,13 +648,28 @@ impl AuthorizedActionContext {
purpose,
selected_profile,
target_authority,
target_memberships: BTreeMap::new(),
result_effects,
audit_context: None,
task_grant: None,
caller_issuer: None,
}
}

pub(crate) fn with_target_memberships(
mut self,
memberships: BTreeMap<String, Vec<crate::model::CompiledMembershipBoundary>>,
) -> Self {
self.target_memberships = memberships;
self
}

pub(crate) fn target_memberships(
&self,
) -> &BTreeMap<String, Vec<crate::model::CompiledMembershipBoundary>> {
&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);
Expand Down
Loading
Loading