Skip to main content

hyprstream_rpc/auth/mac/
genesis.rs

1//! **Genesis labeling** — the initial-SID / `file_contexts` equivalent.
2//!
3//! Design §1 invariant 2 + the S1 acceptance criteria: *every* existing object
4//! and service must carry a label **before** enforcement turns on. Without
5//! genesis, enabling MAC denies everything (an unlabeled object = deny). With a
6//! *permissive* genesis (label-everything-public), MAC is a no-op. So genesis
7//! is the security-critical bootstrap: it must be **explicit, total, and
8//! audited** — every static node mapped to a declared label, with NO catch-all
9//! that silently lifts coverage.
10//!
11//! This module provides the genesis *mechanism* (a deterministic map from node
12//! path → label, with a completeness check). The genesis *content* (the actual
13//! path→label table) comes from the schema `$scope`/TE annotations (S3, #569)
14//! and site policy; S1 supplies the seam + the fail-closed completeness gate.
15//!
16//! Key property: [`GenesisMap::resolve`] returns `None` for any path not
17//! explicitly assigned. There is deliberately **no default label** — an
18//! unmapped node is unlabeled, hence denied. The operator closes the gap by
19//! adding an explicit assignment, never by widening a default.
20
21use super::label::SecurityLabel;
22use super::lattice::{LabelError, Lattice};
23use super::manifest::StaticNodeLabel;
24use std::collections::BTreeMap;
25
26/// The result of checking genesis completeness over a known set of nodes.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct GenesisReport {
29    /// Nodes that have an explicit, well-formed label assignment.
30    pub labeled: Vec<String>,
31    /// Nodes with NO assignment — these are denied at runtime. Enforcement
32    /// MUST NOT be enabled while this is non-empty (or each entry is an
33    /// intentional, audited deny).
34    pub unlabeled: Vec<String>,
35    /// Assignments whose label is ill-formed under the active lattice (e.g.
36    /// references an unknown compartment). Fail-closed: treated as gaps.
37    pub ill_formed: Vec<(String, LabelError)>,
38}
39
40impl GenesisReport {
41    /// Genesis is **complete** iff every known node is labeled with a
42    /// well-formed label (no gaps, no ill-formed assignments). Enforcement may
43    /// only be enabled when this is true. This is the gate that prevents both
44    /// "deny everything" (gaps) and "trust a typo'd label".
45    pub fn is_complete(&self) -> bool {
46        self.unlabeled.is_empty() && self.ill_formed.is_empty()
47    }
48}
49
50/// A deterministic, explicit map from a static node path to its genesis label.
51///
52/// Built once at startup from the schema annotations + site policy. There is no
53/// wildcard fallthrough to a default label — coverage is by explicit assignment
54/// only. (A site MAY add an explicit `"*"`-style rule in its *source* policy,
55/// but it must materialize to concrete per-node assignments here so the
56/// completeness check sees real coverage, not an implicit catch-all.)
57#[derive(Debug, Clone, Default)]
58pub struct GenesisMap {
59    assignments: BTreeMap<String, SecurityLabel>,
60}
61
62impl GenesisMap {
63    pub fn new() -> Self {
64        GenesisMap::default()
65    }
66
67    /// Assign a genesis label to a node path. Returns `self` for chaining.
68    pub fn assign(mut self, path: impl Into<String>, label: SecurityLabel) -> Self {
69        self.assignments.insert(path.into(), label);
70        self
71    }
72
73    /// The label for a node path, if explicitly assigned. `None` ⇒ unlabeled
74    /// ⇒ deny. **No default.**
75    pub fn resolve(&self, path: &str) -> Option<&SecurityLabel> {
76        self.assignments.get(path)
77    }
78
79    /// Resolve a node path to a [`StaticNodeLabel`], validating it against the
80    /// active lattice. An unassigned path or an ill-formed label both yield an
81    /// *unlabeled* node (fail-closed) — the distinction is surfaced only by
82    /// [`GenesisMap::report`] for operator visibility.
83    pub fn resolve_node(&self, path: &str, lattice: &Lattice) -> StaticNodeLabel {
84        match self.assignments.get(path) {
85            Some(label) if lattice.validate(label).is_ok() => StaticNodeLabel::labeled(*label),
86            _ => StaticNodeLabel::unlabeled(),
87        }
88    }
89
90    /// Check genesis completeness over the full set of nodes that *must* be
91    /// labeled (the schema's static-node inventory). Partitions every node into
92    /// labeled / unlabeled / ill-formed. This is the audited bootstrap gate.
93    pub fn report<'a>(
94        &self,
95        all_nodes: impl IntoIterator<Item = &'a str>,
96        lattice: &Lattice,
97    ) -> GenesisReport {
98        let mut labeled = Vec::new();
99        let mut unlabeled = Vec::new();
100        let mut ill_formed = Vec::new();
101
102        for node in all_nodes {
103            match self.assignments.get(node) {
104                None => unlabeled.push(node.to_owned()),
105                Some(label) => match lattice.validate(label) {
106                    Ok(()) => labeled.push(node.to_owned()),
107                    Err(e) => ill_formed.push((node.to_owned(), e)),
108                },
109            }
110        }
111        GenesisReport {
112            labeled,
113            unlabeled,
114            ill_formed,
115        }
116    }
117}
118
119#[cfg(test)]
120#[allow(clippy::unwrap_used)]
121mod tests {
122    use super::super::label::{Assurance, Compartment, CompartmentSet, Level};
123    use super::super::lattice::LatticeVersion;
124    use super::super::manifest::LabeledObject;
125    use super::*;
126
127    fn comp(s: &str) -> Compartment {
128        Compartment::new(s)
129    }
130
131    fn lattice() -> Lattice {
132        // 2-compartment vocabulary → bits 0 ("pii") and 1 ("health").
133        Lattice::new(LatticeVersion(1), [comp("pii"), comp("health")])
134    }
135
136    fn map() -> GenesisMap {
137        let l = lattice();
138        GenesisMap::new()
139            .assign(
140                "/health",
141                SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY),
142            )
143            .assign(
144                "/ctl/policy",
145                l.label(Level::Secret, Assurance::PqHybrid, [comp("pii")])
146                    .unwrap(),
147            )
148    }
149
150    #[test]
151    fn resolve_returns_assigned_label_only() {
152        let m = map();
153        assert!(m.resolve("/health").is_some());
154        assert!(m.resolve("/unknown").is_none()); // no default → deny
155    }
156
157    #[test]
158    fn resolve_node_unassigned_is_unlabeled() {
159        let node = map().resolve_node("/nope", &lattice());
160        assert!(node.security_label().is_none());
161    }
162
163    #[test]
164    fn resolve_node_assigned_is_labeled() {
165        let node = map().resolve_node("/health", &lattice());
166        assert!(node.security_label().is_some());
167    }
168
169    #[test]
170    fn report_detects_gaps() {
171        let report = map().report(
172            ["/health", "/ctl/policy", "/streams", "/metrics"],
173            &lattice(),
174        );
175        assert_eq!(report.labeled.len(), 2);
176        // `report` preserves input order of `all_nodes`.
177        assert_eq!(
178            report.unlabeled,
179            vec!["/streams".to_owned(), "/metrics".to_owned()]
180        );
181        assert!(!report.is_complete());
182    }
183
184    #[test]
185    fn report_complete_when_all_labeled() {
186        let report = map().report(["/health", "/ctl/policy"], &lattice());
187        assert!(report.is_complete());
188        assert!(report.unlabeled.is_empty());
189        assert!(report.ill_formed.is_empty());
190    }
191
192    #[test]
193    fn report_flags_ill_formed_label_as_not_complete() {
194        // a label naming an unknown compartment is ill-formed → fail-closed.
195        // Bit 9 is not registered in the 2-compartment vocabulary → ill-formed.
196        let m = GenesisMap::new().assign(
197            "/bad",
198            SecurityLabel::from_bits(Level::Public, Assurance::Classical, [9]),
199        );
200        let report = m.report(["/bad"], &lattice());
201        assert!(report.labeled.is_empty());
202        assert_eq!(report.ill_formed.len(), 1);
203        assert!(!report.is_complete());
204    }
205
206    #[test]
207    fn ill_formed_label_resolves_as_unlabeled() {
208        // Bit 9 is not registered in the 2-compartment vocabulary → ill-formed.
209        let m = GenesisMap::new().assign(
210            "/bad",
211            SecurityLabel::from_bits(Level::Public, Assurance::Classical, [9]),
212        );
213        // resolve_node fails closed: ill-formed → unlabeled → deny.
214        assert!(m
215            .resolve_node("/bad", &lattice())
216            .security_label()
217            .is_none());
218    }
219}