Skip to main content

hyprstream_rpc/auth/ucan/
capability.rs

1//! The typed **capability** — a single `(resource, ability)` grant — and the
2//! **attenuation** (⊆) relation that is the core ceiling invariant of S5 (#571).
3//!
4//! A UCAN delegates *authority* as a set of capabilities. The cardinal rule of
5//! the whole epic (#547, design "ceiling/attenuation") is that **a delegation
6//! can only ever narrow, never widen**: every capability a child UCAN claims
7//! must be *covered by* (⊆) some capability its delegator held. If it is not,
8//! the chain is rejected — fail-closed. The compiler then lowers the *root* of a
9//! validated chain into a TE ceiling that is guaranteed to be no wider than what
10//! was reviewed.
11//!
12//! ## What lives here vs. what is deferred
13//!
14//! This module is deliberately **vocabulary-independent** (S5 milestone 1). A
15//! [`Capability`] is `(Resource, Ability, Caveats)` where:
16//! - [`Resource`] is a hierarchical URI-like string (`mac://model/qwen-7b`); the
17//!   subset relation on resources is *prefix/`*` containment* — structural, not
18//!   tied to any concrete app vocabulary.
19//! - [`Ability`] is the action verb (`infer`, `model/*`, `*`); subset is
20//!   namespace containment (`a/b` ⊆ `a/*` ⊆ `*`).
21//! - [`Caveats`] is an opaque CBOR map of restrictions; for milestone 1 the
22//!   subset rule is the conservative "more caveats = more restricted, and a
23//!   child may only *add* caveats or keep them equal" — the safe default. The
24//!   value-aware caveat algebra (e.g. numeric ranges) is a milestone-2 seam.
25//!
26//! The mapping from an [`Ability`]/[`Resource`] to S3's concrete
27//! `ScopeAction`/`Operation` + object types — i.e. *what the verbs mean to the
28//! enforcement layer* — is the action vocabulary that lands after S3 (#582). This
29//! module never needs it: attenuation is purely structural.
30
31use serde::{Deserialize, Serialize};
32use std::collections::BTreeMap;
33use std::fmt;
34
35/// A hierarchical resource identifier a capability applies to.
36///
37/// Treated as a `/`-delimited path with an optional trailing `*` wildcard
38/// segment (UCAN-style "resource pointer"). The string is the source of truth;
39/// the [`Resource::covers`] relation is the structural subset used by
40/// attenuation. We do **not** interpret the scheme/authority semantically here —
41/// that interpretation is the deferred vocabulary seam.
42#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
43#[serde(transparent)]
44pub struct Resource(pub String);
45
46impl Resource {
47    pub fn new(s: impl Into<String>) -> Self {
48        Resource(s.into())
49    }
50
51    pub fn as_str(&self) -> &str {
52        &self.0
53    }
54
55    /// Does `self` **cover** `other` — i.e. is `other` within the authority of
56    /// `self`? This is the resource half of attenuation: a child resource is
57    /// valid only if its delegator's resource covers it.
58    ///
59    /// Rules (fail-closed; when in doubt, do NOT cover):
60    /// - `*` (or empty) covers everything.
61    /// - An exact string match covers itself.
62    /// - A trailing `/*` (or bare `*` suffix on a segment boundary) covers any
63    ///   resource sharing the prefix up to that boundary.
64    ///
65    /// A child resource that is *broader* than the parent (e.g. parent
66    /// `mac://m/a`, child `mac://m/*`) is NOT covered → rejected.
67    #[must_use]
68    pub fn covers(&self, other: &Resource) -> bool {
69        let parent = self.0.as_str();
70        let child = other.0.as_str();
71
72        // Top wildcard covers all.
73        if parent == "*" || parent.is_empty() {
74            return true;
75        }
76        if parent == child {
77            return true;
78        }
79        // Prefix wildcard: `prefix/*` covers `prefix/...` (at a segment
80        // boundary, so `a/b/*` does not cover `a/bc`).
81        if let Some(prefix) = parent.strip_suffix("/*") {
82            // `prefix/*` covers `prefix` itself and anything under `prefix/`.
83            return child == prefix || child.starts_with(&format!("{prefix}/"));
84        }
85        if let Some(prefix) = parent.strip_suffix('*') {
86            // Bare-`*` suffix (no slash): textual prefix containment. Narrower
87            // form, kept conservative — only used when an author writes `a*`.
88            return child.starts_with(prefix);
89        }
90        false
91    }
92}
93
94impl fmt::Display for Resource {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(&self.0)
97    }
98}
99
100/// An action/verb a capability authorizes, e.g. `infer`, `model/read`, `*`.
101///
102/// Subset is namespace containment over `/`-delimited verb segments: `a/b` ⊆
103/// `a/*` ⊆ `*`. This mirrors the UCAN ability convention and is intentionally
104/// independent of S3's `ScopeAction` enum — the verb→`ScopeAction` mapping is the
105/// deferred action vocabulary (#582).
106#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
107#[serde(transparent)]
108pub struct Ability(pub String);
109
110impl Ability {
111    pub fn new(s: impl Into<String>) -> Self {
112        Ability(s.into())
113    }
114
115    pub fn as_str(&self) -> &str {
116        &self.0
117    }
118
119    /// Does `self` **cover** `other`? `*` covers all; `a/*` covers `a` and any
120    /// `a/...`; otherwise exact match. Fail-closed: a broader child verb is not
121    /// covered.
122    #[must_use]
123    pub fn covers(&self, other: &Ability) -> bool {
124        let parent = self.0.as_str();
125        let child = other.0.as_str();
126        if parent == "*" {
127            return true;
128        }
129        if parent == child {
130            return true;
131        }
132        if let Some(prefix) = parent.strip_suffix("/*") {
133            return child == prefix || child.starts_with(&format!("{prefix}/"));
134        }
135        false
136    }
137}
138
139impl fmt::Display for Ability {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.write_str(&self.0)
142    }
143}
144
145/// Opaque restriction map attached to a capability (UCAN "caveats").
146///
147/// Milestone-1 semantics are deliberately conservative and value-blind: a child
148/// capability's caveats must be a **superset** (more restrictive) of — or equal
149/// to — the parent's. I.e. a child may *add* restrictions or repeat the
150/// parent's, but may never *drop* or *loosen* one. Concretely [`Caveats::covers`]
151/// requires every parent key to be present in the child with a byte-identical
152/// value; the child may carry extra keys (extra restrictions).
153///
154/// The value-aware algebra (a child `{"max": 5}` being covered by a parent
155/// `{"max": 10}`) is deferred — see the module docs. Until then we never *widen*
156/// on caveats, which is the fail-closed direction.
157#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(transparent)]
159pub struct Caveats(pub BTreeMap<String, CaveatValue>);
160
161/// A single caveat value. Kept as a small, comparable, deterministically
162/// serializable shape so caveat maps hash/compare stably. Rich/value-range
163/// caveats are milestone 2.
164#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
165#[serde(untagged)]
166pub enum CaveatValue {
167    /// A textual restriction (the common UCAN case).
168    Text(String),
169    /// An integer restriction.
170    Int(i64),
171    /// A boolean restriction.
172    Bool(bool),
173    /// A list-of-strings restriction (e.g. a fixed allowlist).
174    List(Vec<String>),
175}
176
177impl Caveats {
178    /// The empty (unrestricted) caveat set.
179    pub fn empty() -> Self {
180        Caveats(BTreeMap::new())
181    }
182
183    pub fn is_empty(&self) -> bool {
184        self.0.is_empty()
185    }
186
187    /// Does `self` (the **parent's** caveats) permit a child carrying
188    /// `child` caveats? True iff every restriction the parent imposes is also
189    /// imposed, identically, by the child — the child may add more but never
190    /// drop or change one. Fail-closed (value-blind in milestone 1).
191    #[must_use]
192    pub fn covers(&self, child: &Caveats) -> bool {
193        self.0.iter().all(|(k, v)| child.0.get(k) == Some(v))
194    }
195}
196
197/// A single capability: authority to perform [`Ability`] on [`Resource`] subject
198/// to [`Caveats`]. The atom of UCAN delegation and the unit attenuation operates
199/// on.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201pub struct Capability {
202    /// The resource (`with` in UCAN parlance).
203    pub resource: Resource,
204    /// The ability/action (`can` in UCAN parlance).
205    pub ability: Ability,
206    /// Restrictions (UCAN `nb`/caveats). Empty = unrestricted.
207    #[serde(default)]
208    pub caveats: Caveats,
209}
210
211impl Capability {
212    /// Construct a capability with no caveats.
213    pub fn new(resource: Resource, ability: Ability) -> Self {
214        Self {
215            resource,
216            ability,
217            caveats: Caveats::empty(),
218        }
219    }
220
221    /// Construct with explicit caveats.
222    pub fn with_caveats(resource: Resource, ability: Ability, caveats: Caveats) -> Self {
223        Self {
224            resource,
225            ability,
226            caveats,
227        }
228    }
229
230    /// **Attenuation predicate**: does `self` (held by a delegator) *authorize*
231    /// `other` (claimed by a delegate)? This is the load-bearing ⊆ relation. A
232    /// delegate capability is valid iff its delegator covers it on **all three**
233    /// axes:
234    ///
235    /// 1. resource: `self.resource.covers(other.resource)`
236    /// 2. ability:  `self.ability.covers(other.ability)`
237    /// 3. caveats:  `self.caveats.covers(other.caveats)` (child at least as
238    ///    restricted)
239    ///
240    /// Conjunction of all three; any axis failing ⇒ NOT authorized (fail-closed).
241    /// A delegate that widens on *any* axis is rejected.
242    #[must_use]
243    pub fn authorizes(&self, other: &Capability) -> bool {
244        self.resource.covers(&other.resource)
245            && self.ability.covers(&other.ability)
246            && self.caveats.covers(&other.caveats)
247    }
248}
249
250impl fmt::Display for Capability {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        write!(f, "{}@{}", self.ability, self.resource)?;
253        if !self.caveats.is_empty() {
254            write!(f, " {:?}", self.caveats.0)?;
255        }
256        Ok(())
257    }
258}
259
260/// Is the capability set `claimed` **entirely covered** by the capability set
261/// `held`? True iff *every* claimed capability is authorized by *at least one*
262/// held capability. This is the set-level attenuation used between adjacent
263/// links of a delegation chain.
264///
265/// Fail-closed: an empty `held` covers only an empty `claimed`; any claimed
266/// capability with no covering held capability rejects the whole set.
267#[must_use]
268pub fn set_attenuates(held: &[Capability], claimed: &[Capability]) -> bool {
269    claimed.iter().all(|c| held.iter().any(|h| h.authorizes(c)))
270}
271
272#[cfg(test)]
273#[allow(clippy::unwrap_used)]
274mod tests {
275    use super::*;
276
277    fn res(s: &str) -> Resource {
278        Resource::new(s)
279    }
280    fn ab(s: &str) -> Ability {
281        Ability::new(s)
282    }
283    fn cap(r: &str, a: &str) -> Capability {
284        Capability::new(res(r), ab(a))
285    }
286
287    // ---- Resource::covers ------------------------------------------------
288
289    #[test]
290    fn resource_exact_match_covers() {
291        assert!(res("mac://model/qwen").covers(&res("mac://model/qwen")));
292        assert!(!res("mac://model/qwen").covers(&res("mac://model/llama")));
293    }
294
295    #[test]
296    fn resource_top_wildcard_covers_all() {
297        assert!(res("*").covers(&res("mac://anything/at/all")));
298        assert!(res("").covers(&res("mac://anything")));
299    }
300
301    #[test]
302    fn resource_prefix_wildcard_covers_subtree_at_boundary() {
303        let parent = res("mac://model/*");
304        assert!(parent.covers(&res("mac://model")));
305        assert!(parent.covers(&res("mac://model/qwen")));
306        assert!(parent.covers(&res("mac://model/qwen/v2")));
307        // Must respect the segment boundary: `model/*` does NOT cover `modelX`.
308        assert!(!parent.covers(&res("mac://modelX")));
309    }
310
311    #[test]
312    fn resource_child_cannot_widen() {
313        // parent narrow, child broad → NOT covered (the anti-widening invariant).
314        assert!(!res("mac://model/qwen").covers(&res("mac://model/*")));
315        assert!(!res("mac://model/qwen").covers(&res("*")));
316    }
317
318    // ---- Ability::covers -------------------------------------------------
319
320    #[test]
321    fn ability_wildcard_and_namespace() {
322        assert!(ab("*").covers(&ab("infer")));
323        assert!(ab("model/*").covers(&ab("model/read")));
324        assert!(ab("model/*").covers(&ab("model")));
325        assert!(!ab("model/read").covers(&ab("model/write")));
326        // child cannot widen.
327        assert!(!ab("model/read").covers(&ab("model/*")));
328        assert!(!ab("infer").covers(&ab("*")));
329    }
330
331    // ---- Caveats::covers -------------------------------------------------
332
333    #[test]
334    fn caveats_empty_parent_covers_anything() {
335        let parent = Caveats::empty();
336        let mut child = BTreeMap::new();
337        child.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
338        assert!(parent.covers(&Caveats(child)));
339    }
340
341    #[test]
342    fn caveats_child_may_add_but_not_drop() {
343        let mut p = BTreeMap::new();
344        p.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
345        let parent = Caveats(p);
346
347        // Child keeps the restriction AND adds one: covered (more restricted).
348        let mut c = BTreeMap::new();
349        c.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
350        c.insert("max".to_owned(), CaveatValue::Int(5));
351        assert!(parent.covers(&Caveats(c)));
352
353        // Child drops the parent's restriction: NOT covered (would widen).
354        assert!(!parent.covers(&Caveats::empty()));
355
356        // Child changes the restriction's value: NOT covered (value-blind, M1).
357        let mut c2 = BTreeMap::new();
358        c2.insert("tenant".to_owned(), CaveatValue::Text("other".to_owned()));
359        assert!(!parent.covers(&Caveats(c2)));
360    }
361
362    // ---- Capability::authorizes (the 3-axis conjunction) -----------------
363
364    #[test]
365    fn capability_authorizes_requires_all_three_axes() {
366        let held = cap("mac://model/*", "model/*");
367        assert!(held.authorizes(&cap("mac://model/qwen", "model/read")));
368        // widen resource → reject
369        assert!(!held.authorizes(&cap("mac://other/qwen", "model/read")));
370        // widen ability → reject
371        assert!(!held.authorizes(&cap("mac://model/qwen", "admin/*")));
372    }
373
374    #[test]
375    fn capability_authorizes_rejects_caveat_drop() {
376        let mut p = BTreeMap::new();
377        p.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
378        let held = Capability::with_caveats(res("mac://model/*"), ab("*"), Caveats(p));
379        // identical resource/ability but child drops the caveat → reject.
380        assert!(!held.authorizes(&cap("mac://model/qwen", "infer")));
381    }
382
383    // ---- set_attenuates --------------------------------------------------
384
385    #[test]
386    fn caveat_value_list_round_trips_through_cbor() {
387        let mut map = BTreeMap::new();
388        map.insert(
389            "allowed_services".to_owned(),
390            CaveatValue::List(vec!["discovery".to_owned(), "policy".to_owned()]),
391        );
392        let capability =
393            Capability::with_caveats(res("mac://model/qwen"), ab("infer"), Caveats(map));
394        let mut bytes = Vec::new();
395        ciborium::ser::into_writer(&capability, &mut bytes).unwrap();
396        let decoded: Capability = ciborium::de::from_reader(bytes.as_slice()).unwrap();
397        assert_eq!(decoded, capability);
398    }
399
400    #[test]
401    fn set_attenuates_every_claimed_must_be_covered() {
402        let held = vec![
403            cap("mac://model/*", "model/*"),
404            cap("mac://stream/*", "subscribe"),
405        ];
406        let claimed = vec![
407            cap("mac://model/qwen", "model/read"),
408            cap("mac://stream/abc", "subscribe"),
409        ];
410        assert!(set_attenuates(&held, &claimed));
411
412        // one claimed cap escapes the held set → whole set rejected.
413        let escapes = vec![
414            cap("mac://model/qwen", "model/read"),
415            cap("mac://admin/x", "manage"),
416        ];
417        assert!(!set_attenuates(&held, &escapes));
418    }
419
420    #[test]
421    fn set_attenuates_empty_held_covers_only_empty() {
422        assert!(set_attenuates(&[], &[]));
423        assert!(!set_attenuates(&[], &[cap("mac://x", "y")]));
424    }
425}