Skip to main content

hyprstream_rpc/auth/mac/
manifest.rs

1//! The **object-label seam** — where an object's content-bound label comes from.
2//!
3//! Design §3: "Data layers: `security_label` in the content-addressed manifest —
4//! cryptographically bound; can't be relabeled without changing the hash
5//! (stronger than SELinux xattrs)." The per-op monitor (S2) reads the object's
6//! label from here and feeds it into `subject.ctx ⊒ object.label`.
7//!
8//! ## Why this is a trait, not a struct
9//!
10//! **The content-addressed CAS manifest layer does not exist yet** in this
11//! codebase (the only "manifest" types today are OCI image manifests in
12//! `hyprstream-workers` and release/context manifests — none is the data-plane
13//! CAS manifest with a `security_label`). So S1 cannot fabricate it. Instead S1
14//! defines:
15//!
16//! - [`LabeledObject`] — the seam the monitor (S2) and PDP (S4) program against:
17//!   "give me this object's label." Implemented later by the real manifest type.
18//! - [`ContentBoundLabel`] — the *binding contract* a real manifest must honor:
19//!   the label is covered by the content hash, so relabeling changes the CID.
20//! - [`StaticNodeLabel`] — the satisfiable-today case: static schema nodes
21//!   (status/ctl/health) whose label is declared in the `$scope` annotation, not
22//!   stored in a manifest. These can be labeled and enforced immediately.
23//!
24//! This keeps the interface S2/S4 consume stable while honestly flagging the
25//! data-plane part as blocked (see module-level BLOCKERS in `mod.rs`).
26
27use super::label::SecurityLabel;
28
29/// Anything the reference monitor can ask for a security label.
30///
31/// The monitor never accepts a label from a token/UCAN/caveat (design §3, §14);
32/// it asks the object. For data layers the impl reads the manifest's
33/// content-bound `security_label`; for static nodes it returns the schema-
34/// declared label.
35pub trait LabeledObject {
36    /// This object's security label. `None` ⇒ **unlabeled** ⇒ the monitor MUST
37    /// deny (no unlabeled-default-allow; design §1 invariant 2). Implementors
38    /// must NOT manufacture a permissive default here.
39    fn security_label(&self) -> Option<SecurityLabel>;
40}
41
42/// The binding contract a real CAS manifest must satisfy: the label is bound to
43/// the content hash, so an attacker cannot relabel without producing a new CID
44/// (and thus a new object). This is the property that makes the object label
45/// *content-truth* rather than a mutable xattr.
46///
47/// S1 specifies the contract; the implementation lands with the manifest layer.
48/// A conforming manifest serializes `security_label` *inside* the bytes that the
49/// CID covers — verifying this is the manifest layer's test, asserted here as a
50/// documented invariant.
51pub trait ContentBoundLabel: LabeledObject {
52    /// The content identifier (hash) of the manifest. The label returned by
53    /// [`LabeledObject::security_label`] MUST be part of the preimage of this
54    /// CID.
55    fn content_id(&self) -> &[u8];
56
57    /// Recompute the CID over the manifest bytes (including the label) and check
58    /// it equals [`content_id`]. A real impl uses this to *verify* the binding
59    /// when a manifest is loaded from the store — a mismatch ⇒ tampered ⇒ deny.
60    ///
61    /// Default impl is `false` (fail-closed) so a stub that forgets to implement
62    /// verification denies rather than trusts.
63    ///
64    /// [`content_id`]: ContentBoundLabel::content_id
65    fn verify_binding(&self) -> bool {
66        false
67    }
68}
69
70/// A static schema node's label (status/ctl/health and other declared nodes).
71///
72/// This is the immediately-satisfiable half of object labeling: the label comes
73/// from the `$scope`/TE annotation in the schema (S3, #569), not from a CAS
74/// manifest, so it needs no data-plane store. Genesis labeling (see
75/// [`super::genesis`]) assigns one of these to every static node before
76/// enforcement turns on.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct StaticNodeLabel {
79    /// Schema-declared label for this node. Always `Some` once genesis is
80    /// complete — a static node with no declared label is a genesis gap and the
81    /// `Option` surfaces it as "unlabeled → deny".
82    label: Option<SecurityLabel>,
83}
84
85impl StaticNodeLabel {
86    /// A labeled static node.
87    pub fn labeled(label: SecurityLabel) -> Self {
88        StaticNodeLabel { label: Some(label) }
89    }
90
91    /// An explicitly-unlabeled node (genesis gap). Provided so callers can
92    /// represent "no label declared" without reaching for a permissive default.
93    pub fn unlabeled() -> Self {
94        StaticNodeLabel { label: None }
95    }
96}
97
98impl LabeledObject for StaticNodeLabel {
99    fn security_label(&self) -> Option<SecurityLabel> {
100        self.label
101    }
102}
103
104// ────────────────────────────────────────────────────────────────────────────
105// Object-label RESOLUTION seam (#699, epic #547 activation prerequisite)
106// ────────────────────────────────────────────────────────────────────────────
107//
108// `LabeledObject` (above) answers "what is THIS object's label" once you
109// already hold an object. The reference monitor doesn't hold objects — it
110// holds a *walked reference* (a path, or a CID) and needs to resolve THAT to
111// a label before it can even construct the `ObjectCtx` the PDP evaluates.
112// `ObjectLabelResolver` is that keyed lookup, ratified as ticket #699's scope
113// item 2 ("An ObjectLabelResolver trait keyed on the walked path / CID that
114// the PEP calls before decide").
115//
116// This module intentionally does NOT wire a concrete resolver against the
117// 9P/VFS `Mount`/`Namespace` types (`hyprstream-vfs`) — that wiring is S2/
118// #568's job (the generated-mount PEP), and this crate is platform-
119// independent by design (no `hyprstream-vfs` dependency, so it keeps
120// compiling for wasm). What lands here is the seam plus the **clamp
121// invariants** ratified alongside #699's carriers, which are pure functions
122// over `SecurityLabel` with no I/O or VFS dependency at all.
123
124/// A reference to the object being labeled, as available to whatever calls
125/// [`ObjectLabelResolver::resolve`] — before any object bytes are read. Mirrors
126/// the two carriers #699 actually has data for at this layer: a walked path
127/// (matches `Mount::walk`'s `&[&str]` component slice in `hyprstream-vfs`,
128/// without this crate depending on that crate) or a content identifier (a
129/// manifest CID / CAS hash).
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131pub enum ObjectRef<'a> {
132    /// Path components of a walked object (schema/synthetic mount nodes).
133    Path(&'a [&'a str]),
134    /// Content identifier of a content-addressed object (CAS manifest).
135    Cid(&'a [u8]),
136}
137
138/// The keyed seam the reference monitor (S2/#568) calls **before** constructing
139/// an `ObjectCtx` for the PDP: "resolve this walked reference to its security
140/// label." Distinct from [`LabeledObject`] (which answers for an object you
141/// already hold) — this answers for a reference you are about to walk.
142///
143/// `None` ⇒ **unresolvable** ⇒ the monitor MUST deny (design §1 invariant 2,
144/// same "no unlabeled-default-allow" rule as [`LabeledObject::security_label`]).
145/// Implementors must NOT manufacture a permissive default.
146pub trait ObjectLabelResolver {
147    /// Resolve `object` to its security label, or `None` if unresolvable.
148    fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel>;
149}
150
151/// Bind-time label clamp (#699 carrier c, D2 amendment ratified 2026-07-03):
152/// a client-controlled mount (the plan9 model — users compose their own
153/// namespaces) can label what it serves *up* but never *down below what it
154/// can read*, or a subject could read data at a high clearance through its own
155/// access and re-export it labeled low through its own mount — declassifying
156/// by re-serving.
157///
158/// `effective = join(binder_floor, declared)`. `join` (BLP least-upper-bound:
159/// max level, max assurance requirement, union of compartments) can only make
160/// the effective label *more* restrictive than either input, never less — so
161/// this is a floor, not a negotiation: `effective ⊒ binder_floor` and
162/// `effective ⊒ declared` always hold.
163///
164/// `binder_floor` is the binding subject's own [`super::context::SecurityContext`]
165/// clearance (what `Namespace::bind_mount`'s threaded `Subject` resolves to);
166/// `declared` is the label the mount asserts for what it serves.
167#[must_use]
168pub fn bind_time_label(binder_floor: SecurityLabel, declared: SecurityLabel) -> SecurityLabel {
169    binder_floor.join(&declared)
170}
171
172/// Foreign-label import floor (#699, D1/D2 amendment ratified 2026-07-03): a
173/// label asserted by a federated peer — whether a manifest's `security_label`
174/// or (per the D1 ruling) a remote node's own capnp-schema-derived label — is
175/// a **hint, not a guarantee**, when we act as a client of that peer. It is
176/// trusted only as far as the peer's own signer, never face-value across a
177/// domain boundary.
178///
179/// `effective = join(import_floor_for_that_peer, translated)`. Same clamp
180/// shape as [`bind_time_label`] (restrict-only, never escalates); the
181/// distinction is only which floor is being enforced — a local subject's own
182/// clearance there, a per-peer import ceiling here. `import_floor_for_that_peer`
183/// is the enrollment/perimeter-assigned ceiling for imports from that specific
184/// peer (see the atproto perimeter gateway, #549); `translated` is the peer's
185/// asserted label after perimeter translation into this node's lattice
186/// vocabulary.
187#[must_use]
188pub fn import_label(
189    import_floor_for_that_peer: SecurityLabel,
190    translated: SecurityLabel,
191) -> SecurityLabel {
192    import_floor_for_that_peer.join(&translated)
193}
194
195#[cfg(test)]
196#[allow(clippy::unwrap_used)]
197mod tests {
198    use super::super::label::{Assurance, CompartmentSet, Level};
199    use super::*;
200
201    #[test]
202    fn static_node_returns_declared_label() {
203        let l = SecurityLabel::new(Level::Internal, Assurance::Classical, CompartmentSet::EMPTY);
204        let node = StaticNodeLabel::labeled(l);
205        assert_eq!(node.security_label(), Some(l));
206    }
207
208    #[test]
209    fn unlabeled_static_node_returns_none() {
210        // → monitor denies. No permissive default.
211        assert!(StaticNodeLabel::unlabeled().security_label().is_none());
212    }
213
214    // A stub manifest demonstrating the seam compiles and fails closed.
215    struct StubManifest {
216        cid: Vec<u8>,
217        label: SecurityLabel,
218    }
219    impl LabeledObject for StubManifest {
220        fn security_label(&self) -> Option<SecurityLabel> {
221            Some(self.label)
222        }
223    }
224    impl ContentBoundLabel for StubManifest {
225        fn content_id(&self) -> &[u8] {
226            &self.cid
227        }
228        // intentionally does NOT override verify_binding → default false.
229    }
230
231    #[test]
232    fn content_bound_default_verify_fails_closed() {
233        let m = StubManifest {
234            cid: vec![1, 2, 3],
235            label: SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY),
236        };
237        assert!(
238            !m.verify_binding(),
239            "unimplemented binding check must fail closed"
240        );
241        assert_eq!(m.content_id(), &[1, 2, 3]);
242    }
243
244    // ── #699: ObjectLabelResolver seam + clamp invariants ────────────────────
245
246    fn label(level: Level) -> SecurityLabel {
247        SecurityLabel::new(level, Assurance::PqHybrid, CompartmentSet::EMPTY)
248    }
249
250    /// A stub resolver over both `ObjectRef` variants, demonstrating the seam
251    /// compiles and fails closed for an unknown reference.
252    struct StubResolver;
253    impl ObjectLabelResolver for StubResolver {
254        fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
255            match object {
256                ObjectRef::Path(["srv", "model", "qwen"]) => Some(label(Level::Confidential)),
257                ObjectRef::Cid(_) | ObjectRef::Path(_) => None,
258            }
259        }
260    }
261
262    #[test]
263    fn resolver_resolves_known_path_denies_unknown() {
264        let r = StubResolver;
265        assert_eq!(
266            r.resolve(ObjectRef::Path(&["srv", "model", "qwen"])),
267            Some(label(Level::Confidential))
268        );
269        assert!(
270            r.resolve(ObjectRef::Path(&["srv", "model", "unknown"]))
271                .is_none(),
272            "an unresolvable reference must deny, not fall back to a default label"
273        );
274        assert!(r.resolve(ObjectRef::Cid(&[9, 9, 9])).is_none());
275    }
276
277    /// Bind-time clamp: a mount can label what it serves MORE restrictive than
278    /// its binder's own floor, but never less — the declassification/re-export
279    /// laundering case the D2 amendment closes.
280    #[test]
281    fn bind_time_label_cannot_declassify_below_the_binder_floor() {
282        let floor = label(Level::Secret);
283
284        // Attempt to re-export Secret-read data as Public: the clamp raises it
285        // back to (at least) Secret.
286        let declared_low = label(Level::Public);
287        let effective = bind_time_label(floor, declared_low);
288        assert_eq!(
289            effective.level,
290            Level::Secret,
291            "declaring a lower label must not lower the effective label below the binder's floor"
292        );
293
294        // Declaring MORE restrictive than the floor is honored as declared.
295        let declared_high =
296            SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY);
297        let effective_high = bind_time_label(floor, declared_high);
298        assert_eq!(effective_high, declared_high.join(&floor));
299    }
300
301    /// Import clamp: a peer's asserted label is honored only up to the
302    /// per-peer import ceiling — a permissive peer cannot hand us a label more
303    /// permissive than our own floor for that peer.
304    #[test]
305    fn import_label_cannot_exceed_peer_floor_downward() {
306        let peer_floor = label(Level::Internal);
307        let peer_asserts = label(Level::Public); // a peer claiming its data is public
308        let effective = import_label(peer_floor, peer_asserts);
309        assert_eq!(
310            effective.level,
311            Level::Internal,
312            "a peer's permissive self-assertion cannot go below our import floor for that peer"
313        );
314    }
315
316    /// Both clamps are restrict-only: the effective label's level is always
317    /// the MAXIMUM of the two inputs' levels — never a mix that is LESS
318    /// restrictive than either (the property that makes this a floor, not a
319    /// negotiation).
320    #[test]
321    fn clamps_never_produce_a_label_less_restrictive_than_either_input() {
322        let a = label(Level::Confidential);
323        let b = label(Level::Internal);
324        let joined = bind_time_label(a, b);
325        assert_eq!(joined.level, Level::Confidential.max(Level::Internal));
326        assert!(joined.level >= a.level);
327        assert!(joined.level >= b.level);
328    }
329}