hyprstream_core/mac/permission_map.rs
1//! The production [`PermissionMap`] (#676): the S3 scope ↔ S5 TE-rule
2//! vocabulary, **injective and exact**.
3//!
4//! ## Shape (and why)
5//!
6//! A [`TeRule`] is a concrete numeric triple `(subject_type, object_type,
7//! action)` — a wildcard is unrepresentable in the compiled matrix, and
8//! inventing a sentinel "any object" id would put wildcard matching on the PEP
9//! decision path (a standing fail-open hazard). So wildcards exist **only on
10//! the grant side** (`Capability::authorizes` does directional covering) and
11//! this map expands them **at compile time** over a closed registry:
12//!
13//! - `mac://<class>/*` expands to one rule per **registered** object of that
14//! class — never beyond the registry.
15//! - a `*` ability expands over exactly [`SCHEMA_SCOPE_ACTIONS`] (the generated,
16//! closed schema enum).
17//! - anything unrecognized (class, name, verb) maps to **nothing**
18//! (fail-closed; never a guessed rule).
19//!
20//! Because the expansion is injective — each concrete `(class, name, verb)`
21//! maps to its own distinct rule, and no two distinct accesses share a rule —
22//! [`granted_access`](ScopePermissionMap) is the **exact inverse** of a rule,
23//! which is trivially its most-permissive access: the tightest upper bound of
24//! a singleton is itself. There is no join/LUB logic that could be "too
25//! narrow" and mask an escalation (the #676 risk). The property tests below
26//! pin exactly this: every request that projects onto a rule is authorized by
27//! that rule's `granted_access`.
28//!
29//! ## Registry determinism
30//!
31//! Object ids are assigned positionally over the **sorted** `(class, name)`
32//! registry, so two nodes constructing the map from the same object list agree
33//! on every id — the compiled matrix and the PEP intern identically with no
34//! side table. The registry is closed at construction: an object added later
35//! has no rule and is **denied by default**; the remedy is a re-compile at a
36//! new policy generation, not a silent wildcard.
37
38use std::collections::{BTreeMap, BTreeSet};
39
40use hyprstream_rpc::auth::ucan::capability::{Ability, Capability, Caveats, Resource};
41
42use crate::auth::{scope_action_from_name, scope_action_name, SCHEMA_SCOPE_ACTIONS};
43use crate::mac::compiler::{AccessRequest, PermissionMap};
44use crate::mac::te::{Action, ObjectType, SubjectType, TeRule};
45
46/// The production S3-scope permission map. See the module docs for the
47/// injective/exact contract and the registry-determinism rule.
48#[derive(Debug, Clone)]
49pub struct ScopePermissionMap {
50 /// The TE domain this map compiles rules for.
51 subject_type: SubjectType,
52 /// `(class, name)` → interned object id. Ids are positional over the
53 /// sorted registry (see module docs).
54 by_name: BTreeMap<(String, String), ObjectType>,
55 /// Exact inverse of `by_name`.
56 by_id: BTreeMap<ObjectType, (String, String)>,
57}
58
59impl ScopePermissionMap {
60 /// Build the map for `subject_type` over a closed object registry of
61 /// `(class, name)` pairs (e.g. `("model", "llama")`). Duplicates collapse;
62 /// ids are assigned `0..n` over the sorted registry (deterministic across
63 /// nodes given the same registry).
64 pub fn new<C, N>(subject_type: SubjectType, objects: impl IntoIterator<Item = (C, N)>) -> Self
65 where
66 C: Into<String>,
67 N: Into<String>,
68 {
69 let sorted: BTreeSet<(String, String)> = objects
70 .into_iter()
71 .map(|(c, n)| (c.into(), n.into()))
72 .collect();
73 let mut by_name = BTreeMap::new();
74 let mut by_id = BTreeMap::new();
75 for (i, key) in sorted.into_iter().enumerate() {
76 let id = ObjectType(i as u32);
77 by_name.insert(key.clone(), id);
78 by_id.insert(id, key);
79 }
80 Self {
81 subject_type,
82 by_name,
83 by_id,
84 }
85 }
86
87 /// Number of registered objects (diagnostics / tests).
88 pub fn len(&self) -> usize {
89 self.by_name.len()
90 }
91
92 /// Is the registry empty? (An empty registry grants nothing — fail-closed.)
93 pub fn is_empty(&self) -> bool {
94 self.by_name.is_empty()
95 }
96
97 /// Look up a registered object's interned id (PEP-side interning: the PEP
98 /// resolves the same `(class, name)` to the same id the compiler used).
99 pub fn object_type(&self, class: &str, name: &str) -> Option<ObjectType> {
100 self.by_name
101 .get(&(class.to_owned(), name.to_owned()))
102 .copied()
103 }
104
105 /// Parse a `mac://<class>/<identifier>` resource URI into its parts.
106 /// `None` for any other shape (fail-closed). The identifier may be `*`.
107 fn parse_resource(resource: &str) -> Option<(&str, &str)> {
108 let rest = resource.strip_prefix("mac://")?;
109 let (class, ident) = rest.split_once('/')?;
110 if class.is_empty() || ident.is_empty() || class == "*" {
111 // A wildcard *class* is not expandable: classes partition the
112 // registry and a grant over "every class" must be written per
113 // class. Fail closed rather than guess.
114 return None;
115 }
116 Some((class, ident))
117 }
118
119 /// The registered objects of `class`, in id order.
120 fn objects_of_class<'a>(&'a self, class: &'a str) -> impl Iterator<Item = ObjectType> + 'a {
121 self.by_name
122 .range((class.to_owned(), String::new())..)
123 .take_while(move |((c, _), _)| c == class)
124 .map(|(_, id)| *id)
125 }
126}
127
128impl PermissionMap for ScopePermissionMap {
129 fn permissions_for(&self, cap: &Capability) -> BTreeSet<TeRule> {
130 let mut out = BTreeSet::new();
131
132 // Verb(s): the generated, closed ScopeAction vocabulary. `*` expands over ALL;
133 // an unrecognized verb grants nothing.
134 let ability = cap.ability.as_str();
135 let actions: Vec<Action> = if ability == "*" {
136 SCHEMA_SCOPE_ACTIONS
137 .iter()
138 .map(|a| Action::from(*a))
139 .collect()
140 } else {
141 match scope_action_from_name(ability) {
142 Some(a) => vec![Action::from(a)],
143 None => return out,
144 }
145 };
146
147 // Object(s): the closed registry. `*` expands over the class's
148 // registered objects; an unregistered name grants nothing.
149 let Some((class, ident)) = Self::parse_resource(cap.resource.as_str()) else {
150 return out;
151 };
152 let objects: Vec<ObjectType> = if ident == "*" {
153 self.objects_of_class(class).collect()
154 } else {
155 match self.object_type(class, ident) {
156 Some(id) => vec![id],
157 None => return out,
158 }
159 };
160
161 for object_type in objects {
162 for &action in &actions {
163 out.insert(TeRule {
164 subject_type: self.subject_type,
165 object_type,
166 action,
167 });
168 }
169 }
170 out
171 }
172
173 fn granted_access(&self, rule: &TeRule) -> Option<AccessRequest> {
174 // Exact inverse: the rule was only ever emitted for one concrete
175 // (class, name, verb), so that concrete access IS the most-permissive
176 // access the rule grants. Unknown subject/object/action ⇒ None ⇒
177 // check_no_escalation treats the rule as an escalation (fail-closed).
178 if rule.subject_type != self.subject_type {
179 return None;
180 }
181 let (class, name) = self.by_id.get(&rule.object_type)?;
182 let verb = scope_action_name(rule.action.scope_action()?);
183 Some(AccessRequest {
184 resource: Resource::new(format!("mac://{class}/{name}")),
185 ability: Ability::new(verb),
186 // Empty caveats = the broadest claim (Caveats::covers requires the
187 // grant's caveats to be present in the claim). A rule enforces no
188 // caveats at the PEP, so its most-permissive access is caveat-free
189 // — and a caveated grant therefore cannot authorize it (correct:
190 // the matrix would have dropped the caveat, i.e. widened).
191 caveats: Caveats::empty(),
192 })
193 }
194}
195
196#[cfg(test)]
197#[allow(clippy::unwrap_used, clippy::expect_used)]
198mod tests {
199 //! #676: the map is injective+exact and `granted_access` upper-bounds every
200 //! request that projects onto its rule. The property tests are the tripwire
201 //! that fails if the map is ever made non-injective or the inverse drifts.
202 use super::*;
203 use proptest::prelude::*;
204
205 fn map() -> ScopePermissionMap {
206 ScopePermissionMap::new(
207 SubjectType(1),
208 [
209 ("model", "llama"),
210 ("model", "qwen"),
211 ("model", "mistral"),
212 ("adapter", "lora-a"),
213 ("adapter", "lora-b"),
214 ],
215 )
216 }
217
218 fn cap(res: &str, ab: &str) -> Capability {
219 Capability::new(Resource::new(res), Ability::new(ab))
220 }
221
222 // ── Determinism / interning ─────────────────────────────────────────────
223
224 #[test]
225 fn ids_are_deterministic_across_construction_order() {
226 let a = ScopePermissionMap::new(
227 SubjectType(1),
228 [("model", "llama"), ("adapter", "lora-a"), ("model", "qwen")],
229 );
230 let b = ScopePermissionMap::new(
231 SubjectType(1),
232 [("model", "qwen"), ("model", "llama"), ("adapter", "lora-a")],
233 );
234 for (class, name) in [("model", "llama"), ("model", "qwen"), ("adapter", "lora-a")] {
235 assert_eq!(
236 a.object_type(class, name),
237 b.object_type(class, name),
238 "id assignment must not depend on registry iteration order"
239 );
240 }
241 }
242
243 // ── Fail-closed: unknown anything grants nothing ────────────────────────
244
245 #[test]
246 fn unrecognized_inputs_grant_nothing() {
247 let m = map();
248 // Unknown verb, unknown object, unknown class, malformed URI, wildcard class.
249 for c in [
250 cap("mac://model/llama", "fly"),
251 cap("mac://model/gpt-x", "query"),
252 cap("mac://widget/llama", "query"),
253 cap("https://model/llama", "query"),
254 cap("mac://model", "query"),
255 cap("mac://*/llama", "query"),
256 ] {
257 assert!(
258 m.permissions_for(&c).is_empty(),
259 "unrecognized capability must grant nothing: {c}"
260 );
261 }
262 // Unknown rule components invert to None (⇒ escalation upstream).
263 assert!(m
264 .granted_access(&TeRule {
265 subject_type: SubjectType(2), // wrong domain
266 object_type: ObjectType(0),
267 action: Action(0),
268 })
269 .is_none());
270 assert!(m
271 .granted_access(&TeRule {
272 subject_type: SubjectType(1),
273 object_type: ObjectType(999), // unregistered object
274 action: Action(0),
275 })
276 .is_none());
277 assert!(m
278 .granted_access(&TeRule {
279 subject_type: SubjectType(1),
280 object_type: ObjectType(0),
281 action: Action(99), // outside the schema enum
282 })
283 .is_none());
284 }
285
286 // ── Wildcard expansion is exactly the registry, nothing more ────────────
287
288 #[test]
289 fn wildcard_identifier_expands_to_exactly_the_class_registry() {
290 let m = map();
291 let rules = m.permissions_for(&cap("mac://model/*", "query"));
292 assert_eq!(rules.len(), 3, "3 registered models, one rule each");
293 // No cross-class leak: none of the adapter ids appear.
294 for rule in &rules {
295 let (class, _) = &m.by_id[&rule.object_type];
296 assert_eq!(class, "model");
297 }
298 }
299
300 #[test]
301 fn wildcard_ability_expands_to_exactly_the_closed_verb_set() {
302 let m = map();
303 let rules = m.permissions_for(&cap("mac://model/llama", "*"));
304 assert_eq!(rules.len(), SCHEMA_SCOPE_ACTIONS.len());
305 }
306
307 // ── THE #676 obligation: granted_access upper-bounds the rule's grant ───
308
309 /// Round-trip exactness: for every capability the grant could contain,
310 /// every rule it lowers to inverts to an access that (a) exists and
311 /// (b) the capability itself authorizes. If the map ever lowered a narrow
312 /// capability to a broad rule, (b) is the assertion that fails.
313 #[test]
314 fn every_emitted_rule_inverts_to_an_access_the_capability_authorizes() {
315 let m = map();
316 let grants = [
317 cap("mac://model/llama", "query"),
318 cap("mac://model/*", "infer"),
319 cap("mac://adapter/*", "*"),
320 cap("mac://model/qwen", "train"),
321 ];
322 for g in &grants {
323 let rules = m.permissions_for(g);
324 assert!(
325 !rules.is_empty(),
326 "grant {g} must lower to at least one rule"
327 );
328 for rule in rules {
329 let access = m
330 .granted_access(&rule)
331 .expect("every emitted rule must have a recognized inverse");
332 let claimed = Capability::with_caveats(
333 access.resource.clone(),
334 access.ability.clone(),
335 access.caveats.clone(),
336 );
337 assert!(
338 g.authorizes(&claimed),
339 "granted_access({rule:?}) = {claimed} must be within the \
340 capability {g} that emitted the rule"
341 );
342 }
343 }
344 }
345
346 proptest! {
347 /// The upper-bound property (#676): any concrete request that PROJECTS
348 /// onto a rule this map can emit is authorized by that rule's
349 /// `granted_access`. Because the map is injective+exact this is an
350 /// equality — this test is the tripwire that fails if the map is ever
351 /// made collapsing/non-injective without upgrading `granted_access`
352 /// to a least-upper-bound (the change that could silently mask
353 /// escalation).
354 #[test]
355 fn granted_access_upper_bounds_every_request_projecting_to_the_rule(
356 class_i in 0usize..4, // model, adapter + 2 unregistered classes
357 name_i in 0usize..5, // registered + unregistered names
358 verb_i in 0usize..(SCHEMA_SCOPE_ACTIONS.len() + 2),
359 ) {
360 let m = map();
361 let classes = ["model", "adapter", "widget", "tensor"];
362 let names = ["llama", "qwen", "mistral", "lora-a", "ghost"];
363 let mut verbs: Vec<&str> = SCHEMA_SCOPE_ACTIONS
364 .iter()
365 .map(|a| scope_action_name(*a))
366 .collect();
367 verbs.push("fly");
368 verbs.push("q");
369
370 let class = classes[class_i];
371 let name = names[name_i];
372 let verb = verbs[verb_i];
373
374 // The PEP-side projection of the concrete request: same interning
375 // the compiler used (object_type via the shared registry, action
376 // via the canonical ScopeAction ids).
377 let projected = m.object_type(class, name).zip(scope_action_from_name(verb)).map(
378 |(object_type, a)| TeRule {
379 subject_type: SubjectType(1),
380 object_type,
381 action: Action::from(a),
382 },
383 );
384
385 match projected {
386 None => {
387 // Unregistered/unrecognized: no rule exists to permit it —
388 // deny-by-default. Nothing to upper-bound.
389 }
390 Some(rule) => {
391 let access = m.granted_access(&rule)
392 .expect("a projectable rule must have a recognized inverse");
393 let granted = Capability::with_caveats(
394 access.resource.clone(),
395 access.ability.clone(),
396 access.caveats.clone(),
397 );
398 let request = Capability::new(
399 Resource::new(format!("mac://{class}/{name}")),
400 Ability::new(verb),
401 );
402 prop_assert!(
403 granted.authorizes(&request),
404 "granted_access({rule:?}) = {granted} must cover the \
405 request {request} that projects onto the rule"
406 );
407 }
408 }
409 }
410
411 /// Injectivity: two DISTINCT concrete accesses never project onto the
412 /// same rule. This is the structural precondition that makes the exact
413 /// inverse sound; if someone deliberately collapses the map, this
414 /// fails first and points at the granted_access contract.
415 #[test]
416 fn distinct_accesses_project_to_distinct_rules(
417 i in 0usize..5, j in 0usize..5,
418 vi in 0usize..SCHEMA_SCOPE_ACTIONS.len(),
419 vj in 0usize..SCHEMA_SCOPE_ACTIONS.len(),
420 ) {
421 let m = map();
422 let objects = [
423 ("model", "llama"), ("model", "qwen"), ("model", "mistral"),
424 ("adapter", "lora-a"), ("adapter", "lora-b"),
425 ];
426 let (ci, ni) = objects[i];
427 let (cj, nj) = objects[j];
428 let va = SCHEMA_SCOPE_ACTIONS[vi];
429 let vb = SCHEMA_SCOPE_ACTIONS[vj];
430 let ra = TeRule {
431 subject_type: SubjectType(1),
432 object_type: m.object_type(ci, ni).unwrap(),
433 action: Action::from(va),
434 };
435 let rb = TeRule {
436 subject_type: SubjectType(1),
437 object_type: m.object_type(cj, nj).unwrap(),
438 action: Action::from(vb),
439 };
440 let same_access = (ci, ni, va) == (cj, nj, vb);
441 prop_assert_eq!(
442 ra == rb,
443 same_access,
444 "rules must be equal exactly when the concrete accesses are"
445 );
446 }
447 }
448
449 // ── End-to-end through the compiler gate ───────────────────────────────
450
451 #[test]
452 fn compile_and_gate_end_to_end_with_the_production_map() {
453 use crate::mac::compiler::{check_no_escalation, compile};
454 use crate::mac::lattice::{Compartment, Lattice, LatticeVersion};
455 use hyprstream_rpc::auth::ucan::token::{Did, Ucan, UcanPayload};
456
457 // compile/check_no_escalation read only the capability set; chain/
458 // signature verification happens upstream (mirrors compiler.rs tests).
459 let did = Did::from_ed25519(&[0u8; 32]);
460 let ucan = Ucan {
461 payload: UcanPayload {
462 issuer: did.clone(),
463 audience: did,
464 capabilities: vec![cap("mac://model/*", "query")],
465 not_before: None,
466 expiration: Some(9_999_999_999),
467 nonce: vec![],
468 },
469 proofs: vec![],
470 signature: vec![],
471 };
472
473 let m = map();
474 let lattice = Lattice::new(LatticeVersion(1), [Compartment::new("pii")]);
475 let policy = compile(&ucan, &lattice, &m);
476 // 3 registered models × 1 verb.
477 assert_eq!(policy.matrix.sorted_rules().0.len(), 3);
478 // The gate passes: nothing in the matrix exceeds the grant.
479 check_no_escalation(&ucan, &policy, &m)
480 .expect("an honestly-compiled wildcard grant must pass the gate");
481 }
482}