plexus_auth_core/scope_registry.rs
1//! Role + `ScopeRegistry` + inheritance — the hub-level roles→scopes source
2//! of truth (R-0; revives AUTHZ-CORE-4 + AUTHZ-CORE-6 verbatim).
3//!
4//! Default-deny dispatch (AUTHZ-CORE-1/5, wired in R-5) and schema projection
5//! (AUTHZ-PRIVACY-3) need a single source of truth that maps roles to scopes,
6//! identifies which methods are public, and resolves a method's required
7//! scope set. Per AUTHZ-S01-output §4: "When a hub routes to a child
8//! activation, the child's required scopes are reported by the macro. The
9//! hub-level `ScopeRegistry` is the **single source of truth** for which
10//! roles map to which scopes." This separation lets a backend assemble
11//! scope-aware activations from third-party crates without those crates
12//! knowing the deployment's role taxonomy.
13//!
14//! # The role model (R-S01 §b, user-ratified)
15//!
16//! - **Scopes are atomic** capability identifiers (`facet.write`-style):
17//! dotted lowercase segments, segment-bounded trailing `.*` wildcard, bare
18//! `*` for "all scopes".
19//! - **Roles are named scope-sets** with transitive inheritance,
20//! cycle-rejected at [`ScopeRegistryBuilder::build`] time.
21//! - **Tokens carry roles** (the `roles` claim, minted by plexus-idp today);
22//! each backend's hub builds a `ScopeRegistry` mapping its deployment's
23//! role taxonomy to its scopes; the gate computes
24//! [`ScopeRegistry::effective_scopes`]`(AuthContext.roles)` and checks
25//! [`Scope::matches`]`(required)`.
26//!
27//! # Deferred / out of scope here
28//!
29//! - **Negative scopes** ("admin minus delete_message") are NOT implemented
30//! in v1 per AUTHZ-S01-output §4's Tier B resolution. A deployment wanting
31//! subtractive grants must model them as multiple roles. A future ticket
32//! can add the form if a real use case surfaces.
33//! - **Gate/dispatch wiring** (`DynamicHub::with_scope_registry`, the
34//! default-deny consult) is R-5 territory (revives AUTHZ-CORE-1 + CORE-5);
35//! this module is pure types + algorithm.
36//!
37//! # Deployment responsibility
38//!
39//! A crate exposing a scope-decorated activation declares its required
40//! scopes on its methods; the deploying hub's `ScopeRegistry` decides who
41//! has those scopes. If the deploying hub forgets to include a role granting
42//! the third-party scopes, those methods are unreachable under default-deny.
43//! Auditing the registry against the composed activation set is a
44//! deployment responsibility (see AUTHZ-FLOWS-3).
45
46use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
47use std::fmt;
48
49use serde::{Deserialize, Serialize};
50
51use crate::audit::RoleName;
52use crate::capabilities::{is_valid_path_segment, MethodPath};
53use crate::credential::Scope;
54
55// ---------------------------------------------------------------------------
56// Scope grammar + matching (AUTHZ-CORE-4; truth table pinned by AUTHZ-CORE-6)
57// ---------------------------------------------------------------------------
58
59/// Why a [`Scope::try_new`] rejected its input.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ScopeError {
62 /// The input was empty.
63 Empty,
64 /// The input did not match the scope grammar (carries the offending
65 /// input).
66 InvalidFormat(String),
67}
68
69impl fmt::Display for ScopeError {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 match self {
72 ScopeError::Empty => write!(f, "scope must not be empty"),
73 ScopeError::InvalidFormat(s) => write!(
74 f,
75 "invalid scope {s:?}: expected bare `*`, dot-separated lowercase \
76 identifiers ([a-z][a-z0-9_]*), or such a path with a trailing `.*` \
77 segment wildcard"
78 ),
79 }
80 }
81}
82
83impl std::error::Error for ScopeError {}
84
85/// Is `s` a valid scope per the AUTHZ-S01-output §1/§4 grammar?
86///
87/// Grammar: bare `*`, OR dot-separated segments each matching
88/// `[a-z][a-z0-9_]*`, OR such a path with one trailing `.*` wildcard
89/// segment. Wildcards anywhere else are rejected.
90fn is_valid_scope(s: &str) -> bool {
91 if s == "*" {
92 return true;
93 }
94 // Optional trailing `.*` — the body before it must be a non-empty valid
95 // dotted path. `.*` alone has an empty body and is rejected.
96 let body = s.strip_suffix(".*").unwrap_or(s);
97 if body.is_empty() {
98 return false;
99 }
100 body.split('.').all(is_valid_path_segment)
101}
102
103impl Scope {
104 /// Construct a `Scope`, validating the canonical grammar.
105 ///
106 /// Accepts: bare `*`, dot-separated lowercase identifiers (each segment
107 /// `[a-z][a-z0-9_]*`), and an optional trailing `.*` segment wildcard.
108 /// Rejects everything else with a [`ScopeError`] carrying the offending
109 /// input.
110 ///
111 /// Per AUTHZ-CORE-4. The pre-existing unvalidated [`Scope::new`]
112 /// constructor remains for wire-decoded values; registry construction
113 /// goes through this validating path.
114 pub fn try_new(s: impl Into<String>) -> Result<Self, ScopeError> {
115 let s = s.into();
116 if s.is_empty() {
117 return Err(ScopeError::Empty);
118 }
119 if !is_valid_scope(&s) {
120 return Err(ScopeError::InvalidFormat(s));
121 }
122 Ok(Self::new(s))
123 }
124
125 /// True for the bare `*` and for any `<prefix>.*` form.
126 pub fn is_wildcard(&self) -> bool {
127 self.as_str() == "*" || self.as_str().ends_with(".*")
128 }
129
130 /// Does the holder of `self` satisfy the requirement `required`?
131 ///
132 /// Returns true iff:
133 /// - `self` is the bare `*` (matches everything), OR
134 /// - `self == required` (exact match), OR
135 /// - `self` ends with `.*` AND its prefix-without-`.*` is a
136 /// **segment-prefix** of `required`.
137 ///
138 /// Segment-prefix matching is the subtle case: `cone.*` matches
139 /// `cone.send_message` AND `cone.threads.list` (multiple downstream
140 /// segments) but does NOT match `cone_extended.thing` — the `.` boundary
141 /// is mandatory. A plain string-prefix check would silently match
142 /// `cone_extended.thing`; that is the exemplar trap AUTHZ-CORE-6's
143 /// boundary test pins against.
144 ///
145 /// The required side never carries wildcards in practice (a method's
146 /// required scope is concrete); the holder side may. A required `*` is
147 /// only satisfied by a held `*` (via the bare-`*` arm).
148 pub fn matches(&self, required: &Scope) -> bool {
149 let held = self.as_str();
150 if held == "*" {
151 return true;
152 }
153 if self == required {
154 return true;
155 }
156 if let Some(prefix) = held.strip_suffix(".*") {
157 let req = required.as_str();
158 // Segment-bounded: the required scope must continue with a `.`
159 // exactly at the prefix boundary.
160 return req.len() > prefix.len()
161 && req.starts_with(prefix)
162 && req.as_bytes()[prefix.len()] == b'.';
163 }
164 false
165 }
166}
167
168// ---------------------------------------------------------------------------
169// RoleName grammar (AUTHZ-CORE-4)
170// ---------------------------------------------------------------------------
171
172/// Why a [`RoleName::try_new`] rejected its input.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum RoleNameError {
175 /// The input was empty.
176 Empty,
177 /// The input did not match `[a-z][a-z0-9_]*` (carries the offending
178 /// input).
179 InvalidFormat(String),
180}
181
182impl fmt::Display for RoleNameError {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 match self {
185 RoleNameError::Empty => write!(f, "role name must not be empty"),
186 RoleNameError::InvalidFormat(s) => {
187 write!(f, "invalid role name {s:?}: expected [a-z][a-z0-9_]*")
188 }
189 }
190 }
191}
192
193impl std::error::Error for RoleNameError {}
194
195impl RoleName {
196 /// Construct a `RoleName`, validating the `[a-z][a-z0-9_]*` grammar.
197 ///
198 /// Per AUTHZ-CORE-4. The pre-existing unvalidated [`RoleName::new`]
199 /// constructor remains for wire-decoded values (token claims); registry
200 /// construction goes through this validating path.
201 pub fn try_new(s: impl Into<String>) -> Result<Self, RoleNameError> {
202 let s = s.into();
203 if s.is_empty() {
204 return Err(RoleNameError::Empty);
205 }
206 if !is_valid_path_segment(&s) {
207 return Err(RoleNameError::InvalidFormat(s));
208 }
209 Ok(Self::new(s))
210 }
211}
212
213// ---------------------------------------------------------------------------
214// Role
215// ---------------------------------------------------------------------------
216
217/// A named scope-set with transitive inheritance.
218///
219/// A `Role` carries a name, a list of granted scopes, an `inherits` list of
220/// upstream roles whose scopes are unioned transitively at
221/// [`ScopeRegistry::expand_role`] time, and a free-text description.
222///
223/// Construction performs no validation beyond the field types themselves
224/// (per AUTHZ-CORE-4 "no validation beyond field-level"); referential
225/// integrity of `inherits` and cycle-freedom are enforced when the role is
226/// installed into a registry via [`ScopeRegistryBuilder::build`].
227///
228/// `Role` is intentionally NOT sealed — the registry's *contents* are
229/// deployment-controlled; only the *types* are framework-owned (AUTHZ-0
230/// §"Crate-level isolation amplifies the seal").
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232pub struct Role {
233 name: RoleName,
234 scopes: Vec<Scope>,
235 inherits: Vec<RoleName>,
236 description: String,
237}
238
239impl Role {
240 /// Construct a `Role` from already-typed fields.
241 pub fn new(
242 name: RoleName,
243 scopes: Vec<Scope>,
244 inherits: Vec<RoleName>,
245 description: impl Into<String>,
246 ) -> Self {
247 Self {
248 name,
249 scopes,
250 inherits,
251 description: description.into(),
252 }
253 }
254
255 /// The role's name.
256 pub fn name(&self) -> &RoleName {
257 &self.name
258 }
259
260 /// The scopes granted directly by this role (excluding inherited).
261 pub fn scopes(&self) -> &[Scope] {
262 &self.scopes
263 }
264
265 /// The upstream roles whose scopes this role unions transitively.
266 pub fn inherits(&self) -> &[RoleName] {
267 &self.inherits
268 }
269
270 /// Free-text description of the role.
271 pub fn description(&self) -> &str {
272 &self.description
273 }
274}
275
276// ---------------------------------------------------------------------------
277// ScopeRegistryError
278// ---------------------------------------------------------------------------
279
280/// Why [`ScopeRegistryBuilder::build`] rejected the declared taxonomy.
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub enum ScopeRegistryError {
283 /// A role name (declared or referenced in `inherits`) failed the
284 /// `[a-z][a-z0-9_]*` grammar.
285 InvalidRoleName(RoleNameError),
286 /// A granted scope failed the scope grammar.
287 InvalidScope(ScopeError),
288 /// The same role name was declared twice. Silent override in an auth
289 /// taxonomy is a footgun; redeclaration is rejected explicitly.
290 DuplicateRole(RoleName),
291 /// A role's `inherits` references a role that was never declared.
292 UnknownInheritedRole {
293 /// The role whose `inherits` list is dangling.
294 role: RoleName,
295 /// The undeclared role it references.
296 inherits: RoleName,
297 },
298 /// The inheritance graph contains a cycle. Carries the cycle path
299 /// (first element repeated at the end, e.g. `[a, b, a]`).
300 InheritanceCycle {
301 /// The roles forming the cycle, in walk order, closing on the first.
302 path: Vec<RoleName>,
303 },
304 /// [`ScopeRegistryBuilder::inherits`] (or `description`) was called
305 /// before any [`ScopeRegistryBuilder::role`] — there is no
306 /// most-recently-added role to modify.
307 InheritsBeforeRole,
308}
309
310impl fmt::Display for ScopeRegistryError {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 match self {
313 ScopeRegistryError::InvalidRoleName(e) => write!(f, "{e}"),
314 ScopeRegistryError::InvalidScope(e) => write!(f, "{e}"),
315 ScopeRegistryError::DuplicateRole(r) => {
316 write!(f, "role {r} declared more than once")
317 }
318 ScopeRegistryError::UnknownInheritedRole { role, inherits } => write!(
319 f,
320 "role {role} inherits undeclared role {inherits}"
321 ),
322 ScopeRegistryError::InheritanceCycle { path } => {
323 let rendered: Vec<&str> = path.iter().map(|r| r.as_str()).collect();
324 write!(f, "role inheritance cycle: {}", rendered.join(" -> "))
325 }
326 ScopeRegistryError::InheritsBeforeRole => write!(
327 f,
328 "inherits()/description() called before any role() — nothing to modify"
329 ),
330 }
331 }
332}
333
334impl std::error::Error for ScopeRegistryError {
335 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
336 match self {
337 ScopeRegistryError::InvalidRoleName(e) => Some(e),
338 ScopeRegistryError::InvalidScope(e) => Some(e),
339 _ => None,
340 }
341 }
342}
343
344impl From<RoleNameError> for ScopeRegistryError {
345 fn from(e: RoleNameError) -> Self {
346 ScopeRegistryError::InvalidRoleName(e)
347 }
348}
349
350impl From<ScopeError> for ScopeRegistryError {
351 fn from(e: ScopeError) -> Self {
352 ScopeRegistryError::InvalidScope(e)
353 }
354}
355
356// ---------------------------------------------------------------------------
357// ScopeRegistry
358// ---------------------------------------------------------------------------
359
360/// Hub-level roles→scopes source of truth. Built once at hub construction
361/// via [`ScopeRegistry::builder`], immutable thereafter.
362///
363/// Holds the role table, the set of public methods, and a per-method
364/// explicit-scope overlay (used when the macro emits explicit `scope = ...`
365/// literals; otherwise [`ScopeRegistry::required_scopes_for`] resolves the
366/// implicit `<activation>.<method>` requirement at lookup time).
367///
368/// The lookups dispatch (AUTHZ-CORE-1/5, R-5) and schema projection
369/// (AUTHZ-PRIVACY-3) consume:
370/// - "what scopes are required for this method?" —
371/// [`ScopeRegistry::required_scopes_for`]
372/// - "is this method public?" — [`ScopeRegistry::is_public`]
373/// - "expand this role to its transitive scope set" —
374/// [`ScopeRegistry::expand_role`] / [`ScopeRegistry::effective_scopes`]
375///
376/// `Default` is the empty registry: no roles, no public methods, no
377/// overlays. A hub without a registry is treated as this empty registry —
378/// with default-deny OFF that is the harmless no-op; with default-deny ON
379/// every gated method denies.
380#[derive(Debug, Clone, Default, PartialEq, Eq)]
381pub struct ScopeRegistry {
382 roles: BTreeMap<RoleName, Role>,
383 public_methods: BTreeSet<MethodPath>,
384 method_overlays: BTreeMap<MethodPath, Vec<Scope>>,
385}
386
387impl ScopeRegistry {
388 /// Start declaring a deployment's role taxonomy.
389 pub fn builder() -> ScopeRegistryBuilder {
390 ScopeRegistryBuilder::default()
391 }
392
393 /// Look up a declared role by name.
394 pub fn role(&self, name: &RoleName) -> Option<&Role> {
395 self.roles.get(name)
396 }
397
398 /// True iff the method was declared public via
399 /// [`ScopeRegistryBuilder::public_method`].
400 pub fn is_public(&self, method: &MethodPath) -> bool {
401 self.public_methods.contains(method)
402 }
403
404 /// The scopes required to invoke `method`.
405 ///
406 /// Returns the explicit overlay if [`ScopeRegistryBuilder::method_scopes`]
407 /// declared one; otherwise the implicit requirement derived from the
408 /// method path itself.
409 ///
410 /// Implicit-scope note: AUTHZ-CORE-4 phrases the implicit rule as
411 /// `<activation>.<method>`; for the canonical two-segment paths the full
412 /// dotted path IS `<activation>.<method>`. For deeper paths
413 /// (e.g. `solar.earth.luna.info`) this implementation uses the **full
414 /// dotted path** as the implicit scope rather than
415 /// first-segment + last-segment, because collapsing the middle segments
416 /// would alias distinct methods (`solar.earth.luna.info` and
417 /// `solar.mars.info` would both require `solar.info` — granting one
418 /// would grant the other, an authorization hazard). Wildcard role grants
419 /// (`solar.*`) still cover the whole subtree.
420 pub fn required_scopes_for(&self, method: &MethodPath) -> Vec<Scope> {
421 if let Some(explicit) = self.method_overlays.get(method) {
422 return explicit.clone();
423 }
424 vec![Scope::new(method.as_str())]
425 }
426
427 /// The transitive union of scopes granted by `role`: its own scopes,
428 /// plus its `inherits` roles' scopes, plus theirs, deduplicated.
429 ///
430 /// A role unknown to this registry expands to the empty set — token
431 /// claims are external input, and a role the deployment never declared
432 /// grants nothing (default-deny posture).
433 ///
434 /// Defense in depth: the walk carries a visited set, so it terminates
435 /// even on a cyclic role graph. Cycles cannot arise through
436 /// [`ScopeRegistryBuilder::build`] (which rejects them); the visited set
437 /// is the layered second defense AUTHZ-CORE-6 risk 3 calls for.
438 pub fn expand_role(&self, role: &RoleName) -> BTreeSet<Scope> {
439 let mut out = BTreeSet::new();
440 let mut visited: HashSet<&RoleName> = HashSet::new();
441 let mut frontier: Vec<&RoleName> = vec![role];
442 while let Some(name) = frontier.pop() {
443 if !visited.insert(name) {
444 continue;
445 }
446 if let Some(def) = self.roles.get(name) {
447 out.extend(def.scopes.iter().cloned());
448 frontier.extend(def.inherits.iter());
449 }
450 }
451 out
452 }
453
454 /// The union of [`ScopeRegistry::expand_role`] over each held role —
455 /// the holder's full effective scope set.
456 ///
457 /// Wildcard scopes (`*`, `<prefix>.*`) are preserved as held scopes in
458 /// the result; the wildcard math happens at the use-site via
459 /// [`Scope::matches`].
460 pub fn effective_scopes(&self, roles: &[RoleName]) -> BTreeSet<Scope> {
461 roles.iter().flat_map(|r| self.expand_role(r)).collect()
462 }
463}
464
465// ---------------------------------------------------------------------------
466// ScopeRegistryBuilder
467// ---------------------------------------------------------------------------
468
469/// One declared-but-not-yet-validated role inside the builder.
470#[derive(Debug, Clone)]
471struct RoleDraft {
472 name: String,
473 scopes: Vec<String>,
474 inherits: Vec<String>,
475 description: String,
476}
477
478/// Chainable declaration of a deployment's role taxonomy
479/// (AUTHZ-S01-output §4's registration syntax).
480///
481/// Role names, scope strings, and inherits references are accepted as bare
482/// strings for chaining ergonomics and validated together at
483/// [`ScopeRegistryBuilder::build`] time — grammar violations, duplicate
484/// roles, dangling `inherits`, and inheritance cycles all surface as
485/// [`ScopeRegistryError`]s from `build()`, never as panics.
486///
487/// # Example
488///
489/// ```
490/// use plexus_auth_core::scope_registry::ScopeRegistry;
491/// use plexus_auth_core::MethodPath;
492///
493/// let registry = ScopeRegistry::builder()
494/// .role("viewer", &["forms.list"])
495/// .role("editor", &["forms.write"])
496/// .inherits(&["viewer"])
497/// .role("tenant_owner", &[])
498/// .inherits(&["editor"])
499/// .role("admin", &["*"])
500/// .public_method(MethodPath::try_new("auth.login").unwrap())
501/// .build()
502/// .unwrap();
503/// assert!(registry.is_public(&MethodPath::try_new("auth.login").unwrap()));
504/// ```
505///
506/// # Wildcard grants are a development posture
507///
508/// `admin = {*}` (the bare-`*` grant) is implemented per AUTHZ-CORE-6 and is
509/// useful in development. **Whether wildcard role grants are permitted in
510/// production deployments is an open human question (R-S01 open question
511/// 5); treat `*` grants as dev-posture until that call is made.** Production
512/// taxonomies should prefer enumerated scopes or segment-bounded prefix
513/// wildcards (`facet.*`) per activation.
514#[derive(Debug, Clone, Default)]
515pub struct ScopeRegistryBuilder {
516 roles: Vec<RoleDraft>,
517 public_methods: BTreeSet<MethodPath>,
518 method_overlays: BTreeMap<MethodPath, Vec<Scope>>,
519 modifier_before_role: bool,
520}
521
522impl ScopeRegistryBuilder {
523 /// Declare a role granting the listed scopes. Returns the builder for
524 /// chaining; subsequent [`ScopeRegistryBuilder::inherits`] /
525 /// [`ScopeRegistryBuilder::description`] calls modify this role until
526 /// the next `role()` call.
527 pub fn role(mut self, name: impl Into<String>, scopes: &[&str]) -> Self {
528 self.roles.push(RoleDraft {
529 name: name.into(),
530 scopes: scopes.iter().map(|s| (*s).to_string()).collect(),
531 inherits: Vec::new(),
532 description: String::new(),
533 });
534 self
535 }
536
537 /// Declare that the most-recently-added role inherits the listed roles'
538 /// scopes transitively. Calling this before any `role()` is recorded
539 /// and surfaces as [`ScopeRegistryError::InheritsBeforeRole`] at
540 /// `build()` time.
541 pub fn inherits(mut self, parents: &[&str]) -> Self {
542 match self.roles.last_mut() {
543 Some(draft) => draft
544 .inherits
545 .extend(parents.iter().map(|s| (*s).to_string())),
546 None => self.modifier_before_role = true,
547 }
548 self
549 }
550
551 /// Attach a free-text description to the most-recently-added role.
552 pub fn description(mut self, description: impl Into<String>) -> Self {
553 match self.roles.last_mut() {
554 Some(draft) => draft.description = description.into(),
555 None => self.modifier_before_role = true,
556 }
557 self
558 }
559
560 /// Declare a method publicly callable (no scope required).
561 pub fn public_method(mut self, method: MethodPath) -> Self {
562 self.public_methods.insert(method);
563 self
564 }
565
566 /// Overlay explicit required scopes for a method (used when the macro
567 /// emitted explicit `scope = ...` literals; otherwise the implicit
568 /// `<activation>.<method>` rule applies at lookup time).
569 pub fn method_scopes(mut self, method: MethodPath, scopes: &[Scope]) -> Self {
570 self.method_overlays.insert(method, scopes.to_vec());
571 self
572 }
573
574 /// Validate the declared taxonomy and freeze it into a
575 /// [`ScopeRegistry`].
576 ///
577 /// Errors (in check order): modifier-before-role, role-name grammar,
578 /// scope grammar, duplicate role, dangling `inherits` reference,
579 /// inheritance cycle. Cycle detection is iterative (explicit stack) —
580 /// no recursion, no stack overflow, no hang, regardless of taxonomy
581 /// size (AUTHZ-CORE-4 acceptance 7).
582 pub fn build(self) -> Result<ScopeRegistry, ScopeRegistryError> {
583 if self.modifier_before_role {
584 return Err(ScopeRegistryError::InheritsBeforeRole);
585 }
586
587 // Grammar validation + duplicate detection.
588 let mut roles: BTreeMap<RoleName, Role> = BTreeMap::new();
589 for draft in self.roles {
590 let name = RoleName::try_new(draft.name)?;
591 let scopes = draft
592 .scopes
593 .into_iter()
594 .map(Scope::try_new)
595 .collect::<Result<Vec<_>, _>>()?;
596 let inherits = draft
597 .inherits
598 .into_iter()
599 .map(RoleName::try_new)
600 .collect::<Result<Vec<_>, _>>()?;
601 if roles.contains_key(&name) {
602 return Err(ScopeRegistryError::DuplicateRole(name));
603 }
604 roles.insert(
605 name.clone(),
606 Role::new(name, scopes, inherits, draft.description),
607 );
608 }
609
610 // Referential integrity: every inherits target must be declared.
611 for role in roles.values() {
612 for parent in role.inherits() {
613 if !roles.contains_key(parent) {
614 return Err(ScopeRegistryError::UnknownInheritedRole {
615 role: role.name().clone(),
616 inherits: parent.clone(),
617 });
618 }
619 }
620 }
621
622 // Cycle rejection (AUTHZ-CORE-4 acceptance 7).
623 if let Some(path) = detect_inheritance_cycle(&roles) {
624 return Err(ScopeRegistryError::InheritanceCycle { path });
625 }
626
627 Ok(ScopeRegistry {
628 roles,
629 public_methods: self.public_methods,
630 method_overlays: self.method_overlays,
631 })
632 }
633}
634
635/// Find a cycle in the role-inheritance graph, if any, returning its path
636/// (closing on the first repeated role, e.g. `[a, b, a]`).
637///
638/// Iterative three-color DFS with an explicit stack: bounded memory, no
639/// recursion, terminates on every finite graph. Precondition: every
640/// `inherits` target exists in `roles` (build checks referential integrity
641/// first).
642fn detect_inheritance_cycle(roles: &BTreeMap<RoleName, Role>) -> Option<Vec<RoleName>> {
643 #[derive(Clone, Copy, PartialEq)]
644 enum Color {
645 /// On the current DFS path.
646 Gray,
647 /// Fully explored; cannot be part of an undiscovered cycle.
648 Black,
649 }
650
651 let mut color: HashMap<&RoleName, Color> = HashMap::new();
652
653 for start in roles.keys() {
654 if color.contains_key(start) {
655 continue;
656 }
657 // Stack of (role, index of next inherits-edge to explore).
658 let mut stack: Vec<(&RoleName, usize)> = vec![(start, 0)];
659 color.insert(start, Color::Gray);
660
661 while let Some(&(node, edge_idx)) = stack.last() {
662 let inherits = roles
663 .get(node)
664 .expect("referential integrity checked before cycle detection")
665 .inherits();
666 if edge_idx < inherits.len() {
667 stack.last_mut().expect("stack non-empty inside loop").1 += 1;
668 let child = &inherits[edge_idx];
669 match color.get(child) {
670 Some(Color::Gray) => {
671 // Cycle: slice the current path from the first
672 // occurrence of `child`, then close on it.
673 let pos = stack
674 .iter()
675 .position(|(n, _)| *n == child)
676 .expect("gray node is on the current path");
677 let mut path: Vec<RoleName> =
678 stack[pos..].iter().map(|(n, _)| (*n).clone()).collect();
679 path.push(child.clone());
680 return Some(path);
681 }
682 Some(Color::Black) => {}
683 None => {
684 color.insert(child, Color::Gray);
685 stack.push((child, 0));
686 }
687 }
688 } else {
689 color.insert(node, Color::Black);
690 stack.pop();
691 }
692 }
693 }
694 None
695}
696
697// ---------------------------------------------------------------------------
698// Tests (AUTHZ-CORE-4's unit matrix; AUTHZ-CORE-6's exhaustive truth table
699// lives in tests/scope_registry.rs)
700// ---------------------------------------------------------------------------
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705
706 fn scope(s: &str) -> Scope {
707 Scope::try_new(s).unwrap()
708 }
709
710 fn role_name(s: &str) -> RoleName {
711 RoleName::try_new(s).unwrap()
712 }
713
714 fn method(s: &str) -> MethodPath {
715 MethodPath::try_new(s).unwrap()
716 }
717
718 // -- Scope grammar: exhaustive accept/reject matrix (CORE-4 acceptance 2)
719
720 #[test]
721 fn scope_grammar_accepts_canonical_forms() {
722 for ok in [
723 "*",
724 "forms",
725 "forms.list",
726 "forms.list.detail",
727 "forms.*",
728 "forms.list.*",
729 "cone.send_message",
730 "a1.b_2",
731 "a_x.y9.*",
732 "x",
733 ] {
734 assert!(
735 Scope::try_new(ok).is_ok(),
736 "grammar must accept {ok:?}"
737 );
738 }
739 }
740
741 #[test]
742 fn scope_grammar_rejects_violations() {
743 assert_eq!(Scope::try_new(""), Err(ScopeError::Empty));
744 for bad in [
745 ".",
746 ".*",
747 "*.*",
748 "**",
749 "*a",
750 "a*",
751 "a.b*",
752 "a.*x",
753 "a.*.b",
754 "*.thing",
755 "a.",
756 ".a",
757 "a..b",
758 "a.b.",
759 "A.b",
760 "a.B",
761 "Forms.List",
762 "9a.b",
763 "_a.b",
764 "a-b.c",
765 "a b",
766 "a.b ",
767 " a.b",
768 "café.list",
769 ] {
770 assert_eq!(
771 Scope::try_new(bad),
772 Err(ScopeError::InvalidFormat(bad.to_string())),
773 "grammar must reject {bad:?}"
774 );
775 }
776 }
777
778 #[test]
779 fn scope_is_wildcard() {
780 assert!(scope("*").is_wildcard());
781 assert!(scope("cone.*").is_wildcard());
782 assert!(scope("cone.threads.*").is_wildcard());
783 assert!(!scope("cone.send_message").is_wildcard());
784 assert!(!scope("forms").is_wildcard());
785 }
786
787 // -- Scope matching: the canonical six (CORE-4 acceptance 3; the full
788 // CORE-6 matrix lives in tests/scope_registry.rs)
789
790 #[test]
791 fn scope_matches_canonical_six() {
792 assert!(scope("*").matches(&scope("cone.send_message")));
793 assert!(scope("cone.*").matches(&scope("cone.send_message")));
794 assert!(scope("cone.*").matches(&scope("cone.threads.list")));
795 assert!(!scope("cone.*").matches(&scope("forms.list")));
796 assert!(scope("cone.send_message").matches(&scope("cone.send_message")));
797 assert!(!scope("cone.send_message").matches(&scope("cone.read_thread")));
798 }
799
800 // -- RoleName grammar (CORE-4 acceptance 4)
801
802 #[test]
803 fn role_name_grammar_accepts() {
804 for ok in ["admin", "a", "tenant_owner", "r2d2", "x_9"] {
805 assert!(
806 RoleName::try_new(ok).is_ok(),
807 "grammar must accept {ok:?}"
808 );
809 }
810 }
811
812 #[test]
813 fn role_name_grammar_rejects() {
814 assert_eq!(RoleName::try_new(""), Err(RoleNameError::Empty));
815 for bad in ["Admin", "9x", "_x", "a.b", "a-b", "a b", "*", "ADMIN", "café"] {
816 assert_eq!(
817 RoleName::try_new(bad),
818 Err(RoleNameError::InvalidFormat(bad.to_string())),
819 "grammar must reject {bad:?}"
820 );
821 }
822 }
823
824 // -- Role construction (CORE-4: no validation beyond field-level)
825
826 #[test]
827 fn role_construction_carries_fields() {
828 let r = Role::new(
829 role_name("editor"),
830 vec![scope("forms.write")],
831 vec![role_name("viewer")],
832 "can edit forms",
833 );
834 assert_eq!(r.name(), &role_name("editor"));
835 assert_eq!(r.scopes(), &[scope("forms.write")]);
836 assert_eq!(r.inherits(), &[role_name("viewer")]);
837 assert_eq!(r.description(), "can edit forms");
838 }
839
840 // -- Builder: the §4 example taxonomy (CORE-4 acceptance 5 + 6)
841
842 fn example_registry() -> ScopeRegistry {
843 ScopeRegistry::builder()
844 .role("viewer", &["forms.list"])
845 .description("read-only access")
846 .role("editor", &["forms.write"])
847 .inherits(&["viewer"])
848 .role("tenant_owner", &[])
849 .inherits(&["editor"])
850 .role("admin", &["*"])
851 .public_method(method("auth.login"))
852 .method_scopes(method("forms.export"), &[scope("forms.list")])
853 .build()
854 .expect("the §4 example taxonomy must build")
855 }
856
857 #[test]
858 fn builder_example_taxonomy_expands_as_pinned() {
859 let reg = example_registry();
860 assert_eq!(
861 reg.expand_role(&role_name("viewer")),
862 BTreeSet::from([scope("forms.list")])
863 );
864 assert_eq!(
865 reg.expand_role(&role_name("editor")),
866 BTreeSet::from([scope("forms.write"), scope("forms.list")])
867 );
868 assert_eq!(
869 reg.expand_role(&role_name("tenant_owner")),
870 BTreeSet::from([scope("forms.write"), scope("forms.list")])
871 );
872 assert_eq!(
873 reg.expand_role(&role_name("admin")),
874 BTreeSet::from([scope("*")])
875 );
876 }
877
878 #[test]
879 fn builder_role_lookup_carries_description() {
880 let reg = example_registry();
881 let viewer = reg.role(&role_name("viewer")).expect("viewer declared");
882 assert_eq!(viewer.description(), "read-only access");
883 }
884
885 // -- is_public (CORE-4 acceptance 10)
886
887 #[test]
888 fn is_public_true_only_for_declared_methods() {
889 let reg = example_registry();
890 assert!(reg.is_public(&method("auth.login")));
891 assert!(!reg.is_public(&method("forms.export")));
892 assert!(!reg.is_public(&method("cone.send_message")));
893 }
894
895 // -- required_scopes_for (CORE-4 acceptance 9)
896
897 #[test]
898 fn required_scopes_explicit_overlay_wins() {
899 let reg = example_registry();
900 assert_eq!(
901 reg.required_scopes_for(&method("forms.export")),
902 vec![scope("forms.list")]
903 );
904 }
905
906 #[test]
907 fn required_scopes_implicit_is_the_method_path() {
908 let reg = example_registry();
909 assert_eq!(
910 reg.required_scopes_for(&method("cone.send_message")),
911 vec![Scope::new("cone.send_message")]
912 );
913 }
914
915 // -- Cycle rejection (CORE-4 acceptance 7)
916
917 #[test]
918 fn build_rejects_two_role_cycle_with_path() {
919 let err = ScopeRegistry::builder()
920 .role("a", &["x.one"])
921 .inherits(&["b"])
922 .role("b", &["y.one"])
923 .inherits(&["a"])
924 .build()
925 .expect_err("cycle must be rejected at build()");
926 match err {
927 ScopeRegistryError::InheritanceCycle { path } => {
928 // Path closes on its first element and contains both roles.
929 assert_eq!(path.first(), path.last());
930 assert!(path.contains(&role_name("a")));
931 assert!(path.contains(&role_name("b")));
932 assert_eq!(path.len(), 3, "a->b->a (closed) has length 3");
933 }
934 other => panic!("expected InheritanceCycle, got {other:?}"),
935 }
936 }
937
938 #[test]
939 fn build_rejects_self_cycle() {
940 let err = ScopeRegistry::builder()
941 .role("a", &["x.one"])
942 .inherits(&["a"])
943 .build()
944 .expect_err("self-cycle must be rejected at build()");
945 assert!(matches!(
946 err,
947 ScopeRegistryError::InheritanceCycle { ref path } if path == &vec![role_name("a"), role_name("a")]
948 ));
949 }
950
951 #[test]
952 fn build_rejects_deep_cycle_without_overflow() {
953 // A long chain ending in a cycle: r0 -> r1 -> ... -> r9999 -> r0.
954 // Iterative DFS must neither overflow nor hang.
955 let n = 10_000;
956 let names: Vec<String> = (0..n).map(|i| format!("r{i}")).collect();
957 let mut b = ScopeRegistry::builder();
958 for i in 0..n {
959 let parent = names[(i + 1) % n].clone();
960 b = b.role(names[i].as_str(), &[]).inherits(&[parent.as_str()]);
961 }
962 let err = b.build().expect_err("the loop must be rejected");
963 assert!(matches!(err, ScopeRegistryError::InheritanceCycle { .. }));
964 }
965
966 #[test]
967 fn build_accepts_diamond_inheritance() {
968 // a -> b, a -> c, b -> d, c -> d: shared ancestor, no cycle.
969 let reg = ScopeRegistry::builder()
970 .role("d", &["base.read"])
971 .role("b", &["b.write"])
972 .inherits(&["d"])
973 .role("c", &["c.write"])
974 .inherits(&["d"])
975 .role("a", &[])
976 .inherits(&["b", "c"])
977 .build()
978 .expect("diamond is acyclic");
979 assert_eq!(
980 reg.expand_role(&role_name("a")),
981 BTreeSet::from([scope("base.read"), scope("b.write"), scope("c.write")])
982 );
983 }
984
985 // -- Builder error surfaces
986
987 #[test]
988 fn build_rejects_unknown_inherited_role() {
989 let err = ScopeRegistry::builder()
990 .role("a", &["x.one"])
991 .inherits(&["ghost"])
992 .build()
993 .expect_err("dangling inherits must be rejected");
994 assert_eq!(
995 err,
996 ScopeRegistryError::UnknownInheritedRole {
997 role: role_name("a"),
998 inherits: role_name("ghost"),
999 }
1000 );
1001 }
1002
1003 #[test]
1004 fn build_rejects_duplicate_role() {
1005 let err = ScopeRegistry::builder()
1006 .role("a", &["x.one"])
1007 .role("a", &["y.one"])
1008 .build()
1009 .expect_err("redeclaration must be rejected");
1010 assert_eq!(err, ScopeRegistryError::DuplicateRole(role_name("a")));
1011 }
1012
1013 #[test]
1014 fn build_rejects_invalid_role_name() {
1015 let err = ScopeRegistry::builder()
1016 .role("Admin", &["x.one"])
1017 .build()
1018 .expect_err("bad role name must be rejected");
1019 assert!(matches!(err, ScopeRegistryError::InvalidRoleName(_)));
1020 }
1021
1022 #[test]
1023 fn build_rejects_invalid_scope() {
1024 let err = ScopeRegistry::builder()
1025 .role("a", &["Bad.Scope"])
1026 .build()
1027 .expect_err("bad scope must be rejected");
1028 assert!(matches!(err, ScopeRegistryError::InvalidScope(_)));
1029 }
1030
1031 #[test]
1032 fn build_rejects_inherits_before_role() {
1033 let err = ScopeRegistry::builder()
1034 .inherits(&["a"])
1035 .role("a", &["x.one"])
1036 .build()
1037 .expect_err("inherits() before role() must be rejected");
1038 assert_eq!(err, ScopeRegistryError::InheritsBeforeRole);
1039 }
1040
1041 // -- Empty/default registry (CORE-4 "hub without registry" row)
1042
1043 #[test]
1044 fn default_registry_is_empty() {
1045 let reg = ScopeRegistry::default();
1046 assert!(!reg.is_public(&method("auth.login")));
1047 assert!(reg.effective_scopes(&[role_name("admin")]).is_empty());
1048 assert_eq!(
1049 reg.required_scopes_for(&method("cone.send_message")),
1050 vec![Scope::new("cone.send_message")]
1051 );
1052 assert_eq!(reg, ScopeRegistry::builder().build().unwrap());
1053 }
1054
1055 // -- Defense-in-depth smoke test (CORE-6 acceptance 5): a cyclic graph
1056 // injected by direct internal manipulation (bypassing build()) must
1057 // not hang or overflow expand_role; the visited set bounds the walk.
1058
1059 #[test]
1060 fn expand_role_terminates_on_injected_cycle() {
1061 let mut roles = BTreeMap::new();
1062 roles.insert(
1063 role_name("a"),
1064 Role::new(role_name("a"), vec![scope("x.one")], vec![role_name("b")], ""),
1065 );
1066 roles.insert(
1067 role_name("b"),
1068 Role::new(role_name("b"), vec![scope("y.one")], vec![role_name("a")], ""),
1069 );
1070 // Direct struct construction — possible only inside the crate; the
1071 // builder (the only public path) rejects this shape. AUTHZ-CORE-4's
1072 // build()-time rejection is the primary defense; this is layered.
1073 let reg = ScopeRegistry {
1074 roles,
1075 public_methods: BTreeSet::new(),
1076 method_overlays: BTreeMap::new(),
1077 };
1078 assert_eq!(
1079 reg.expand_role(&role_name("a")),
1080 BTreeSet::from([scope("x.one"), scope("y.one")])
1081 );
1082 }
1083}