Skip to main content

hyprstream_rpc_build/schema/
dispatch_label.rs

1//! Strict `$dispatchMac`/`$dispatchPublic` grammar and the `InitialLabelMap`
2//! (v16 §6, WS-D / #1505).
3//!
4//! This module is the ONE parser for the dispatch-label grammar, shared by the
5//! proc-macro codegen (`hyprstream-rpc-derive`, via the cgr re-export) and any
6//! build-time validation in this crate. A second implementation of this
7//! grammar is a refactor-plan §0.3 violation.
8//!
9//! Grammar (v16 §6):
10//!
11//! ```text
12//! <level>:<assurance>[:<compartment>[,<compartment>...]]
13//! ```
14//!
15//! Every failure mode below is a **build error** at code generation — an
16//! annotation failure can never produce an unlabeled runtime row:
17//!
18//! - unknown level or assurance;
19//! - empty components (`internal:`, `:pq-hybrid`, `secret:pq-hybrid:`);
20//! - duplicate compartments;
21//! - compartments not listed in canonical (bit-ascending) order;
22//! - compartment names not present in the checked-in `InitialLabelMap`;
23//! - trailing/leading whitespace anywhere (the annotation is not trimmed);
24//! - system low (`public:unverified`, no compartments) written through
25//!   `$dispatchMac` — that label is exactly what `$dispatchPublic` expands to,
26//!   so spelling it through the MAC annotation is the one form that would let
27//!   a "labeled" row be indistinguishable from a public row; and
28//! - `$dispatchPublic` with an empty, whitespace-only, or
29//!   surrounding-whitespace-padded reason (the reason is never trimmed — the
30//!   recorded inventory text is the exact declared annotation text).
31
32use std::collections::HashMap;
33
34use serde::Deserialize;
35
36/// The checked-in compartment vocabulary: name → stable bit.
37///
38/// Versioned, append-only, tombstoned (see `schema/initial-label-map.json`).
39/// Parsed once per process (build/codegen), never on a hot path.
40#[derive(Debug, Clone, Deserialize)]
41struct InitialLabelMapFile {
42    version: u32,
43    #[serde(default)]
44    compartments: Vec<InitialLabelMapEntry>,
45    #[serde(default)]
46    retired: Vec<InitialLabelMapEntry>,
47}
48
49#[derive(Debug, Clone, Deserialize)]
50struct InitialLabelMapEntry {
51    name: String,
52    bit: u32,
53}
54
55/// The parsed [`crate::schema::dispatch_label`] vocabulary.
56#[derive(Debug, Clone)]
57pub struct InitialLabelMap {
58    version: u32,
59    /// Live name → bit. Built with duplicate detection at load.
60    bits: HashMap<String, u32>,
61    /// Tombstoned names — forever unusable, present for auditability.
62    retired: Vec<InitialLabelMapEntry>,
63}
64
65/// The map file is malformed (not valid JSON against the schema above, a
66/// duplicate live or tombstoned name/bit, live/tombstone overlap, or a bit
67/// outside the `SecurityLabel` compartment width).
68#[derive(Debug)]
69pub struct InitialLabelMapError(pub String);
70
71impl std::fmt::Display for InitialLabelMapError {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "InitialLabelMap: {}", self.0)
74    }
75}
76
77/// Maximum compartment bits — mirrors
78/// `hyprstream_rpc::auth::mac::label::MAX_COMPARTMENTS` (the fixed `u64`
79/// bitset width of `SecurityLabel`). rpc-build cannot depend on the runtime
80/// crate (the runtime crate depends on this one's consumers), so the constant
81/// is restated here and cross-checked by a drift test in `hyprstream-rpc`.
82pub const MAX_COMPARTMENT_BITS: u32 = 64;
83
84/// The label axes the grammar accepts. These mirror the runtime
85/// `Level`/`Assurance` enums; the mapping to runtime values lives in the
86/// generated code, keyed on these strings.
87pub const LEVELS: &[&str] = &["public", "internal", "confidential", "secret"];
88pub const ASSURANCES: &[&str] = &["unverified", "classical", "pq-hybrid"];
89
90/// The system-low label text — the exact expansion of `$dispatchPublic`.
91pub const SYSTEM_LOW: &str = "public:unverified";
92
93/// The read-class authorization actions (S3 `ScopeAction` Block A). A leaf in
94/// this class may still declare a bounded application effect; every other
95/// action requires an explicit mutation policy. This is the CODEGEN-TIME copy;
96/// the runtime
97/// validator keeps its own copy in `hyprstream_rpc::proof::policy`, and the
98/// full-inventory validation test is the drift gate between them: a row
99/// generated under one list fails the other's validation.
100pub const READ_CLASS_ACTIONS: &[&str] = &["query", "subscribe"];
101
102/// The checked-in map, embedded at compile time so codegen (proc-macro and
103/// build binary alike) reads exactly the reviewed artifact.
104const INITIAL_LABEL_MAP_JSON: &str = include_str!("../../schema/initial-label-map.json");
105
106/// A parsed `$dispatchMac` label: the axis values plus the resolved,
107/// canonical-ordered compartment bits.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct DispatchLabel {
110    pub level: &'static str,
111    pub assurance: &'static str,
112    /// Compartment bits in ascending order (canonical form).
113    pub compartment_bits: Vec<u32>,
114}
115
116impl DispatchLabel {
117    /// Render back to the canonical annotation text (round-trip identity).
118    pub fn to_canonical_text(&self, map: &InitialLabelMap) -> Option<String> {
119        let mut names: Vec<(u32, &str)> = Vec::with_capacity(self.compartment_bits.len());
120        for bit in &self.compartment_bits {
121            names.push((*bit, map.name_of(*bit)?));
122        }
123        names.sort_by_key(|(b, _)| *b);
124        let mut text = format!("{}:{}", self.level, self.assurance);
125        if !names.is_empty() {
126            text.push(':');
127            text.push_str(&names.iter().map(|(_, n)| *n).collect::<Vec<_>>().join(","));
128        }
129        Some(text)
130    }
131
132    /// Whether this is exactly the system-low label.
133    pub fn is_system_low(&self) -> bool {
134        self.level == "public" && self.assurance == "unverified" && self.compartment_bits.is_empty()
135    }
136}
137
138impl InitialLabelMap {
139    /// Load the checked-in map (embedded at compile time).
140    pub fn load() -> Result<Self, InitialLabelMapError> {
141        Self::parse_text(INITIAL_LABEL_MAP_JSON)
142    }
143
144    /// Parse map text (unit-testable seam; production always uses
145    /// [`Self::load`]).
146    pub fn parse_text(text: &str) -> Result<Self, InitialLabelMapError> {
147        let file: InitialLabelMapFile = serde_json::from_str(text)
148            .map_err(|e| InitialLabelMapError(format!("invalid map JSON: {e}")))?;
149        let mut bits = HashMap::new();
150        let mut seen_bits = std::collections::HashSet::new();
151        let mut seen_names = std::collections::HashSet::new();
152        for entry in &file.compartments {
153            if entry.name.trim().is_empty() || entry.name != entry.name.trim() {
154                return Err(InitialLabelMapError(format!(
155                    "compartment name {:?} is empty or padded",
156                    entry.name
157                )));
158            }
159            if entry.bit >= MAX_COMPARTMENT_BITS {
160                return Err(InitialLabelMapError(format!(
161                    "compartment {:?} bit {} exceeds the {}-bit width",
162                    entry.name, entry.bit, MAX_COMPARTMENT_BITS
163                )));
164            }
165            if bits.contains_key(&entry.name) {
166                return Err(InitialLabelMapError(format!(
167                    "compartment {:?} assigned twice",
168                    entry.name
169                )));
170            }
171            if !seen_bits.insert(entry.bit) {
172                return Err(InitialLabelMapError(format!(
173                    "bit {} assigned twice",
174                    entry.bit
175                )));
176            }
177            seen_names.insert(entry.name.clone());
178            bits.insert(entry.name.clone(), entry.bit);
179        }
180        for entry in &file.retired {
181            if entry.name.trim().is_empty() || entry.name != entry.name.trim() {
182                return Err(InitialLabelMapError(format!(
183                    "tombstoned compartment name {:?} is empty or padded",
184                    entry.name
185                )));
186            }
187            if entry.bit >= MAX_COMPARTMENT_BITS {
188                return Err(InitialLabelMapError(format!(
189                    "tombstoned compartment {:?} bit {} exceeds the {}-bit width",
190                    entry.name, entry.bit, MAX_COMPARTMENT_BITS
191                )));
192            }
193            if !seen_names.insert(entry.name.clone()) {
194                return Err(InitialLabelMapError(format!(
195                    "tombstoned compartment {:?} is already assigned or retired",
196                    entry.name
197                )));
198            }
199            if !seen_bits.insert(entry.bit) {
200                return Err(InitialLabelMapError(format!(
201                    "tombstoned compartment bit {} is already assigned or retired",
202                    entry.bit
203                )));
204            }
205        }
206        Ok(Self {
207            version: file.version,
208            bits,
209            retired: file.retired,
210        })
211    }
212
213    /// The lattice/policy version this vocabulary belongs to.
214    pub fn version(&self) -> u32 {
215        self.version
216    }
217
218    /// Live compartment count.
219    pub fn len(&self) -> usize {
220        self.bits.len()
221    }
222
223    /// Whether the live vocabulary is empty.
224    pub fn is_empty(&self) -> bool {
225        self.bits.is_empty()
226    }
227
228    /// The stable bit a live compartment name is assigned.
229    pub fn bit_of(&self, name: &str) -> Option<u32> {
230        self.bits.get(name).copied()
231    }
232
233    /// The live name a bit resolves to (canonical rendering).
234    pub fn name_of(&self, bit: u32) -> Option<&str> {
235        self.bits
236            .iter()
237            .find(|(_, b)| **b == bit)
238            .map(|(n, _)| n.as_str())
239    }
240
241    /// Tombstoned names — listed for audit output only, never assignable.
242    pub fn retired_names(&self) -> Vec<&str> {
243        self.retired.iter().map(|e| e.name.as_str()).collect()
244    }
245}
246
247/// Parse one `$dispatchMac` annotation value against the map.
248///
249/// Every rule violation returns `Err` with the review-facing reason; the caller
250/// turns that into a build error (`compile_error!` / build-script failure), so
251/// no unparseable annotation can ever reach a runtime row.
252pub fn parse_dispatch_mac(text: &str, map: &InitialLabelMap) -> Result<DispatchLabel, String> {
253    let label = parse_label_text(text, map)?;
254    if label.is_system_low() {
255        return Err(format!(
256            "'{text}' is system low — the label `$dispatchPublic` expands to. \
257             System low through `$dispatchMac` is a build error; declare \
258             `$dispatchPublic(\"<reason>\")` instead or choose a real label."
259        ));
260    }
261    Ok(label)
262}
263
264/// Parse the bare label grammar (also the `$dispatchPublic` expansion target).
265fn parse_label_text(text: &str, map: &InitialLabelMap) -> Result<DispatchLabel, String> {
266    if text.trim() != text || text.is_empty() {
267        return Err(format!(
268            "label '{text}' is empty or padded — the annotation is not trimmed"
269        ));
270    }
271    let parts: Vec<&str> = text.split(':').collect();
272    if parts.len() < 2 || parts.len() > 3 {
273        return Err(format!(
274            "label '{text}' must be '<level>:<assurance>[:<compartments>]' \
275             ({} colon-separated components, found {})",
276            if parts.len() < 2 {
277                "too few"
278            } else {
279                "too many"
280            },
281            parts.len()
282        ));
283    }
284    let level = parts[0];
285    let assurance = parts[1];
286    if !LEVELS.contains(&level) {
287        return Err(format!(
288            "label '{text}': unknown level '{level}' (one of {})",
289            LEVELS.join("|")
290        ));
291    }
292    if !ASSURANCES.contains(&assurance) {
293        return Err(format!(
294            "label '{text}': unknown assurance '{assurance}' (one of {})",
295            ASSURANCES.join("|")
296        ));
297    }
298    let mut compartment_bits = Vec::new();
299    if parts.len() == 3 {
300        if parts[2].is_empty() {
301            return Err(format!(
302                "label '{text}': empty compartment component — omit the third \
303                 component instead of writing an empty one"
304            ));
305        }
306        for name in parts[2].split(',') {
307            if name.trim() != name || name.is_empty() {
308                return Err(format!(
309                    "label '{text}': compartment component '{name}' is empty or padded"
310                ));
311            }
312            let bit = map.bit_of(name).ok_or_else(|| {
313                format!(
314                    "label '{text}': compartment '{name}' is not in the checked-in \
315                     InitialLabelMap (v{}); adding a compartment is an append-only, \
316                     reviewed edit to the map",
317                    map.version()
318                )
319            })?;
320            if let Some(prev) = compartment_bits.last() {
321                if *prev == bit {
322                    return Err(format!(
323                        "label '{text}': compartment '{name}' appears twice"
324                    ));
325                }
326                if *prev > bit {
327                    return Err(format!(
328                        "label '{text}': compartments must be listed in canonical \
329                         (bit-ascending) order — '{name}' (bit {bit}) follows bit {prev}"
330                    ));
331                }
332            }
333            compartment_bits.push(bit);
334        }
335    }
336    // Both axes were membership-checked above; the finds cannot miss, and a
337    // miss is a grammar denial rather than a panic.
338    let level_ref = LEVELS
339        .iter()
340        .find(|l| **l == level)
341        .ok_or_else(|| format!("label '{text}': unknown level '{level}'"))?;
342    let assurance_ref = ASSURANCES
343        .iter()
344        .find(|a| **a == assurance)
345        .ok_or_else(|| format!("label '{text}': unknown assurance '{assurance}'"))?;
346    Ok(DispatchLabel {
347        level: level_ref,
348        assurance: assurance_ref,
349        compartment_bits,
350    })
351}
352
353/// Validate one `$dispatchPublic` reason string: nonempty and already trimmed.
354///
355/// The strict contract (annotations.capnp; v16 §6) is a canonical, reviewable
356/// reason. Surrounding whitespace is a schema error, never silently rewritten:
357/// the reason recorded in the generated inventory is the exact declared text.
358pub fn parse_dispatch_public_reason(text: &str) -> Result<&str, String> {
359    if text.trim().is_empty() {
360        return Err(format!(
361            "$dispatchPublic reason {text:?} is empty or whitespace-only — a \
362             public leaf carries a mandatory, reviewable reason"
363        ));
364    }
365    if text.trim() != text {
366        return Err(format!(
367            "$dispatchPublic reason {text:?} is padded — declare the reason \
368             already trimmed; the inventory records the exact annotation text"
369        ));
370    }
371    Ok(text)
372}
373
374/// The label `$dispatchPublic` expands to — always exactly system low.
375pub fn public_expansion() -> DispatchLabel {
376    DispatchLabel {
377        level: "public",
378        assurance: "unverified",
379        compartment_bits: Vec::new(),
380    }
381}
382
383#[cfg(test)]
384#[allow(clippy::unwrap_used, clippy::expect_used)]
385mod tests {
386    use super::*;
387
388    fn map_with(compartments: &[(&str, u32)]) -> InitialLabelMap {
389        let entries: Vec<String> = compartments
390            .iter()
391            .map(|(n, b)| format!(r#"{{"name":"{n}","bit":{b}}}"#))
392            .collect();
393        let text = format!(
394            r#"{{"version":3,"compartments":[{}],"retired":[]}}"#,
395            entries.join(",")
396        );
397        InitialLabelMap::parse_text(&text).unwrap()
398    }
399
400    #[test]
401    fn the_checked_in_map_loads() {
402        let map = InitialLabelMap::load().unwrap();
403        assert_eq!(map.version(), 1);
404        assert!(map.is_empty(), "production lattice v1 has no compartments");
405    }
406
407    #[test]
408    fn a_two_axis_label_parses() {
409        let map = InitialLabelMap::load().unwrap();
410        let label = parse_dispatch_mac("internal:pq-hybrid", &map).unwrap();
411        assert_eq!(label.level, "internal");
412        assert_eq!(label.assurance, "pq-hybrid");
413        assert!(label.compartment_bits.is_empty());
414        assert!(!label.is_system_low());
415    }
416
417    #[test]
418    fn every_level_assurance_pair_parses_except_system_low() {
419        let map = InitialLabelMap::load().unwrap();
420        for level in LEVELS {
421            for assurance in ASSURANCES {
422                let text = format!("{level}:{assurance}");
423                let parsed = parse_dispatch_mac(&text, &map);
424                if text == SYSTEM_LOW {
425                    assert!(parsed.is_err(), "system low via $dispatchMac denies");
426                } else {
427                    assert!(parsed.is_ok(), "{text} must parse");
428                }
429            }
430        }
431    }
432
433    #[test]
434    fn compartments_resolve_to_bits_in_canonical_order() {
435        let map = map_with(&[("core", 2), ("pii", 0), ("finance", 1)]);
436        let label = parse_dispatch_mac("secret:pq-hybrid:pii,finance,core", &map).unwrap();
437        assert_eq!(label.compartment_bits, vec![0, 1, 2]);
438        // Round-trip identity through the canonical renderer.
439        assert_eq!(
440            label.to_canonical_text(&map).unwrap(),
441            "secret:pq-hybrid:pii,finance,core"
442        );
443    }
444
445    #[test]
446    fn noncanonical_ordering_duplicates_and_unknowns_deny() {
447        let map = map_with(&[("pii", 0), ("finance", 1)]);
448        // finance (bit 1) before pii (bit 0).
449        assert!(parse_dispatch_mac("internal:pq-hybrid:finance,pii", &map).is_err());
450        // duplicate.
451        assert!(parse_dispatch_mac("internal:pq-hybrid:pii,pii", &map).is_err());
452        // unknown name.
453        assert!(parse_dispatch_mac("internal:pq-hybrid:pii,ghost", &map).is_err());
454        // tombstoned-forever names are simply unknown.
455        let retired = InitialLabelMap::parse_text(
456            r#"{"version":2,"compartments":[{"name":"pii","bit":0}],"retired":[{"name":"old","bit":7}]}"#,
457        )
458        .unwrap();
459        assert!(parse_dispatch_mac("internal:pq-hybrid:old", &retired).is_err());
460        assert_eq!(retired.retired_names(), vec!["old"]);
461    }
462
463    #[test]
464    fn malformed_grammar_denies() {
465        let map = map_with(&[("pii", 0)]);
466        for bad in [
467            "",
468            "internal",
469            "internal:",
470            ":pq-hybrid",
471            "internal:pq-hybrid:",
472            "internal:pq-hybrid:pii,",
473            ",pii",
474            "internal pq-hybrid",
475            "INTERNAL:pq-hybrid",
476            "internal:PQ-HYBRID",
477            "internal:pq-hybrid:pii :x",
478            "a:b:c:d",
479            " internal:pq-hybrid",
480            "internal:pq-hybrid ",
481        ] {
482            assert!(
483                parse_dispatch_mac(bad, &map).is_err(),
484                "{bad:?} must be a build error"
485            );
486        }
487    }
488
489    #[test]
490    fn system_low_through_dispatch_mac_denies() {
491        let map = InitialLabelMap::load().unwrap();
492        assert!(parse_dispatch_mac("public:unverified", &map).is_err());
493        // A compartmented public label is NOT system low and is fine.
494        let map = map_with(&[("pii", 0)]);
495        assert!(parse_dispatch_mac("public:unverified:pii", &map).is_ok());
496    }
497
498    #[test]
499    fn public_reasons_must_be_trimmed_nonempty() {
500        // A valid trimmed reason passes through EXACTLY as declared.
501        assert_eq!(
502            parse_dispatch_public_reason("circularity").unwrap(),
503            "circularity"
504        );
505        assert_eq!(
506            parse_dispatch_public_reason("no padding on either side").unwrap(),
507            "no padding on either side"
508        );
509        // Surrounding whitespace of any shape is a schema error, not a trim.
510        for padded in [
511            "  padded  ",
512            " leading",
513            "trailing ",
514            "\ttabbed\t",
515            "\nnew\n",
516        ] {
517            let err = parse_dispatch_public_reason(padded).unwrap_err();
518            assert!(err.contains("padded"), "{padded:?}: {err}");
519        }
520        for bad in ["", "   ", "\t"] {
521            let err = parse_dispatch_public_reason(bad).unwrap_err();
522            assert!(err.contains("empty or whitespace-only"), "{bad:?}: {err}");
523        }
524    }
525
526    #[test]
527    fn the_public_expansion_is_exactly_system_low() {
528        let expansion = public_expansion();
529        assert!(expansion.is_system_low());
530        assert_eq!(expansion.level, "public");
531        assert_eq!(expansion.assurance, "unverified");
532        assert!(expansion.compartment_bits.is_empty());
533    }
534
535    #[test]
536    fn a_malformed_map_denies_at_load() {
537        // duplicate name
538        assert!(InitialLabelMap::parse_text(
539            r#"{"version":1,"compartments":[{"name":"a","bit":0},{"name":"a","bit":1}]}"#
540        )
541        .is_err());
542        // duplicate bit
543        assert!(InitialLabelMap::parse_text(
544            r#"{"version":1,"compartments":[{"name":"a","bit":0},{"name":"b","bit":0}]}"#
545        )
546        .is_err());
547        // bit beyond the SecurityLabel width
548        assert!(InitialLabelMap::parse_text(
549            r#"{"version":1,"compartments":[{"name":"a","bit":9999}]}"#
550        )
551        .is_err());
552        // live + tombstoned at once
553        assert!(InitialLabelMap::parse_text(
554            r#"{"version":1,"compartments":[{"name":"a","bit":0}],"retired":[{"name":"a","bit":3}]}"#
555        )
556        .is_err());
557        // A renamed live compartment cannot reuse a retired bit.
558        assert!(InitialLabelMap::parse_text(
559            r#"{"version":1,"compartments":[{"name":"renamed","bit":3}],"retired":[{"name":"old","bit":3}]}"#
560        )
561        .is_err());
562        // Tombstones validate their own canonical name and bit constraints.
563        for malformed_retired in [
564            r#"{"version":1,"retired":[{"name":" ","bit":3}]}"#,
565            r#"{"version":1,"retired":[{"name":"old","bit":64}]}"#,
566            r#"{"version":1,"retired":[{"name":"old","bit":3},{"name":"old","bit":4}]}"#,
567            r#"{"version":1,"retired":[{"name":"old","bit":3},{"name":"older","bit":3}]}"#,
568        ] {
569            assert!(
570                InitialLabelMap::parse_text(malformed_retired).is_err(),
571                "malformed tombstone must deny: {malformed_retired}"
572            );
573        }
574        // not JSON at all
575        assert!(InitialLabelMap::parse_text("not json").is_err());
576    }
577
578    #[test]
579    fn disjoint_live_and_tombstoned_vocabulary_remains_canonical() {
580        let map = InitialLabelMap::parse_text(
581            r#"{"version":2,"compartments":[{"name":"pii","bit":0},{"name":"finance","bit":2}],"retired":[{"name":"former-core","bit":1},{"name":"former-legal","bit":3}]}"#,
582        )
583        .unwrap();
584        let label = parse_dispatch_mac("secret:pq-hybrid:pii,finance", &map).unwrap();
585        assert_eq!(label.compartment_bits, vec![0, 2]);
586        assert_eq!(
587            label.to_canonical_text(&map).as_deref(),
588            Some("secret:pq-hybrid:pii,finance")
589        );
590        assert_eq!(map.retired_names(), vec!["former-core", "former-legal"]);
591    }
592}