Skip to main content

systemprompt_security/authz/
resolver.rs

1//! Pure deny-overrides resolver with `user > … > role` specificity.
2//!
3//! Core ships two subject dimensions, `user` and `role`. Extensions declare
4//! their own — department, cost centre, clearance — as
5//! [`SubjectDimension`]s and pass them in via [`ResolveInput::dimensions`],
6//! with the user's values for them in [`ResolveInput::attributes`]. The
7//! precedence ladder is built per call from those two fields, so `resolve`
8//! learns no tenant vocabulary and stays pure. With no dimensions passed the
9//! ladder is exactly `user > role`, which is the pre-existing behaviour.
10//!
11//! The function is intentionally synchronous and free of I/O so it can be
12//! reused by the in-process [`super::rule_based::RuleBasedHook`], the
13//! template's webhook handler, and unit tests without setup. Callers fetch
14//! [`AccessRule`]s plus the `default_included` sentinel from
15//! [`super::repository::AccessControlRepository`] and pass them in.
16//!
17//! A declared ruleset is **authoritative and closed**: an entity that names its
18//! own roles is closed to every role it does not name, and only an entity with
19//! no rules of its own defers to its parents. This is what makes a narrow
20//! `roles: [admin]` grant restrictive even when the entity belongs to a group
21//! that is granted to everyone.
22//!
23//! `default_included` is `Option<bool>` — `None` signals the entity is
24//! unknown to access control (no row in `access_control_entities`), which
25//! the resolver turns into [`DenyReason::UnknownEntity`] rather than the
26//! generic `NotAssigned` deny. This distinction matters operationally: an
27//! unknown entity is a publish-pipeline gap, not a missing role grant.
28//!
29//! Copyright (c) systemprompt.io — Business Source License 1.1.
30//! See <https://systemprompt.io> for licensing details.
31
32use systemprompt_identifiers::UserId;
33
34use super::subject::{ROLE_PRECEDENCE, SubjectAttributes, SubjectDimension, USER_PRECEDENCE};
35use super::types::{Access, AccessRule, Decision, DenyReason, EntityRef, MatchedBy, RuleType};
36
37/// A parent entity whose rules cascade onto the child being resolved.
38///
39/// Parents are ordered nearest-first: the entity directly above the child
40/// comes before its grandparent, so a closer grant wins over a more distant
41/// one within the same precedence band.
42#[derive(Debug, Clone, Copy)]
43pub struct ResolveParent<'a> {
44    pub entity: &'a EntityRef,
45    pub rules: &'a [AccessRule],
46    pub default_included: Option<bool>,
47}
48
49/// Inputs to [`resolve`]. Bundled so the function stays under the clippy
50/// argument-count limit and so call sites can read top-to-bottom.
51#[derive(Debug, Clone, Copy)]
52pub struct ResolveInput<'a> {
53    pub entity: &'a EntityRef,
54    pub rules: &'a [AccessRule],
55    pub user_id: &'a UserId,
56    pub user_roles: &'a [String],
57    pub default_included: Option<bool>,
58    pub parents: &'a [ResolveParent<'a>],
59    /// The user's values for each extension-declared dimension, gathered by
60    /// [`gather_subject_attributes`][super::subject::gather_subject_attributes].
61    pub attributes: &'a SubjectAttributes,
62    /// Extension dimensions to interleave into the precedence ladder. Passed
63    /// in rather than read from the inventory so `resolve` stays pure and
64    /// unit-testable; pass `&[]` for core-only `user > role` behaviour.
65    pub dimensions: &'a [SubjectDimension],
66}
67
68/// Resolves a decision with parent inheritance on the crate-head deny-overrides
69/// model.
70///
71/// A child deny overrides a parent allow, a nearer rule overrides a farther one
72/// within the same precedence band, and a parent grant cascades to the child
73/// only when the child declares no rules at all — a child that declares any
74/// rule owns its decision and is closed to roles it does not name. An unknown
75/// child entity (`default_included == None`) yields
76/// [`DenyReason::UnknownEntity`] unless a rule or a parent's `default_included`
77/// grants access.
78#[must_use]
79pub fn resolve(input: ResolveInput<'_>) -> Decision {
80    let ResolveInput {
81        entity,
82        rules,
83        user_id,
84        user_roles,
85        default_included,
86        parents,
87        attributes,
88        dimensions,
89    } = input;
90
91    let ladder = ladder(dimensions);
92    let subject = Subject {
93        user_id,
94        user_roles,
95        attributes,
96        ladder: &ladder,
97    };
98
99    if let Some(decision) = match_ruleset(entity, rules, &subject) {
100        return decision;
101    }
102    // Why: A declared ruleset is authoritative: an entity that names its own roles
103    // is closed to every role it does not name. `match_ruleset` cannot
104    // distinguish "no rule matches you" from "no rules exist", so only an
105    // entity with no rules of its own defers to its parents.
106    let parents = if rules.is_empty() { parents } else { &[] };
107
108    for parent in parents {
109        if let Some(decision) = match_ruleset(parent.entity, parent.rules, &subject) {
110            return decision;
111        }
112    }
113
114    if default_included == Some(true) {
115        return Decision::Allow {
116            matched_by: MatchedBy::DefaultIncluded,
117        };
118    }
119    if parents
120        .iter()
121        .any(|parent| parent.default_included == Some(true))
122    {
123        return Decision::Allow {
124            matched_by: MatchedBy::DefaultIncluded,
125        };
126    }
127
128    if default_included.is_none() {
129        return Decision::Deny {
130            reason: DenyReason::UnknownEntity {
131                entity: entity.clone(),
132            },
133        };
134    }
135    Decision::Deny {
136        reason: DenyReason::NotAssigned {
137            entity: entity.clone(),
138            user_id: user_id.clone(),
139            roles: user_roles.to_vec(),
140        },
141    }
142}
143
144fn ladder(dimensions: &[SubjectDimension]) -> Vec<(RuleType, u16)> {
145    let mut bands = vec![
146        (RuleType::USER, USER_PRECEDENCE),
147        (RuleType::ROLE, ROLE_PRECEDENCE),
148    ];
149    bands.extend(
150        dimensions
151            .iter()
152            .filter(|d| d.rule_type != RuleType::USER && d.rule_type != RuleType::ROLE)
153            .map(|d| (d.rule_type.clone(), d.precedence)),
154    );
155    bands.sort_by_key(|&(_, precedence)| precedence);
156    bands
157}
158
159struct Subject<'a> {
160    user_id: &'a UserId,
161    user_roles: &'a [String],
162    attributes: &'a SubjectAttributes,
163    ladder: &'a [(RuleType, u16)],
164}
165
166impl Subject<'_> {
167    fn matches(&self, rule: &AccessRule) -> bool {
168        if rule.rule_type == RuleType::USER {
169            return rule.rule_value == self.user_id.as_str();
170        }
171        let held = if rule.rule_type == RuleType::ROLE {
172            self.user_roles
173        } else {
174            self.attributes.values(&rule.rule_type)
175        };
176        held.iter().any(|value| value == &rule.rule_value)
177    }
178}
179
180fn match_ruleset(
181    target: &EntityRef,
182    ruleset: &[AccessRule],
183    subject: &Subject<'_>,
184) -> Option<Decision> {
185    for (rule_type, _) in subject.ladder {
186        let in_band = |r: &&AccessRule| r.rule_type == *rule_type && subject.matches(r);
187
188        if let Some(rule) = ruleset
189            .iter()
190            .find(|r| in_band(r) && r.access == Access::Deny)
191        {
192            return Some(deny_for(target, subject, rule));
193        }
194        if let Some(rule) = ruleset
195            .iter()
196            .find(|r| in_band(r) && r.access == Access::Allow)
197        {
198            return Some(allow_for(rule));
199        }
200    }
201    None
202}
203
204// Why: Built-ins keep their dedicated variants so existing
205// `governance_decisions` audit JSON stays stable; extension dimensions report
206// through the generic attribute variants.
207fn deny_for(target: &EntityRef, subject: &Subject<'_>, rule: &AccessRule) -> Decision {
208    let reason = if rule.rule_type == RuleType::USER {
209        DenyReason::UserDeny {
210            entity: target.clone(),
211            user_id: subject.user_id.clone(),
212            justification: rule.justification.clone(),
213        }
214    } else if rule.rule_type == RuleType::ROLE {
215        DenyReason::RoleDeny {
216            entity: target.clone(),
217            role: rule.rule_value.clone(),
218            justification: rule.justification.clone(),
219        }
220    } else {
221        DenyReason::AttributeDeny {
222            entity: target.clone(),
223            rule_type: rule.rule_type.clone(),
224            value: rule.rule_value.clone(),
225            justification: rule.justification.clone(),
226        }
227    };
228    Decision::Deny { reason }
229}
230
231fn allow_for(rule: &AccessRule) -> Decision {
232    let matched_by = if rule.rule_type == RuleType::USER {
233        MatchedBy::UserAllow
234    } else if rule.rule_type == RuleType::ROLE {
235        MatchedBy::RoleAllow {
236            role: rule.rule_value.clone(),
237        }
238    } else {
239        MatchedBy::AttributeAllow {
240            rule_type: rule.rule_type.clone(),
241            value: rule.rule_value.clone(),
242        }
243    };
244    Decision::Allow { matched_by }
245}