Skip to main content

hyprstream_core/mac/
genesis.rs

1//! **Production genesis labeling** — content, enumeration, resolution, and the
2//! boot-time coverage gate for the native-MAC data plane (S1 activation, #567,
3//! epic #547).
4//!
5//! S1's *mechanism* already lives in [`hyprstream_rpc::auth::mac::genesis`]:
6//! [`GenesisMap`] (an explicit path→label map with **no** catch-all default) and
7//! [`GenesisReport`] (the completeness gate). This module supplies the pieces the
8//! mechanism can't: the actual *content* and the wiring that turns "a map exists"
9//! into "every node in the running namespace is covered, and here is the
10//! evidence."
11//!
12//! Four net-new pieces, in the order the boot path uses them:
13//!
14//! 1. [`NamespaceEnumerator`] — walks the production export surface (the
15//!    `/srv/{name}` service inventory + the export-root skeleton +, optionally, a
16//!    live [`Namespace`]'s mount prefixes) to produce the **node set** the
17//!    completeness check runs against. Without a concrete node set the report is
18//!    vacuous; this is what makes "every existing object" a finite, checkable
19//!    list.
20//! 2. [`SitePolicy`] — the site-policy label table. A small set of **explicit**
21//!    per-node rules plus a conservative **floor**, [materialized](SitePolicy::materialize)
22//!    into concrete per-node [`GenesisMap`] assignments. This is the sanctioned
23//!    "explicit `*`-style rule that materializes to concrete assignments" the
24//!    genesis mechanism permits — never an implicit catch-all inside the map.
25//! 3. [`CompositeObjectLabelResolver`] — the production [`ObjectLabelResolver`]:
26//!    genesis static nodes → bind-time D2 descendant inheritance → CAS
27//!    [`BlobManifest`](crate::storage::cas::manifest::BlobManifest)-carried
28//!    labels; a manifest present but unlabeled is denied; anything
29//!    unresolvable returns `None` ⇒ deny.
30//! 4. [`GenesisGate`] — constructed at boot: it runs the enumerator, materialize,
31//!    and report, and holds the resolver, so the startup path can log/emit the
32//!    [`GenesisReport`] and a status surface can render coverage evidence.
33//!
34//! The production resolver is consumed by the authoritative 9P translator PEP.
35//! Missing and unlabeled objects deny; there is no permissive fallback.
36
37use std::collections::{BTreeMap, BTreeSet};
38use std::sync::Arc;
39
40use hyprstream_rpc::auth::mac::{
41    clamp_descendant, import_label, Assurance, BindLabelMap, GenesisMap, GenesisReport, Lattice,
42    LatticeVersion, Level, ObjectLabelResolver, ObjectRef, SecurityLabel,
43};
44use hyprstream_rpc::metadata::VfsNodeTable;
45
46/// The export-root skeleton nodes the host VFS composes under (mirrors
47/// `server::routes::ninep::build_export_mount` + the `#730` host VFS layout).
48/// These are structural container directories, always present regardless of which
49/// services are running.
50pub const EXPORT_ROOTS: &[&str] = &["/", "/srv", "/worktree", "/stream"];
51
52/// Non-service mount points the standard namespace binds (see
53/// `services::namespace_builder::build_standard_namespace` and
54/// [`hyprstream_vfs::STANDARD_NAMESPACE_PATHS`]). `/srv/model` and `/srv/registry`
55/// are *also* services, so they're covered by the service inventory; these are the
56/// ones that are not services.
57pub const STANDARD_NON_SERVICE_MOUNTS: &[&str] = &["/bin", "/env", "/lang/tcl"];
58
59// ────────────────────────────────────────────────────────────────────────────
60// 1. Namespace enumerator
61// ────────────────────────────────────────────────────────────────────────────
62
63/// Accumulates the set of node paths a genesis must cover, deduplicated and
64/// deterministically ordered.
65///
66/// The enumerator is intentionally *source-agnostic*: it collects candidate node
67/// paths from whichever surfaces are available (the compile-time service factory
68/// inventory, the export-root skeleton, a live [`Namespace`]'s mount prefixes) and
69/// normalizes them into one sorted, deduplicated set. The completeness check
70/// ([`GenesisReport`]) then runs against exactly this set — so the report's node
71/// list is only as complete as what the enumerator was told to walk. Adding a new
72/// export surface means adding a source here, not changing the mechanism.
73#[derive(Debug, Clone, Default)]
74pub struct NamespaceEnumerator {
75    nodes: BTreeSet<String>,
76}
77
78impl NamespaceEnumerator {
79    /// An empty enumerator.
80    pub fn new() -> Self {
81        NamespaceEnumerator::default()
82    }
83
84    /// The default production node set: export-root skeleton + every registered
85    /// `/srv/{name}` service mount + the standard non-service mounts. This is the
86    /// set a daemon exports today; it's derived from the compile-time inventory so
87    /// it needs no running namespace.
88    pub fn production() -> Self {
89        NamespaceEnumerator::new()
90            .with_export_roots()
91            .with_service_inventory()
92            .with_standard_mounts()
93    }
94
95    /// Add the export-root skeleton nodes ([`EXPORT_ROOTS`]).
96    pub fn with_export_roots(mut self) -> Self {
97        for root in EXPORT_ROOTS {
98            self.push(root);
99        }
100        self
101    }
102
103    /// Add `/srv/{name}` for every service registered via `#[service_factory]`
104    /// (the inventory the daemon actually mounts under `/srv`).
105    pub fn with_service_inventory(mut self) -> Self {
106        for factory in hyprstream_service::list_factories() {
107            self.push(&format!("/srv/{}", factory.name));
108        }
109        self
110    }
111
112    /// Add the standard non-service mount points ([`STANDARD_NON_SERVICE_MOUNTS`]).
113    pub fn with_standard_mounts(mut self) -> Self {
114        for mount in STANDARD_NON_SERVICE_MOUNTS {
115            self.push(mount);
116        }
117        self
118    }
119
120    /// Add every mount prefix of a live [`Namespace`] (e.g. a composed export
121    /// namespace). Complements the static inventory with whatever a particular
122    /// process actually bound at runtime.
123    pub fn with_namespace(mut self, ns: &hyprstream_vfs::Namespace) -> Self {
124        for prefix in ns.mount_prefixes() {
125            self.push(prefix);
126        }
127        self
128    }
129
130    /// Add a single explicit node path (site-specific extension point).
131    pub fn with_node(mut self, path: impl AsRef<str>) -> Self {
132        self.push(path.as_ref());
133        self
134    }
135
136    fn push(&mut self, path: &str) {
137        let normalized = normalize_node_path(path);
138        if !normalized.is_empty() {
139            self.nodes.insert(normalized);
140        }
141    }
142
143    /// The number of distinct nodes collected.
144    pub fn len(&self) -> usize {
145        self.nodes.len()
146    }
147
148    /// Whether no nodes have been collected.
149    pub fn is_empty(&self) -> bool {
150        self.nodes.is_empty()
151    }
152
153    /// The collected node set, sorted and deduplicated.
154    pub fn into_nodes(self) -> Vec<String> {
155        self.nodes.into_iter().collect()
156    }
157
158    /// Borrow the collected node set (sorted, deduplicated).
159    pub fn nodes(&self) -> impl Iterator<Item = &str> {
160        self.nodes.iter().map(String::as_str)
161    }
162}
163
164/// Normalize a node path to a canonical absolute form: leading slash, no trailing
165/// slash, no empty components. `""`/`"/"` normalize to the addressable root.
166fn normalize_node_path(path: &str) -> String {
167    let mut out = String::new();
168    for component in path.split('/') {
169        if component.is_empty() {
170            continue;
171        }
172        out.push('/');
173        out.push_str(component);
174    }
175    if out.is_empty() {
176        "/".to_owned()
177    } else {
178        out
179    }
180}
181
182// ────────────────────────────────────────────────────────────────────────────
183// 2. Genesis content source (site-policy table)
184// ────────────────────────────────────────────────────────────────────────────
185
186/// The floor label for the existing world: `(Public, Unverified, {})` — the
187/// lattice bottom. Used as the D2 clamp target for descendants / unlabeled
188/// carriers and as the value for explicitly-public structural nodes.
189pub fn floor_label() -> SecurityLabel {
190    SecurityLabel::bottom()
191}
192
193/// The genesis lattice the floor labels are validated against.
194///
195/// The floor content carries **no compartments** (compartment vocabulary is S3's
196/// job, #569), so an empty-vocabulary lattice validates every floor label. When S3
197/// lands a real `$scope`-derived vocabulary, this is where it's swapped in — the
198/// rest of this module is unchanged.
199pub fn genesis_lattice() -> Lattice {
200    Lattice::new(LatticeVersion(1), [])
201}
202
203/// A site-policy label table: a set of **explicit** per-node rules plus a
204/// conservative floor for every other enumerated node.
205///
206/// This is the genesis *content*. It is deliberately not a wildcard matcher: rules
207/// are keyed on the exact normalized node path, and [`materialize`](Self::materialize)
208/// emits one concrete [`GenesisMap`] assignment per enumerated node (matched rule,
209/// else the floor). That materialization is what the genesis mechanism sanctions —
210/// the completeness check then sees real per-node coverage, never an implicit
211/// catch-all inside the map.
212///
213/// The default ([`SitePolicy::conservative`]) reflects the current world's actual
214/// sensitivity — control-plane services above data services above public
215/// structure — so the genesis is *not* the "label-everything-public" no-op the
216/// mechanism warns against. Real per-node labels ultimately come from S3
217/// `$scope`/TE annotations; this table is the site-policy seam until then.
218#[derive(Debug, Clone)]
219pub struct SitePolicy {
220    /// Exact node path → label. Longest wins is unnecessary because materialize
221    /// runs over a finite enumerated node set and each rule is an exact match.
222    rules: std::collections::BTreeMap<String, SecurityLabel>,
223    /// Label materialized for any enumerated node without an explicit rule.
224    floor: SecurityLabel,
225}
226
227impl SitePolicy {
228    /// A site policy with only a floor and no explicit elevations. Every
229    /// enumerated node materializes to `floor`.
230    pub fn floor_only(floor: SecurityLabel) -> Self {
231        SitePolicy {
232            rules: std::collections::BTreeMap::new(),
233            floor,
234        }
235    }
236
237    /// The default conservative site policy for the current world.
238    ///
239    /// - **Control plane** (`policy`, `oauth`, `ledger`) → `Confidential`: the
240    ///   authorization/identity/audit services are the most sensitive surface.
241    /// - **Data / internal services** and the non-service mounts → `Internal`
242    ///   (the floor): model/registry/worker/etc. content is org-internal, not
243    ///   world-readable.
244    /// - **Structural export roots** (`/srv`, `/worktree`, `/stream`) → `Public`:
245    ///   these are container directories whose *listing* is not itself sensitive.
246    ///
247    /// Assurance is left at the `Unverified` floor across the board: elevating the
248    /// crypto-assurance axis (#548) is a per-object decision, not a blanket
249    /// genesis floor — a genesis that demanded `PqHybrid` everywhere would make
250    /// most objects unreachable before the assurance-binding layer is wired.
251    pub fn conservative() -> Self {
252        let internal =
253            SecurityLabel::new(Level::Internal, Assurance::Unverified, Default::default());
254        let confidential = SecurityLabel::new(
255            Level::Confidential,
256            Assurance::Unverified,
257            Default::default(),
258        );
259        let public = SecurityLabel::new(Level::Public, Assurance::Unverified, Default::default());
260
261        let mut rules = std::collections::BTreeMap::new();
262        // Control-plane services.
263        for name in ["policy", "oauth", "ledger"] {
264            rules.insert(format!("/srv/{name}"), confidential);
265        }
266        // Structural export roots (directory listings, not sensitive content).
267        for root in EXPORT_ROOTS {
268            rules.insert(normalize_node_path(root), public);
269        }
270        SitePolicy {
271            rules,
272            floor: internal,
273        }
274    }
275
276    /// Add or override an explicit per-node rule (builder).
277    pub fn with_rule(mut self, path: impl AsRef<str>, label: SecurityLabel) -> Self {
278        self.rules.insert(normalize_node_path(path.as_ref()), label);
279        self
280    }
281
282    /// The floor label materialized for unmatched nodes.
283    pub fn floor(&self) -> SecurityLabel {
284        self.floor
285    }
286
287    /// The label this policy assigns to `node`: its explicit rule if any, else the
288    /// floor. Total — every node gets a concrete label (that's the point).
289    pub fn label_for(&self, node: &str) -> SecurityLabel {
290        let normalized = normalize_node_path(node);
291        self.rules.get(&normalized).copied().unwrap_or(self.floor)
292    }
293
294    /// Materialize this policy into a [`GenesisMap`] over `nodes`: one explicit
295    /// assignment per node (matched rule, else floor). No implicit catch-all is
296    /// left in the map — every assignment is concrete, so the completeness check
297    /// sees real coverage.
298    pub fn materialize<'a>(&self, nodes: impl IntoIterator<Item = &'a str>) -> GenesisMap {
299        let mut map = GenesisMap::new();
300        for node in nodes {
301            map = map.assign(node, self.label_for(node));
302        }
303        map
304    }
305}
306
307// ────────────────────────────────────────────────────────────────────────────
308// 3. Composite production ObjectLabelResolver
309// ────────────────────────────────────────────────────────────────────────────
310
311/// Resolves a content-addressed object (a CAS [`BlobManifest`]) to its carried
312/// label. The seam between the composite resolver and the CAS manifest store.
313///
314/// The outer `Option` is "does a manifest exist for this CID?" and the inner is
315/// the manifest's `security_label` carrier field:
316/// - `Some(Some(label))` — manifest present and labeled ⇒ use the label.
317/// - `Some(None)` — manifest present but unlabeled ⇒ deny.
318/// - `None` — no manifest for this CID ⇒ unresolvable ⇒ deny.
319pub trait ManifestLabelSource: Send + Sync {
320    /// The label carried by the manifest for `cid`, per the semantics above.
321    fn label_for(&self, cid: &[u8]) -> Option<Option<SecurityLabel>>;
322}
323
324/// The Stage-0 default manifest source: no CAS manifest store is wired to the
325/// resolver yet, so every CID is unresolvable (`None` ⇒ deny). Honest and
326/// fail-closed — it never invents a label for content it can't see.
327#[derive(Debug, Default, Clone, Copy)]
328pub struct NoManifests;
329
330impl ManifestLabelSource for NoManifests {
331    fn label_for(&self, _cid: &[u8]) -> Option<Option<SecurityLabel>> {
332        None
333    }
334}
335
336/// The production [`ObjectLabelResolver`]: composes the label sources the
337/// reference monitor needs, in priority order, and fails closed when none applies.
338///
339/// For a **path** reference:
340/// 1. **Carrier (a) deny-set** — a *generated* node whose schema declared no
341///    `$vfsMac` is unlabeled ⇒ **deny**. It does NOT inherit an ancestor's label
342///    (that would be a permissive default on a known surface the operator
343///    explicitly left unannotated). Only the *exact* path of a known unlabeled
344///    generated node denies; a path the inventory never saw still walks its
345///    ancestors.
346/// 2. **Carrier (c) bind-time floor** — a path *under* a synthetic mount
347///    ([`BindLabelMap`]) inherits that mount's bind-time floor, D2-joined with
348///    any genesis/generated label found below (the mount can only raise, never
349///    lower).
350/// 3. **Genesis static node** (incl. materialized carrier-(a) labels) — an exact
351///    assignment, or the nearest labeled non-structural-root ancestor.
352/// 4. None ⇒ `None` ⇒ deny.
353///
354/// For a **CID** reference: the CAS [`ManifestLabelSource`] — a present-but-
355/// unlabeled manifest denies, and an absent manifest denies.
356///
357/// Every arm honors the S1 invariant: an unresolvable reference returns `None`
358/// (deny), never a manufactured permissive default.
359pub struct CompositeObjectLabelResolver {
360    genesis: GenesisMap,
361    floor: SecurityLabel,
362    manifests: Arc<dyn ManifestLabelSource>,
363    /// Carrier (a): exact paths of generated nodes whose schema declared no
364    /// `$vfsMac` (or a non-`pq-hybrid` one). These **deny** — they do not fall
365    /// through to ancestor inheritance, because the operator left a *known*
366    /// surface unannotated and a permissive default there is exactly the silent
367    /// hole #1228 closes.
368    generated_unlabeled: BTreeSet<String>,
369    /// Carrier (c): synthetic-mount bind-time labels. Empty at boot (Stage 0 —
370    /// no composed mounts yet); the bind operation (`BindLabelMap::bind`, which
371    /// takes both labels as `SecurityLabel` — no label-less construction) feeds
372    /// this. `Arc` so the future PEP bind path and this resolver share one map.
373    binds: Arc<BindLabelMap>,
374}
375
376impl CompositeObjectLabelResolver {
377    /// Construct from a materialized genesis map, the D2 clamp floor, a CAS
378    /// manifest source, the carrier-(a) generated-node deny-set, and the
379    /// carrier-(c) bind-time label map.
380    pub fn new(
381        genesis: GenesisMap,
382        floor: SecurityLabel,
383        manifests: Arc<dyn ManifestLabelSource>,
384        generated_unlabeled: BTreeSet<String>,
385        binds: Arc<BindLabelMap>,
386    ) -> Self {
387        CompositeObjectLabelResolver {
388            genesis,
389            floor,
390            manifests,
391            generated_unlabeled,
392            binds,
393        }
394    }
395
396    /// Resolve a walked path (already split into components) to a label.
397    fn resolve_path(&self, components: &[&str]) -> Option<SecurityLabel> {
398        if components.is_empty() {
399            return self.genesis.resolve("/").copied();
400        }
401        let full = join_components(components);
402
403        // Carrier (a): a generated node whose schema declared no $vfsMac (or a
404        // non-pq-hybrid one) ⇒ unlabeled ⇒ deny. Do NOT walk ancestors — a known
405        // unannotated surface must not inherit a permissive label from its
406        // service mount (#1228).
407        if self.generated_unlabeled.contains(&full) {
408            return None;
409        }
410
411        // Carrier (c): nearest enclosing synthetic mount's bind-time floor (the
412        // D2 clamp target for everything beneath it). `BindLabelMap::resolve`
413        // already walks ancestors internally.
414        let bind_floor = self.binds.resolve(components);
415
416        // Genesis (incl. materialized carrier-a labels): nearest labeled
417        // ancestor, with the structural-root inheritance carve-out.
418        let node_label = self.resolve_genesis_label(components);
419
420        // D2-join the bind floor with the node label (restrict-only). Either
421        // alone is enough to label the object; neither ⇒ deny.
422        match (bind_floor, node_label) {
423            (Some(f), Some(l)) => Some(clamp_descendant(f, l)),
424            (Some(f), None) => Some(f),
425            (None, Some(l)) => Some(l),
426            (None, None) => None,
427        }
428    }
429
430    /// Walk ancestors for the nearest genesis assignment, honoring the
431    /// structural-root inheritance carve-out (a `/srv`/`/worktree`/`/stream`
432    /// Public label does NOT flow to descendants — otherwise the structural root
433    /// acts as an implicit permissive wildcard).
434    fn resolve_genesis_label(&self, components: &[&str]) -> Option<SecurityLabel> {
435        let full = components.len();
436        let mut depth = full;
437        while depth > 0 {
438            let path = join_components(&components[..depth]);
439            if let Some(label) = self.genesis.resolve(&path) {
440                let inherited = depth < full;
441                let structural_root = EXPORT_ROOTS.contains(&path.as_str());
442                if !inherited || !structural_root {
443                    return Some(*label);
444                }
445            }
446            depth -= 1;
447        }
448        None
449    }
450
451    /// Resolve a content identifier via the CAS manifest source.
452    fn resolve_cid(&self, cid: &[u8]) -> Option<SecurityLabel> {
453        match self.manifests.label_for(cid) {
454            // Manifest present and labeled ⇒ D2 import clamp to the boundary
455            // floor. `import_label` is the restrict-only join: a carried label
456            // can only ever be raised toward the floor, never returned below it,
457            // so a `Public` carrier under an `Internal` floor still clamps to
458            // `Internal` (D2 — object labels clamp to the importing boundary's
459            // floor, never returned unrestricted).
460            Some(Some(label)) => Some(import_label(self.floor, label)),
461            // Present-but-unlabeled and absent manifests both deny. Never
462            // manufacture a label or join either case to a floor.
463            Some(None) | None => None,
464        }
465    }
466}
467
468impl ObjectLabelResolver for CompositeObjectLabelResolver {
469    fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
470        match object {
471            ObjectRef::Path(components) => self.resolve_path(components),
472            ObjectRef::Cid(cid) => self.resolve_cid(cid),
473        }
474    }
475}
476
477/// Adapt the genesis/bind carrier resolver to the canonical cross-plane MAC
478/// resolver contract. For the VFS plane, `service_domain` is the normalized
479/// absolute object path and there is no browser method discriminator.
480///
481/// **RPC dispatch no longer routes through this adapter** (#1499): the
482/// dispatch PEP evaluates typed `(service, leaf/method)` rows from
483/// [`crate::mac::dispatch_labels`], so a bare service domain is never split
484/// as a path here. This impl serves the VFS/9P plane only
485/// ([`crate::mac::pep::production_vfs_pep`]).
486impl hyprstream_rpc::auth::mac::RpcObjectLabelResolver for CompositeObjectLabelResolver {
487    fn resolve(&self, service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
488        let components: Vec<&str> = service_domain
489            .split('/')
490            .filter(|component| !component.is_empty() && *component != "." && *component != "..")
491            .collect();
492        self.resolve_path(&components)
493    }
494}
495
496/// Join path components into a normalized absolute path (`["srv","model"]` →
497/// `"/srv/model"`), matching [`normalize_node_path`]'s output so genesis lookups
498/// hit.
499fn join_components(components: &[&str]) -> String {
500    let mut out = String::new();
501    for c in components {
502        if c.is_empty() {
503            continue;
504        }
505        out.push('/');
506        out.push_str(c);
507    }
508    out
509}
510
511// ────────────────────────────────────────────────────────────────────────────
512// 4. Startup gate + report surface
513// ────────────────────────────────────────────────────────────────────────────
514
515/// The boot-time genesis coverage gate: enumerate → materialize → report, holding
516/// the composite resolver ready for a PEP to consume once activation is decided.
517///
518/// Constructed once at startup. It does **not** enable enforcement — it produces
519/// the [`GenesisReport`] evidence (`is_complete()`, plus the `unlabeled` /
520/// `ill_formed` lists) the activation decision gates on, and it owns the
521/// production [`CompositeObjectLabelResolver`] that a real decider will later be
522/// wired to.
523pub struct GenesisGate {
524    nodes: Vec<String>,
525    lattice: Lattice,
526    report: GenesisReport,
527    resolver: CompositeObjectLabelResolver,
528    /// Carrier (a) coverage over the real generated-node inventory (#699). Kept
529    /// on the gate so an operator / status surface can see exactly which
530    /// generated nodes are annotated and which are findings.
531    generated: GeneratedNodeCoverage,
532}
533
534impl GenesisGate {
535    /// Build a gate from explicit parts, folding in the **real** generated-node
536    /// inventory (carrier (a), collected from every registered `VfsNodeTable`).
537    ///
538    /// The generated inventory is part of the gate, not a manually-callable
539    /// helper: a generated node whose schema declared no `$vfsMac` (or a
540    /// non-`pq-hybrid` one) is an unlabeled **finding** that makes the report
541    /// incomplete, so enforcement cannot be enabled until every reachable
542    /// generated object class is annotated. Labeled generated nodes are
543    /// materialized into the genesis map (so the resolver resolves them);
544    /// unlabeled ones go into the resolver's deny-set (so they deny, never
545    /// inherit an ancestor's label).
546    pub fn build(
547        nodes: Vec<String>,
548        lattice: Lattice,
549        policy: &SitePolicy,
550        manifests: Arc<dyn ManifestLabelSource>,
551    ) -> Self {
552        // Site-policy genesis over the enumerated MOUNT nodes only — generated
553        // node labels come exclusively from `$vfsMac` below, never from the
554        // site-policy floor (an unannotated generated node must deny, not pick
555        // up the floor).
556        let mut genesis = policy.materialize(nodes.iter().map(String::as_str));
557
558        // Carrier (a): the real generated-node inventory.
559        let generated = GeneratedNodeCoverage::for_all_services();
560        for (path, label) in &generated.labeled {
561            genesis = genesis.assign(path, *label);
562        }
563
564        // The report node set = mount nodes ∪ generated-node paths, so the
565        // completeness check covers every reachable object class.
566        let mut all_nodes: Vec<String> = nodes;
567        for (path, _) in &generated.labeled {
568            all_nodes.push(path.clone());
569        }
570        for path in &generated.unlabeled {
571            all_nodes.push(path.clone());
572        }
573        all_nodes.sort();
574        all_nodes.dedup();
575
576        let report = genesis.report(all_nodes.iter().map(String::as_str), &lattice);
577        let generated_unlabeled: BTreeSet<String> = generated.unlabeled.iter().cloned().collect();
578        // Carrier (c): Stage 0 — no synthetic mounts composed yet. The bind map
579        // is empty; the future bind operation (`BindLabelMap::bind`, which takes
580        // both labels as `SecurityLabel`) feeds the shared map the resolver
581        // consults. No label-less construction exists.
582        let binds = Arc::new(BindLabelMap::new());
583        let resolver = CompositeObjectLabelResolver::new(
584            genesis,
585            policy.floor(),
586            manifests,
587            generated_unlabeled,
588            binds,
589        );
590        GenesisGate {
591            nodes: all_nodes,
592            lattice,
593            report,
594            resolver,
595            generated,
596        }
597    }
598
599    /// Build the default production gate: the production node inventory, the
600    /// conservative site policy, the genesis lattice, and no CAS manifest source
601    /// wired yet ([`NoManifests`], Stage 0). The generated-node inventory is
602    /// collected from the real `VfsNodeTable` registry.
603    pub fn production() -> Self {
604        GenesisGate::build(
605            NamespaceEnumerator::production().into_nodes(),
606            genesis_lattice(),
607            &SitePolicy::conservative(),
608            Arc::new(NoManifests),
609        )
610    }
611
612    /// Carrier (a) coverage over the real generated-node inventory: the
613    /// `(path, label)` pairs that resolved, and the paths that are findings
614    /// (unlabeled ⇒ deny). This is the per-node evidence an operator annotates
615    /// against before activation.
616    pub fn generated_coverage(&self) -> &GeneratedNodeCoverage {
617        &self.generated
618    }
619
620    /// The completeness report over the enumerated node set.
621    pub fn report(&self) -> &GenesisReport {
622        &self.report
623    }
624
625    /// The production object-label resolver (for wiring a real decider later).
626    pub fn resolver(&self) -> &CompositeObjectLabelResolver {
627        &self.resolver
628    }
629
630    /// Consume the gate and transfer its production resolver to the live PEP.
631    pub fn into_resolver(self) -> CompositeObjectLabelResolver {
632        self.resolver
633    }
634
635    /// The enumerated node set the report covers.
636    pub fn nodes(&self) -> &[String] {
637        &self.nodes
638    }
639
640    /// The genesis lattice.
641    pub fn lattice(&self) -> &Lattice {
642        &self.lattice
643    }
644
645    /// Emit the coverage report to the tracing log at boot. `info` on a complete
646    /// genesis; `warn` (with the gap lists) on an incomplete one, so an operator
647    /// activating enforcement sees exactly which nodes would deny. **Log only —
648    /// never changes enforcement state.**
649    pub fn log_report(&self) {
650        let r = &self.report;
651        if r.is_complete() {
652            tracing::info!(
653                nodes = self.nodes.len(),
654                labeled = r.labeled.len(),
655                "MAC genesis coverage COMPLETE: floor-only monitors remain active; operator may evaluate the remaining G2-G7 evidence"
656            );
657        } else {
658            tracing::warn!(
659                nodes = self.nodes.len(),
660                labeled = r.labeled.len(),
661                unlabeled = r.unlabeled.len(),
662                ill_formed = r.ill_formed.len(),
663                "MAC genesis coverage INCOMPLETE: identity-aware widening is blocked; floor-only monitors remain active"
664            );
665            for node in &r.unlabeled {
666                tracing::warn!(node = %node, "MAC genesis gap: unlabeled node (would deny under enforcement)");
667            }
668            for (node, err) in &r.ill_formed {
669                tracing::warn!(node = %node, error = %err, "MAC genesis gap: ill-formed label (fail-closed → treated as unlabeled)");
670            }
671        }
672    }
673
674    /// Render a human-readable coverage report for a CLI / status surface. This is
675    /// the activation coverage-gate evidence: a summary line plus the full
676    /// `unlabeled` / `ill_formed` gap lists and the per-node label table.
677    pub fn render_report(&self) -> String {
678        use std::fmt::Write as _;
679        let r = &self.report;
680        let mut out = String::new();
681
682        let status = if r.is_complete() {
683            "COMPLETE"
684        } else {
685            "INCOMPLETE"
686        };
687        let _ = writeln!(
688            out,
689            "MAC genesis coverage: {status} (monitors active; subject context floor-only until operator widening)"
690        );
691        let _ = writeln!(
692            out,
693            "  nodes={}  labeled={}  unlabeled={}  ill_formed={}  lattice={}",
694            self.nodes.len(),
695            r.labeled.len(),
696            r.unlabeled.len(),
697            r.ill_formed.len(),
698            self.lattice.version(),
699        );
700
701        if !r.unlabeled.is_empty() {
702            let _ = writeln!(out, "\n  UNLABELED (would deny under enforcement):");
703            for node in &r.unlabeled {
704                let _ = writeln!(out, "    - {node}");
705            }
706        }
707        if !r.ill_formed.is_empty() {
708            let _ = writeln!(out, "\n  ILL-FORMED (fail-closed → treated as unlabeled):");
709            for (node, err) in &r.ill_formed {
710                let _ = writeln!(out, "    - {node}: {err}");
711            }
712        }
713
714        let _ = writeln!(out, "\n  Labeled nodes:");
715        for node in &r.labeled {
716            // Show each labeled node with the label the site policy assigned it.
717            if let Some(label) = self.resolver.genesis.resolve(node) {
718                let _ = writeln!(out, "    {node} -> {label}");
719            } else {
720                let _ = writeln!(out, "    {node} -> <unresolved>");
721            }
722        }
723
724        out
725    }
726}
727
728// ────────────────────────────────────────────────────────────────────────────
729// 5. Carrier (a) — schema-derived labels on generated mount nodes (#699)
730// ────────────────────────────────────────────────────────────────────────────
731
732/// Per-node label coverage of a service's generated `vfs_nodes()` table
733/// (#699 carrier (a)): each generated `/srv/{service}/*` node carries its MAC
734/// label as a property of its type, derived from the `$vfsMac` schema annotation
735/// at codegen (see [`hyprstream_rpc::metadata::VfsNode::mac_label`]).
736///
737/// A node whose schema declared no `$vfsMac` decodes to `None` ⇒ **unlabeled** ⇒
738/// deny ⇒ a **finding** the operator must close (by annotating the schema) before
739/// enforcement is enabled. There is no permissive default and no catch-all: this
740/// type only partitions what the schemas declared.
741#[derive(Debug, Clone, Default, PartialEq, Eq)]
742pub struct GeneratedNodeCoverage {
743    /// `(mount-relative path, label)` for every node that resolves to a label.
744    pub labeled: Vec<(String, SecurityLabel)>,
745    /// Mount-relative paths of nodes whose schema declared no `$vfsMac`
746    /// (unlabeled ⇒ deny ⇒ finding).
747    pub unlabeled: Vec<String>,
748}
749
750impl GeneratedNodeCoverage {
751    /// Coverage is complete iff every generated node resolves to a label.
752    pub fn is_complete(&self) -> bool {
753        self.unlabeled.is_empty()
754    }
755
756    /// Classify the **real** generated-node inventory — every `vfs_nodes()`
757    /// table registered at codegen via `inventory::submit! { VfsNodeTable }` —
758    /// into labeled / unlabeled. This is the source the startup gate walks: it
759    /// covers every reachable generated object class, not whatever a hand-built
760    /// fixture happened to include.
761    ///
762    /// Deterministic: tables are sorted by service name, and the output's
763    /// `labeled`/`unlabeled` are sorted (stable reports + tests).
764    pub fn for_all_services() -> Self {
765        let mut by_service: BTreeMap<&'static str, &'static [hyprstream_rpc::metadata::VfsNode]> =
766            BTreeMap::new();
767        for t in inventory::iter::<VfsNodeTable> {
768            let (name, nodes) = (t.nodes_fn)();
769            by_service.insert(name, nodes);
770        }
771        let mut labeled = Vec::new();
772        let mut unlabeled = Vec::new();
773        for (service, nodes) in &by_service {
774            let cov = GeneratedNodeCoverage::for_service(service, nodes);
775            labeled.extend(cov.labeled);
776            unlabeled.extend(cov.unlabeled);
777        }
778        labeled.sort_by(|a, b| a.0.cmp(&b.0));
779        unlabeled.sort();
780        GeneratedNodeCoverage { labeled, unlabeled }
781    }
782
783    /// Classify a service's generated node table by carrier (a).
784    ///
785    /// `service` is the `/srv/{service}` mount name (for reporting); `nodes` is
786    /// the table the codegen macro emitted (from `vfs_nodes()`).
787    pub fn for_service(service: &str, nodes: &[hyprstream_rpc::metadata::VfsNode]) -> Self {
788        let mut labeled = Vec::new();
789        let mut unlabeled = Vec::new();
790        for n in nodes {
791            let path = format!("/srv/{}{}", service, normalize_relative(n.path));
792            match n.mac_label() {
793                Some(label) => labeled.push((path, label)),
794                None => unlabeled.push(path),
795            }
796        }
797        // Deterministic order (tests + stable reports).
798        labeled.sort_by(|a, b| a.0.cmp(&b.0));
799        unlabeled.sort();
800        GeneratedNodeCoverage { labeled, unlabeled }
801    }
802}
803
804/// Normalize a mount-relative node path into an absolute `/srv/{service}/...`
805/// segment suffix: prepend `/` if the node path is non-empty, else "" (the
806/// service root itself). `{brace}` arg-segments are kept verbatim — they are
807/// part of the node's path identity, not resolved here.
808fn normalize_relative(path: &str) -> String {
809    if path.is_empty() {
810        String::new()
811    } else if path.starts_with('/') {
812        path.to_owned()
813    } else {
814        format!("/{path}")
815    }
816}
817
818#[cfg(test)]
819#[allow(clippy::unwrap_used)]
820mod tests {
821    use super::*;
822
823    // ── Enumerator ───────────────────────────────────────────────────────────
824
825    #[test]
826    fn enumerator_production_covers_services_roots_and_mounts() {
827        let nodes = NamespaceEnumerator::production().into_nodes();
828        // Export roots present.
829        for root in EXPORT_ROOTS {
830            assert!(
831                nodes.contains(&root.to_string()),
832                "missing export root {root}"
833            );
834        }
835        // Standard non-service mounts present.
836        for m in STANDARD_NON_SERVICE_MOUNTS {
837            assert!(nodes.contains(&m.to_string()), "missing standard mount {m}");
838        }
839        // Known services from the factory inventory appear as /srv/{name}.
840        assert!(nodes.contains(&"/srv/policy".to_owned()));
841        assert!(nodes.contains(&"/srv/model".to_owned()));
842        assert!(nodes.contains(&"/srv/registry".to_owned()));
843    }
844
845    #[test]
846    fn enumerator_is_sorted_and_deduplicated() {
847        let nodes = NamespaceEnumerator::new()
848            .with_node("/srv/model")
849            .with_node("/srv/model") // dup
850            .with_node("/a")
851            .with_node("/srv/model/") // trailing slash normalizes to same
852            .into_nodes();
853        assert_eq!(nodes, vec!["/a".to_owned(), "/srv/model".to_owned()]);
854    }
855
856    #[test]
857    fn enumerator_normalizes_paths() {
858        assert_eq!(normalize_node_path("/srv//model/"), "/srv/model");
859        assert_eq!(normalize_node_path("srv/model"), "/srv/model");
860        assert_eq!(normalize_node_path("/"), "/");
861        assert_eq!(normalize_node_path(""), "/");
862    }
863
864    #[test]
865    fn enumerator_from_namespace_uses_mount_prefixes() {
866        use hyprstream_vfs::Namespace;
867        let mut ns = Namespace::new();
868        // Mount a trivial synthetic tree at a couple of prefixes.
869        let tree = Arc::new(crate::services::fs::SyntheticTree::new(
870            crate::services::fs::SyntheticNode::Dir {
871                children: Default::default(),
872            },
873        ));
874        ns.mount("/srv/custom", tree.clone()).unwrap();
875        ns.mount("/data", tree).unwrap();
876        let nodes = NamespaceEnumerator::new().with_namespace(&ns).into_nodes();
877        assert!(nodes.contains(&"/srv/custom".to_owned()));
878        assert!(nodes.contains(&"/data".to_owned()));
879    }
880
881    // ── Site policy / content ────────────────────────────────────────────────
882
883    #[test]
884    fn conservative_policy_elevates_control_plane() {
885        let p = SitePolicy::conservative();
886        assert_eq!(p.label_for("/srv/policy").level, Level::Confidential);
887        assert_eq!(p.label_for("/srv/oauth").level, Level::Confidential);
888        assert_eq!(p.label_for("/srv/ledger").level, Level::Confidential);
889        // Data services fall to the internal floor.
890        assert_eq!(p.label_for("/srv/model").level, Level::Internal);
891        assert_eq!(p.label_for("/bin").level, Level::Internal);
892        // Structural roots are public.
893        assert_eq!(p.label_for("/srv").level, Level::Public);
894        assert_eq!(p.label_for("/worktree").level, Level::Public);
895    }
896
897    #[test]
898    fn conservative_policy_is_not_the_public_everything_noop() {
899        // The genesis.rs warning: a label-everything-public genesis makes MAC a
900        // no-op. Assert the floor is genuinely restrictive (not Public).
901        let p = SitePolicy::conservative();
902        assert_eq!(p.floor().level, Level::Internal);
903    }
904
905    #[test]
906    fn materialize_assigns_every_node_no_catch_all() {
907        let nodes = [
908            "/srv/policy".to_owned(),
909            "/srv/model".to_owned(),
910            "/srv".to_owned(),
911        ];
912        let p = SitePolicy::conservative();
913        let map = p.materialize(nodes.iter().map(String::as_str));
914        // Every node resolves to a concrete label (materialized, not a default).
915        assert!(map.resolve("/srv/policy").is_some());
916        assert!(map.resolve("/srv/model").is_some());
917        assert!(map.resolve("/srv").is_some());
918        // A node NOT in the enumerated set is genuinely absent (no catch-all).
919        assert!(map.resolve("/srv/unenumerated").is_none());
920    }
921
922    #[test]
923    fn materialize_report_is_complete_over_enumerated_nodes() {
924        let nodes = NamespaceEnumerator::production().into_nodes();
925        let lattice = genesis_lattice();
926        let map = SitePolicy::conservative().materialize(nodes.iter().map(String::as_str));
927        let report = map.report(nodes.iter().map(String::as_str), &lattice);
928        assert!(
929            report.is_complete(),
930            "conservative genesis must fully cover the production node set; gaps: {:?}",
931            report.unlabeled
932        );
933    }
934
935    // ── Composite resolver ───────────────────────────────────────────────────
936
937    fn resolver_over(
938        nodes: &[&str],
939        manifests: Arc<dyn ManifestLabelSource>,
940    ) -> CompositeObjectLabelResolver {
941        let p = SitePolicy::conservative();
942        let map = p.materialize(nodes.iter().copied());
943        CompositeObjectLabelResolver::new(
944            map,
945            p.floor(),
946            manifests,
947            BTreeSet::new(),
948            Arc::new(BindLabelMap::new()),
949        )
950    }
951
952    #[test]
953    fn resolver_exact_genesis_node() {
954        let r = resolver_over(&["/srv/policy"], Arc::new(NoManifests));
955        let label = r.resolve(ObjectRef::Path(&["srv", "policy"])).unwrap();
956        assert_eq!(label.level, Level::Confidential);
957    }
958
959    #[test]
960    fn resolver_descendant_inherits_ancestor_label_d2() {
961        // A read under /srv/policy inherits the mount's (Confidential) floor —
962        // bind-time D2 descendant inheritance, never LESS restrictive.
963        let r = resolver_over(&["/srv/policy"], Arc::new(NoManifests));
964        let label = r
965            .resolve(ObjectRef::Path(&["srv", "policy", "config", "current"]))
966            .unwrap();
967        assert_eq!(label.level, Level::Confidential);
968    }
969
970    #[test]
971    fn resolver_unknown_path_denies() {
972        let r = resolver_over(&["/srv/policy"], Arc::new(NoManifests));
973        // No genesis node and no ancestor → None → deny.
974        assert!(r
975            .resolve(ObjectRef::Path(&["nowhere", "at", "all"]))
976            .is_none());
977    }
978
979    struct FixedManifests(Option<Option<SecurityLabel>>);
980    impl ManifestLabelSource for FixedManifests {
981        fn label_for(&self, _cid: &[u8]) -> Option<Option<SecurityLabel>> {
982            self.0
983        }
984    }
985
986    #[test]
987    fn resolver_cid_labeled_manifest() {
988        let labeled = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, Default::default());
989        let import_floor =
990            SecurityLabel::new(Level::Internal, Assurance::Classical, Default::default());
991        let genesis = SitePolicy::floor_only(import_floor).materialize(["/srv/policy"]);
992        let r = CompositeObjectLabelResolver::new(
993            genesis,
994            import_floor,
995            Arc::new(FixedManifests(Some(Some(labeled)))),
996            BTreeSet::new(),
997            Arc::new(BindLabelMap::new()),
998        );
999        let expected = SecurityLabel::new(Level::Secret, Assurance::Classical, Default::default());
1000        assert_eq!(
1001            r.resolve(ObjectRef::Cid(&[1, 2, 3])),
1002            Some(expected),
1003            "PqHybrid provenance imported through a Classical floor must degrade to Classical"
1004        );
1005    }
1006
1007    #[test]
1008    fn resolver_cid_unlabeled_manifest_is_denied() {
1009        let r = resolver_over(&["/srv/policy"], Arc::new(FixedManifests(Some(None))));
1010        assert!(r.resolve(ObjectRef::Cid(&[1, 2, 3])).is_none());
1011    }
1012
1013    #[test]
1014    fn resolver_cid_absent_manifest_denies() {
1015        // No manifest for this CID ⇒ unresolvable ⇒ deny.
1016        let r = resolver_over(&["/srv/policy"], Arc::new(FixedManifests(None)));
1017        assert!(r.resolve(ObjectRef::Cid(&[9, 9, 9])).is_none());
1018    }
1019
1020    #[test]
1021    fn resolver_no_manifests_denies_every_cid() {
1022        let r = resolver_over(&["/srv/policy"], Arc::new(NoManifests));
1023        assert!(r.resolve(ObjectRef::Cid(&[0])).is_none());
1024    }
1025
1026    // ── Gate ─────────────────────────────────────────────────────────────────
1027
1028    #[test]
1029    fn production_gate_mount_coverage_is_complete() {
1030        // The site-policy half: every enumerated MOUNT node (/srv/{service},
1031        // structural roots, standard mounts) is labeled by the conservative
1032        // policy. This is the pre-existing coverage; carrier (a) adds the
1033        // generated-node dimension on top.
1034        let gate = GenesisGate::production();
1035        let mount_nodes = NamespaceEnumerator::production().into_nodes();
1036        for node in &mount_nodes {
1037            assert!(
1038                gate.report().labeled.contains(node),
1039                "mount node {node} must be labeled by the site-policy genesis"
1040            );
1041        }
1042    }
1043
1044    #[test]
1045    fn production_gate_generated_coverage_is_collected() {
1046        // Carrier (a) wiring (#1228): the gate folds in the REAL generated-node
1047        // inventory — not a hand-built fixture. The inventory is non-empty (the
1048        // daemon's services project generated nodes), and the coverage is
1049        // surfaced on the gate for operator visibility.
1050        let gate = GenesisGate::production();
1051        let cov = gate.generated_coverage();
1052        let total = cov.labeled.len() + cov.unlabeled.len();
1053        assert!(
1054            total > 0,
1055            "the real generated-node inventory must be collected into the gate"
1056        );
1057    }
1058
1059    #[test]
1060    fn production_gate_is_incomplete_until_all_generated_nodes_annotated() {
1061        // The startup activation gate (#1228): a generated node whose schema
1062        // declared no `$vfsMac` is a finding, so the production gate is
1063        // INCOMPLETE until every reachable generated object class is annotated.
1064        // This is the honest Stage 0 state — enforcement MUST NOT be enabled
1065        // while any generated node is unlabeled. (Schemas are not yet fully
1066        // `$vfsMac`-annotated, so the unannotated majority are findings here.)
1067        let gate = GenesisGate::production();
1068        assert!(
1069            !gate.generated_coverage().is_complete(),
1070            "the production gate must surface the unannotated generated nodes as \
1071             findings — a complete gate before schemas are annotated would mean \
1072             the inventory is not really gating"
1073        );
1074        // And the report itself is incomplete (the generated unlabeled paths are
1075        // in the report's unlabeled list, not silently dropped).
1076        assert!(
1077            !gate.report().is_complete(),
1078            "the report must reflect the generated-node findings"
1079        );
1080    }
1081
1082    #[test]
1083    fn gate_render_report_contains_summary_and_labels() {
1084        // The rendered report carries the status line and each labeled node's
1085        // assignment, whether the gate is COMPLETE or INCOMPLETE.
1086        let gate = GenesisGate::production();
1087        let rendered = gate.render_report();
1088        assert!(
1089            rendered.contains("MAC genesis coverage:"),
1090            "rendered report has a status line: {rendered}"
1091        );
1092        assert!(
1093            rendered.contains("/srv/policy -> confidential"),
1094            "labeled mount nodes appear in the report: {rendered}"
1095        );
1096    }
1097
1098    #[test]
1099    fn gate_with_gap_reports_incomplete() {
1100        // A node set that the floor-only policy still covers is complete; force an
1101        // incomplete report by using a floor-only policy but reporting over an
1102        // extra node that was never materialized.
1103        let nodes = ["/srv/model".to_owned()];
1104        let lattice = genesis_lattice();
1105        let policy = SitePolicy::conservative();
1106        let genesis = policy.materialize(nodes.iter().map(String::as_str));
1107        // Report over a superset that includes an unmaterialized node.
1108        let all = ["/srv/model", "/srv/ghost"];
1109        let report = genesis.report(all, &lattice);
1110        assert!(!report.is_complete());
1111        assert_eq!(report.unlabeled, vec!["/srv/ghost".to_owned()]);
1112    }
1113
1114    #[test]
1115    fn gate_resolver_matches_report_coverage() {
1116        // Every labeled node in the report must resolve to the label materialized
1117        // into genesis: generated nodes use their schema carrier, while mount
1118        // nodes use the site-policy label.
1119        let gate = GenesisGate::production();
1120        let policy = SitePolicy::conservative();
1121        for node in &gate.report().labeled {
1122            let components: Vec<&str> = node
1123                .split('/')
1124                .filter(|component| !component.is_empty())
1125                .collect();
1126            let carrier_label = gate
1127                .generated_coverage()
1128                .labeled
1129                .iter()
1130                .find_map(|(path, label)| (path == node).then_some(*label));
1131            let expected = carrier_label.unwrap_or_else(|| policy.label_for(node));
1132            assert_eq!(
1133                gate.resolver().resolve(ObjectRef::Path(&components)),
1134                Some(expected),
1135                "labeled node {node} must resolve to its materialized genesis label"
1136            );
1137            if carrier_label.is_none() {
1138                assert_eq!(expected.assurance, Assurance::Unverified);
1139            }
1140        }
1141    }
1142
1143    // ── Carrier wiring (#1228): the carriers reach the resolver, end-to-end ──
1144
1145    #[test]
1146    fn resolver_resolves_real_annotated_generated_node() {
1147        // End-to-end over the REAL generated-node inventory (not a fixture):
1148        // the production gate folds in every registered `VfsNodeTable`, so a
1149        // `$vfsMac`-annotated real schema node resolves through the production
1150        // resolver to its schema-declared label. `registry`'s `healthCheck` is
1151        // annotated `internal:pq-hybrid` and projects to `/srv/registry/health`.
1152        let gate = GenesisGate::production();
1153        let cov = gate.generated_coverage();
1154        let health_path = "/srv/registry/health";
1155        assert!(
1156            cov.labeled.iter().any(|(p, _)| p == health_path),
1157            "the annotated registry health node must be in the generated coverage: {:?}",
1158            cov.labeled
1159        );
1160        let label = gate
1161            .resolver()
1162            .resolve(ObjectRef::Path(&["srv", "registry", "health"]))
1163            .unwrap(); // annotated node must resolve to its label
1164        assert_eq!(label.level, Level::Internal);
1165        assert_eq!(label.assurance, Assurance::PqHybrid);
1166    }
1167
1168    #[test]
1169    fn resolver_denies_real_unannotated_generated_node() {
1170        // End-to-end over the REAL inventory: an unannotated generated node (one
1171        // the schema left without a `$vfsMac`) denies — it does NOT inherit its
1172        // service mount's label. `registry`'s `getByName` projects to
1173        // `/srv/registry/{name}` and carries no `$vfsMac`, so it is a finding
1174        // and resolves to None ⇒ deny (#1228: the silent hole is closed).
1175        let gate = GenesisGate::production();
1176        let cov = gate.generated_coverage();
1177        let name_path = "/srv/registry/{name}";
1178        assert!(
1179            cov.unlabeled.iter().any(|p| p == name_path),
1180            "the unannotated registry {{name}} node must be a finding: {:?}",
1181            cov.unlabeled
1182        );
1183        assert!(
1184            gate.resolver()
1185                .resolve(ObjectRef::Path(&["srv", "registry", "{name}"]))
1186                .is_none(),
1187            "an unannotated real node must deny, not inherit the mount label"
1188        );
1189    }
1190
1191    #[test]
1192    fn resolver_bind_time_floor_clamps_descendant_carrier_c() {
1193        // Carrier (c) reaches the resolver: a synthetic mount bound with a
1194        // floor clamps every descendant to at least that floor (D2 restrict-
1195        // only). A descendant with its own label is joined; one without inherits
1196        // the floor. A path under no bound and no genesis label denies.
1197        let p = SitePolicy::conservative();
1198        let map = p.materialize(["/srv/model"]);
1199        let secret_floor =
1200            SecurityLabel::new(Level::Secret, Assurance::PqHybrid, Default::default());
1201        let mut binds = BindLabelMap::new();
1202        // A Secret-cleared subject binds a synthetic mount at /synth.
1203        binds.bind("/synth", secret_floor, secret_floor);
1204        let resolver = CompositeObjectLabelResolver::new(
1205            map,
1206            p.floor(),
1207            Arc::new(NoManifests),
1208            std::collections::BTreeSet::new(),
1209            Arc::new(binds),
1210        );
1211        // A descendant with no label of its own inherits the bind floor.
1212        let under = resolver
1213            .resolve(ObjectRef::Path(&["synth", "child"]))
1214            .unwrap(); // descendant of a bound mount inherits the floor
1215        assert_eq!(under.level, Level::Secret);
1216        // A path under no bound prefix and no genesis assignment denies.
1217        assert!(resolver
1218            .resolve(ObjectRef::Path(&["nowhere", "at", "all"]))
1219            .is_none());
1220    }
1221
1222    #[test]
1223    fn resolver_bind_floor_joins_genesis_label_restrict_only() {
1224        // Carrier (c) × genesis: a descendant under a Secret bind floor whose
1225        // genesis label is Internal resolves to Secret (the join — floor wins,
1226        // D2 restrict-only, never less).
1227        let p = SitePolicy::conservative();
1228        let internal = SecurityLabel::new(Level::Internal, Assurance::PqHybrid, Default::default());
1229        let secret = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, Default::default());
1230        let map = p.materialize(["/srv"]).assign("/synth/low", internal);
1231        let mut binds = BindLabelMap::new();
1232        binds.bind("/synth", secret, secret);
1233        let resolver = CompositeObjectLabelResolver::new(
1234            map,
1235            p.floor(),
1236            Arc::new(NoManifests),
1237            std::collections::BTreeSet::new(),
1238            Arc::new(binds),
1239        );
1240        let label = resolver
1241            .resolve(ObjectRef::Path(&["synth", "low"]))
1242            .unwrap(); // bind floor joined with genesis label resolves
1243        assert_eq!(
1244            label.level,
1245            Level::Secret,
1246            "join(Secret floor, Internal label) = Secret (restrict-only)"
1247        );
1248    }
1249
1250    // ── Carrier (a): generated-node label coverage (#699) ─────────────────────
1251
1252    use hyprstream_rpc::metadata::{VfsNode, VfsNodeKind};
1253
1254    fn vnode(path: &'static str, mac: &'static str) -> VfsNode {
1255        VfsNode {
1256            method: "m",
1257            path,
1258            kind: VfsNodeKind::File,
1259            scope: "query",
1260            bulk: false,
1261            mac,
1262        }
1263    }
1264
1265    #[test]
1266    fn every_annotated_generated_node_resolves_to_a_label() {
1267        // Carrier (a): a fully-`$vfsMac`-annotated service's generated table has
1268        // NO unlabeled nodes — every node resolves to a label. Every annotation
1269        // carries the mandatory `pq-hybrid` assurance.
1270        let nodes = [
1271            vnode("status", "internal:pq-hybrid"),
1272            vnode("{name}", "confidential:pq-hybrid"),
1273            vnode("ctl", "secret:pq-hybrid:0"),
1274        ];
1275        let cov = GeneratedNodeCoverage::for_service("model", &nodes);
1276        assert!(cov.is_complete(), "unlabeled findings: {:?}", cov.unlabeled);
1277        assert_eq!(cov.labeled.len(), 3);
1278        assert_eq!(cov.unlabeled, Vec::<String>::new());
1279        // Paths are /srv/{service}/{node}.
1280        let paths: Vec<&str> = cov.labeled.iter().map(|(p, _)| p.as_str()).collect();
1281        assert!(paths.contains(&"/srv/model/status"));
1282        assert!(paths.contains(&"/srv/model/{name}"));
1283        assert!(paths.contains(&"/srv/model/ctl"));
1284    }
1285
1286    #[test]
1287    fn unannotated_generated_node_is_a_finding_not_a_default() {
1288        // A node whose schema declared no `$vfsMac` is unlabeled ⇒ deny ⇒ a
1289        // finding. It is NOT defaulted to a permissive label.
1290        let nodes = [vnode("status", "internal:pq-hybrid"), vnode("secret", "")];
1291        let cov = GeneratedNodeCoverage::for_service("model", &nodes);
1292        assert!(!cov.is_complete());
1293        assert_eq!(cov.unlabeled, vec!["/srv/model/secret"]);
1294        assert_eq!(cov.labeled.len(), 1);
1295    }
1296
1297    #[test]
1298    fn non_pq_hybrid_assurance_is_a_finding() {
1299        // #556/#1228: the internal VFS carrier requires `pq-hybrid`. A
1300        // level-only annotation, `unverified`, or `classical` all decode to
1301        // None ⇒ unlabeled ⇒ finding (the non-PQ path must not silently land).
1302        let nodes = [
1303            vnode("a", "internal"), // level-only — assurance mandatory
1304            vnode("b", "internal:unverified"),
1305            vnode("c", "internal:classical"),
1306            vnode("ok", "internal:pq-hybrid"), // the one accepted form
1307        ];
1308        let cov = GeneratedNodeCoverage::for_service("model", &nodes);
1309        assert!(!cov.is_complete());
1310        assert!(cov.unlabeled.contains(&"/srv/model/a".to_owned()));
1311        assert!(cov.unlabeled.contains(&"/srv/model/b".to_owned()));
1312        assert!(cov.unlabeled.contains(&"/srv/model/c".to_owned()));
1313        assert_eq!(cov.labeled.len(), 1);
1314    }
1315
1316    #[test]
1317    fn malformed_vfs_mac_is_a_finding() {
1318        // A garbled `$vfsMac` decodes to None ⇒ finding (fail-closed).
1319        let nodes = [
1320            vnode("status", "internal:pq-hybrid"),
1321            vnode("x", "not-a-level"),
1322        ];
1323        let cov = GeneratedNodeCoverage::for_service("model", &nodes);
1324        assert!(!cov.is_complete());
1325        assert!(cov.unlabeled.contains(&"/srv/model/x".to_owned()));
1326    }
1327}