Skip to main content

hyprstream_rpc/auth/mac/
bind.rs

1//! **Carrier (c) — bind-time labels for synthetic VFS mounts** (#699 scope item 1,
2//! epic #547).
3//!
4//! A synthetic mount (one a subject binds into its own namespace, the Plan 9
5//! composition model) carries a security label computed at bind time from two
6//! inputs the binder supplies:
7//!
8//! - **`binder_floor`** — the binding subject's own clearance floor. Not optional:
9//!   a mount must carry a label, and that label can never be *less* restrictive
10//!   than what the binder is itself cleared to read (otherwise a subject could
11//!   re-export high-clearance data through its own mount labeled low —
12//!   declassification by re-serving, the D2 amendment case).
13//! - **`declared`** — the label the mount asserts for what it serves.
14//!
15//! The effective label is [`bind_time_label`]`binder_floor.join(declared)` — the
16//! BLP least-upper-bound, a floor not a negotiation. Every node beneath the mount
17//! is clamped to *at least* this label ([`BindLabelMap::resolve`] returns it for a
18//! descendant), and a descendant's own carrier-(a) label is joined on top
19//! ([`clamp_descendant`]) — restrict-only, never less.
20//!
21//! ## No escape hatch
22//!
23//! There is **no label-less bind**. [`BindLabelMap::bind`] takes both inputs as
24//! `SecurityLabel` (not `Option`), so a mount cannot be constructed without a
25//! label at the type level — and a path under a prefix that was never bound
26//! resolves to `None` ⇒ **deny** (the MAC model has no default label; absence is
27//! denial — the same invariant `hyprstream::mac::exchange` states for grants).
28//! There is no `Default`, no
29//! `NotApplicable`, no flag that turns the clamp off.
30
31use std::collections::BTreeMap;
32
33use super::label::SecurityLabel;
34use super::manifest::bind_time_label;
35
36/// The effective bind-time label a synthetic mount carries: the restrict-only
37/// join of the binder's floor and the mount's declared label, via
38/// [`bind_time_label`].
39///
40/// Constructed only by [`BindLabelMap::bind`], which guarantees the label is
41/// `⊒ binder_floor` and `⊒ declared` (the join can only raise, never lower).
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct BindLabel(SecurityLabel);
44
45impl BindLabel {
46    /// The effective label everything beneath this mount is clamped to.
47    pub fn effective(&self) -> SecurityLabel {
48        self.0
49    }
50}
51
52/// The set of synthetic-mount bind-time labels keyed by mount prefix.
53///
54/// This is the carrier-(c) companion to [`super::genesis::GenesisMap`] (carrier
55/// (a) static nodes): where genesis labels the *generated* `/srv/{name}` surface
56/// from schema annotations, this labels the *synthetic* mounts a subject composes
57/// into its own namespace, from the binder's floor × the mount's declared label.
58///
59/// Both carriers feed the same [`super::manifest::ObjectLabelResolver`] at
60/// enforcement time; this type is the pure-data source for the bind-time half.
61#[derive(Debug, Clone, Default)]
62pub struct BindLabelMap {
63    /// Normalized absolute prefix → effective bind-time label.
64    bindings: BTreeMap<String, BindLabel>,
65}
66
67impl BindLabelMap {
68    /// An empty bind-label map.
69    pub fn new() -> Self {
70        BindLabelMap::default()
71    }
72
73    /// Bind `binder_floor × declared` at `prefix`, storing the effective
74    /// [`bind_time_label`] and returning the stored label by value.
75    ///
76    /// **Both labels are mandatory** (`SecurityLabel`, not `Option`): there is no
77    /// label-less bind — a synthetic mount must carry a label, and this is the
78    /// only way to add one. The effective label is the restrict-only join, so it
79    /// is always `⊒ binder_floor` and `⊒ declared`.
80    pub fn bind(
81        &mut self,
82        prefix: &str,
83        binder_floor: SecurityLabel,
84        declared: SecurityLabel,
85    ) -> BindLabel {
86        let normalized = normalize_prefix(prefix);
87        let effective = bind_time_label(binder_floor, declared);
88        let entry = BindLabel(effective);
89        self.bindings.insert(normalized, entry);
90        entry
91    }
92
93    /// The effective label a mount bound at `prefix` carries, if any. A prefix
94    /// that was never bound ⇒ `None` ⇒ unlabeled ⇒ deny.
95    pub fn label_for(&self, prefix: &str) -> Option<SecurityLabel> {
96        self.bindings
97            .get(&normalize_prefix(prefix))
98            .map(BindLabel::effective)
99    }
100
101    /// Resolve a walked object (path components relative to the namespace root)
102    /// to the effective bind-time label of the **nearest enclosing** synthetic
103    /// mount — the floor every node beneath that mount is clamped to.
104    ///
105    /// Walks from the full path up its ancestors; the first bound prefix found is
106    /// the enclosing mount, and its label is the descendant floor (the clamp).
107    /// `None` ⇒ no enclosing labeled mount ⇒ unlabeled ⇒ deny.
108    pub fn resolve(&self, components: &[&str]) -> Option<SecurityLabel> {
109        let full = components.len();
110        let mut depth = full;
111        while depth > 0 {
112            let path = join_components(&components[..depth]);
113            if let Some(entry) = self.bindings.get(&path) {
114                return Some(entry.effective());
115            }
116            depth -= 1;
117        }
118        None
119    }
120
121    /// Whether any synthetic mount has been bound.
122    pub fn is_empty(&self) -> bool {
123        self.bindings.is_empty()
124    }
125
126    /// The number of bound synthetic mounts.
127    pub fn len(&self) -> usize {
128        self.bindings.len()
129    }
130
131    /// Iterate the bound `(prefix, effective-label)` pairs.
132    pub fn iter(&self) -> impl Iterator<Item = (&str, SecurityLabel)> {
133        self.bindings
134            .iter()
135            .map(|(p, b)| (p.as_str(), b.effective()))
136    }
137}
138
139/// Clamp a descendant node's own (carrier-a/manifest) label to at least its
140/// enclosing mount's bind-time floor.
141///
142/// `effective = mount_floor.join(node_label)` — restrict-only: the descendant's
143/// effective label is `⊒ mount_floor` and `⊒ node_label`. A node that *declares*
144/// a less-restrictive label than its mount cannot lower the effective label below
145/// the mount's floor (the declassification-by-declaration case the clamp closes).
146/// A node may always declare itself *more* restrictive.
147#[must_use]
148pub fn clamp_descendant(mount_floor: SecurityLabel, node_label: SecurityLabel) -> SecurityLabel {
149    mount_floor.join(&node_label)
150}
151
152/// Normalize a prefix to a canonical absolute form: leading slash, no trailing
153/// slash, no empty components (`"/srv/model/"`, `"srv/model"` → `"/srv/model"`).
154/// The empty/`"/"` prefix normalizes to `""` and is never stored (the namespace
155/// root is not itself an addressable mount here).
156fn normalize_prefix(prefix: &str) -> String {
157    join_components(&prefix.split('/').collect::<Vec<_>>())
158}
159
160/// Join path components into a normalized absolute path (`["srv","model"]` →
161/// `"/srv/model"`), skipping empty components.
162fn join_components(components: &[&str]) -> String {
163    let mut out = String::new();
164    for c in components {
165        if c.is_empty() {
166            continue;
167        }
168        out.push('/');
169        out.push_str(c);
170    }
171    out
172}
173
174#[cfg(test)]
175#[allow(clippy::unwrap_used)]
176mod tests {
177    use super::super::label::{Assurance, CompartmentSet, Level};
178    use super::*;
179
180    fn label(level: Level) -> SecurityLabel {
181        SecurityLabel::new(level, Assurance::PqHybrid, CompartmentSet::EMPTY)
182    }
183
184    // ── Test (2): a mount without a label fails to construct ──────────────────
185    //
186    // `bind` takes both labels as `SecurityLabel` (not Option), so a label-less
187    // mount is unconstructible at the type level. Runtime mirror: a path under a
188    // prefix that was never bound resolves to None ⇒ deny (no default label).
189
190    #[test]
191    fn unbound_prefix_resolves_to_none_deny() {
192        // A namespace where /srv/model is bound but /srv/policy is not.
193        let mut map = BindLabelMap::new();
194        map.bind("/srv/model", label(Level::Internal), label(Level::Internal));
195        // /srv/policy carries no label → its descendants are denied.
196        assert!(
197            map.resolve(&["srv", "policy", "config"]).is_none(),
198            "a path under a mount that carries no label must deny, not fall back to a default"
199        );
200    }
201
202    #[test]
203    fn bind_requires_both_labels_type_level() {
204        // The only `bind` constructor takes (binder_floor, declared) as
205        // SecurityLabel. The effective label is the join of exactly those two —
206        // there is no third "no-label" path the caller can reach.
207        let mut map = BindLabelMap::new();
208        let b = map.bind(
209            "/srv/model",
210            label(Level::Internal),
211            label(Level::Confidential),
212        );
213        // effective = join(Internal, Confidential) = Confidential.
214        assert_eq!(b.effective().level, Level::Confidential);
215    }
216
217    // ── Test (3): a node beneath a mount is clamped to at least the floor ─────
218
219    #[test]
220    fn descendant_inherits_mount_effective_label() {
221        let mut map = BindLabelMap::new();
222        // A Secret-cleared binder declares Internal; effective = Secret (floor wins).
223        map.bind("/srv/policy", label(Level::Secret), label(Level::Internal));
224        let under = map
225            .resolve(&["srv", "policy", "config", "current"])
226            .unwrap();
227        assert_eq!(
228            under.level,
229            Level::Secret,
230            "a descendant is clamped to at least the mount's effective floor"
231        );
232    }
233
234    // ── Test (4): the clamp is restrict-only ──────────────────────────────────
235
236    #[test]
237    fn clamp_descendant_is_restrict_only() {
238        let mount_floor = label(Level::Secret);
239        // A node that declares itself LESS restrictive than its mount cannot
240        // lower the effective label below the mount floor.
241        let node_declared_low = label(Level::Public);
242        assert_eq!(
243            clamp_descendant(mount_floor, node_declared_low).level,
244            Level::Secret,
245            "a descendant declaring a lower label cannot lower below the mount floor"
246        );
247        // A node that declares itself MORE restrictive is honored as-is (still ⊒ mount).
248        let node_declared_higher = SecurityLabel::new(
249            Level::Secret,
250            Assurance::PqHybrid,
251            CompartmentSet::single(0),
252        );
253        let clamped = clamp_descendant(mount_floor, node_declared_higher);
254        assert!(clamped.compartments.contains(0));
255        assert!(clamped.level >= mount_floor.level);
256    }
257
258    #[test]
259    fn effective_label_never_below_binder_floor() {
260        // The D2 invariant: re-exporting Secret-read data as Public via a mount
261        // the binder labeled low still clamps back to (at least) Secret.
262        let mut map = BindLabelMap::new();
263        map.bind("/reexport", label(Level::Secret), label(Level::Public));
264        let effective = map.label_for("/reexport").unwrap();
265        assert_eq!(
266            effective.level,
267            Level::Secret,
268            "bind_time_label must not let a declared-low mount go below the binder floor"
269        );
270    }
271
272    #[test]
273    fn resolve_walks_to_nearest_enclosing_mount() {
274        let mut map = BindLabelMap::new();
275        map.bind("/srv", label(Level::Public), label(Level::Public));
276        map.bind("/srv/model", label(Level::Internal), label(Level::Internal));
277        // /srv/model/qwen/status → nearest is /srv/model (Internal), not /srv.
278        assert_eq!(
279            map.resolve(&["srv", "model", "qwen", "status"])
280                .unwrap()
281                .level,
282            Level::Internal
283        );
284        // /srv/other → nearest is /srv (Public).
285        assert_eq!(map.resolve(&["srv", "other"]).unwrap().level, Level::Public);
286    }
287
288    #[test]
289    fn empty_map_denies_everything() {
290        let map = BindLabelMap::new();
291        assert!(map.is_empty());
292        assert!(map.resolve(&["anything"]).is_none());
293    }
294}