Skip to main content

hyprstream_core/mac/
enrollment_reconcile.rs

1//! Enrollment reconciler (#698 Phase 2, code slice 2) — the single-writer
2//! protected-controller action that folds the durable enrollment-intent
3//! journal into the NEXT unsigned boot-policy generation for the offline
4//! `trust sign-mac-boot-policy` ceremony.
5//!
6//! Design: `docs/mac-architecture.md` "Enrollment lifecycle (#698 Phase 2)".
7//!
8//! Inputs:
9//! - the intent journal ([`crate::mac::enrollment_journal`]), and
10//! - the CURRENT boot policy as pinned by OS-owned config: the signed
11//!   artifact at `policy_path` plus the operator-supplied
12//!   `(expected_generation, expected_policy_hash)` pin
13//!   ([`crate::config::MacBootPolicyConfig`]). The pin is the trust anchor:
14//!   the reconciler recomputes the artifact's policy hash and refuses on any
15//!   mismatch, so it never folds intents into a policy the deployment did
16//!   not pin.
17//!
18//! Output (unsigned, never signed, never installed here): a new
19//! [`CompiledPolicy`] JSON with `generation = current + 1`, the SAME lattice
20//! compartment vocabulary, an empty TE matrix (enrollment-only, the
21//! `check_enrollment_only` contract), and the enrollment table = current
22//! table ∪ non-conflicted intents. Signing and distribution stay with the
23//! offline authority + config pin + restart; this module only stages the
24//! reviewed input and prints the exact `trust hash-mac-boot-policy` command.
25//!
26//! Fail closed everywhere:
27//! - unreadable/corrupt/gapped/locked journal ⇒ refuse (no output);
28//! - missing/undecodable current policy, or any pin mismatch ⇒ refuse;
29//! - a current policy with non-empty TE rules ⇒ refuse (the reconciler never
30//!   authors TE authority);
31//! - conflicting intents ⇒ emit the policy WITHOUT every subject touched by
32//!   a conflict and list them in the report for operator resolution —
33//!   conflicts are never auto-resolved;
34//! - intent labels outside the allowed user-clearance vocabulary
35//!   (`internal` / `confidential`, design risk #5) ⇒ that intent is excluded
36//!   (deny-side) and reported, never silently mapped.
37
38use std::collections::BTreeSet;
39use std::io::Write as _;
40use std::path::{Path, PathBuf};
41
42use serde::Serialize;
43
44use crate::mac::compiled::{CompiledPolicy, PolicyDistError, SignedPolicy};
45use crate::mac::enrollment_journal::{EnrollmentJournal, JournalError, RecordBody};
46use crate::mac::lattice::{
47    Assurance, CompartmentSet, Lattice, LatticeVersion, Level, SecurityLabel,
48};
49use crate::mac::te::TeMatrix;
50
51/// File name of the emitted unsigned `CompiledPolicy` JSON inside the output
52/// directory.
53pub const UNSIGNED_POLICY_FILE: &str = "unsigned-policy.json";
54/// File name of the reconciliation report inside the output directory.
55pub const RECONCILE_REPORT_FILE: &str = "reconcile-report.json";
56
57#[derive(Debug, thiserror::Error)]
58pub enum ReconcileError {
59    /// Unreadable, corrupt, gapped, or locked journal — refuse to emit.
60    #[error("enrollment journal refused: {0}")]
61    Journal(#[from] JournalError),
62    /// The current (config-pinned) signed policy artifact is not on disk.
63    #[error("current MAC boot policy is missing at {0} — refusing to reconcile")]
64    MissingCurrentPolicy(PathBuf),
65    /// The current signed policy artifact does not decode.
66    #[error("current MAC boot policy does not decode: {0}")]
67    CurrentPolicyDecode(String),
68    /// The artifact disagrees with the operator-supplied OS-owned pin
69    /// (generation or recomputed hash) — never fold intents into an
70    /// unpinned artifact.
71    #[error("current MAC boot policy fails the config pin: {0}")]
72    PinMismatch(String),
73    /// The current policy carries TE authority; this reconciler only ever
74    /// produces enrollment-only artifacts.
75    #[error("current MAC boot policy is not enrollment-only — refusing to reconcile")]
76    NotEnrollmentOnly,
77    #[error("policy canonicalization failed: {0}")]
78    Policy(#[from] PolicyDistError),
79    /// The output directory already exists; reconciler outputs are never
80    /// overwritten (same publication rule as the signing ceremony).
81    #[error("reconcile output directory already exists: {0}")]
82    OutputExists(PathBuf),
83    #[error("reconcile output I/O: {0}")]
84    Io(#[from] std::io::Error),
85    /// Generation exceeds the lattice version width (u32) — refuse rather
86    /// than wrap.
87    #[error("policy generation {0} exceeds the lattice version width")]
88    GenerationOverflow(u64),
89}
90
91/// An intent folded into the new enrollment table.
92#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
93pub struct AppliedIntent {
94    pub seq: u64,
95    pub subject: String,
96    pub label: String,
97    /// `true` when the subject was already enrolled at the same label (the
98    /// fold is a no-op for it; the journal is authoritative-current, not a
99    /// diff log).
100    pub already_enrolled: bool,
101}
102
103/// An intent deliberately left OUT of the new table (fail-closed exclusion).
104#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
105#[serde(tag = "reason", rename_all = "snake_case")]
106pub enum ExcludedIntent {
107    /// The subject is touched by a conflict record; neither copy is enrolled
108    /// until an operator disambiguates the journal out-of-band.
109    ConflictedSubject { seq: u64, subject: String },
110    /// The intent's label is outside the user-clearance vocabulary the
111    /// reconciler is allowed to assign (`internal` / `confidential`).
112    UnsupportedLabel {
113        seq: u64,
114        subject: String,
115        label: String,
116    },
117}
118
119/// A durable conflict record surfaced for operator resolution.
120#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
121pub struct ConflictSummary {
122    pub seq: u64,
123    pub attempted_subject: String,
124    pub attempted_label: String,
125    pub reason: String,
126}
127
128/// What the reconciler produced — mirrored to `reconcile-report.json` next to
129/// the unsigned policy so the offline reviewer sees exactly what changed.
130#[derive(Clone, Debug, Serialize)]
131pub struct ReconcileReport {
132    pub current_generation: u64,
133    pub new_generation: u64,
134    /// Hex BLAKE3 policy hash of the verified current artifact (matches the
135    /// supplied pin — reconciliation refuses otherwise).
136    pub current_policy_hash: String,
137    /// Hex BLAKE3 policy hash of the emitted unsigned policy; the reviewer
138    /// confirms this exact value via the hash command below before signing.
139    pub new_policy_hash: String,
140    pub current_enrollment_count: usize,
141    pub new_enrollment_count: usize,
142    pub applied: Vec<AppliedIntent>,
143    pub excluded: Vec<ExcludedIntent>,
144    pub conflicts: Vec<ConflictSummary>,
145    /// Path of the emitted unsigned `CompiledPolicy` JSON.
146    pub unsigned_policy_path: PathBuf,
147    /// The exact hash command for the offline authority. `--reviewed-ucan`
148    /// stays operator-authored (an authority-reviewed empty-capability UCAN);
149    /// the reconciler never fabricates the review input.
150    pub hash_command: String,
151}
152
153/// Map an intent's clearance label onto the lattice vocabulary. Only
154/// `internal` / `confidential` are assignable to user enrollments (design
155/// risk #5): the resolver floors every enrolled subject at
156/// `Assurance::Classical` regardless (Decision D), and user clearances never
157/// carry compartments. Anything else is excluded fail-closed by the caller.
158fn user_clearance_label(label: &str) -> Option<SecurityLabel> {
159    let level = match label.to_ascii_lowercase().as_str() {
160        "internal" => Level::Internal,
161        "confidential" => Level::Confidential,
162        _ => return None,
163    };
164    Some(SecurityLabel::new(
165        level,
166        Assurance::Classical,
167        CompartmentSet::EMPTY,
168    ))
169}
170
171/// Read and validate the CURRENT boot policy against the operator-supplied
172/// OS-owned pin. The artifact's own hash is recomputed — the pin, not the
173/// file, is trusted. (The artifact's hybrid signature was verified when the
174/// daemon installed it; the reconciler runs offline where the authority
175/// roster need not be present, so the BLAKE3 pin match is the integrity
176/// check here.)
177fn load_current_policy(
178    policy_path: &Path,
179    expected_generation: u64,
180    expected_policy_hash: &str,
181) -> Result<(CompiledPolicy, [u8; 32]), ReconcileError> {
182    let bytes = std::fs::read(policy_path).map_err(|error| {
183        if error.kind() == std::io::ErrorKind::NotFound {
184            ReconcileError::MissingCurrentPolicy(policy_path.to_path_buf())
185        } else {
186            ReconcileError::Io(error)
187        }
188    })?;
189    let signed: SignedPolicy = serde_json::from_slice(&bytes)
190        .map_err(|e| ReconcileError::CurrentPolicyDecode(e.to_string()))?;
191    let policy = CompiledPolicy::decode_canonical(&signed.policy_bytes)
192        .map_err(|e| ReconcileError::CurrentPolicyDecode(e.to_string()))?;
193    if policy.generation != signed.generation {
194        return Err(ReconcileError::PinMismatch(format!(
195            "outer generation {} != inner {}",
196            signed.generation, policy.generation
197        )));
198    }
199    let expected_hash: [u8; 32] = hex::decode(expected_policy_hash)
200        .ok()
201        .and_then(|v| <[u8; 32]>::try_from(v).ok())
202        .ok_or_else(|| {
203            ReconcileError::PinMismatch("expected hash is not 32 bytes of hex".to_owned())
204        })?;
205    let actual_hash = policy.policy_hash()?;
206    if policy.generation != expected_generation {
207        return Err(ReconcileError::PinMismatch(format!(
208            "generation {} != pinned {}",
209            policy.generation, expected_generation
210        )));
211    }
212    if actual_hash != expected_hash {
213        return Err(ReconcileError::PinMismatch(
214            "recomputed policy hash != pinned hash".to_owned(),
215        ));
216    }
217    let (allow, escalate) = policy.matrix.sorted_rules();
218    if !(allow.is_empty() && escalate.is_empty()) {
219        return Err(ReconcileError::NotEnrollmentOnly);
220    }
221    Ok((policy, actual_hash))
222}
223
224/// Fold the journal into the next unsigned boot-policy generation and stage
225/// it, unsigned, for the offline ceremony. NEVER signs and NEVER installs.
226///
227/// - `journal_dir`: the intent journal directory (opened under its flock;
228///   run this where the provisioning writer is quiescent).
229/// - `current_policy_path` + `expected_generation` + `expected_policy_hash`:
230///   the OS-owned config pin ([`crate::config::MacBootPolicyConfig`]).
231/// - `output_dir`: MUST NOT exist; created atomically and never overwritten.
232pub fn reconcile_enrollment(
233    journal_dir: &Path,
234    current_policy_path: &Path,
235    expected_generation: u64,
236    expected_policy_hash: &str,
237    output_dir: &Path,
238) -> Result<ReconcileReport, ReconcileError> {
239    // Fail closed on any journal problem before touching policy state.
240    let journal = EnrollmentJournal::open(journal_dir)?;
241    let (current, current_hash) = load_current_policy(
242        current_policy_path,
243        expected_generation,
244        expected_policy_hash,
245    )?;
246
247    // Subjects touched by a conflict are excluded wholesale: neither the
248    // attempted record nor the committed copy it collided with is enrolled
249    // until an operator disambiguates. Key-reuse conflicts additionally
250    // exclude the subject holding the reused key ("refuses to enroll either
251    // copy", design §2.2).
252    let mut conflicted_subjects: BTreeSet<String> = BTreeSet::new();
253    let mut conflicts = Vec::new();
254    for (seq, conflict) in journal.conflicts() {
255        conflicted_subjects.insert(conflict.attempted.subject.clone());
256        if let Some(key) = &conflict.attempted.idempotency_key {
257            for record in journal.records() {
258                if let RecordBody::Intent(existing) = &record.body {
259                    if existing.idempotency_key.as_deref() == Some(key.as_str()) {
260                        conflicted_subjects.insert(existing.subject.clone());
261                    }
262                }
263            }
264        }
265        conflicts.push(ConflictSummary {
266            seq,
267            attempted_subject: conflict.attempted.subject.clone(),
268            attempted_label: conflict.attempted.label.clone(),
269            reason: format!("{:?}", conflict.reason),
270        });
271    }
272
273    let mut table = current.enrollment.clone();
274    let mut applied = Vec::new();
275    let mut excluded = Vec::new();
276    for (seq, intent) in journal.intents() {
277        if conflicted_subjects.contains(&intent.subject) {
278            excluded.push(ExcludedIntent::ConflictedSubject {
279                seq,
280                subject: intent.subject.clone(),
281            });
282            continue;
283        }
284        let Some(label) = user_clearance_label(&intent.label) else {
285            excluded.push(ExcludedIntent::UnsupportedLabel {
286                seq,
287                subject: intent.subject.clone(),
288                label: intent.label.clone(),
289            });
290            continue;
291        };
292        let already_enrolled = table.get(&intent.subject) == Some(&label);
293        table.insert(intent.subject.clone(), label);
294        applied.push(AppliedIntent {
295            seq,
296            subject: intent.subject.clone(),
297            label: intent.label.clone(),
298            already_enrolled,
299        });
300    }
301
302    // Next generation: same lattice vocabulary, empty TE matrix, generation
303    // taken from the verified CURRENT artifact + 1 — never from a local
304    // counter (design §4).
305    let new_generation = current.generation + 1;
306    let current_lattice = current
307        .lattice()
308        .map_err(|e| ReconcileError::CurrentPolicyDecode(e.to_string()))?;
309    let lattice = Lattice::new(
310        LatticeVersion(
311            u32::try_from(new_generation)
312                .map_err(|_| ReconcileError::GenerationOverflow(new_generation))?,
313        ),
314        current_lattice.compartment_names().to_vec(),
315    );
316    let policy = CompiledPolicy::new(TeMatrix::default(), &lattice).with_enrollment(table);
317    let new_hash = policy.policy_hash()?;
318
319    publish_outputs(output_dir, &policy, |policy_path| {
320        ReconcileReport {
321        current_generation: current.generation,
322        new_generation,
323        current_policy_hash: hex::encode(current_hash),
324        new_policy_hash: hex::encode(new_hash),
325        current_enrollment_count: current.enrollment.len(),
326        new_enrollment_count: policy.enrollment.len(),
327        applied,
328        excluded,
329        conflicts,
330        hash_command: format!(
331            "hyprstream trust hash-mac-boot-policy --policy-input {} --reviewed-ucan <REVIEWED_EMPTY_UCAN_JSON>",
332            policy_path.display()
333        ),
334        unsigned_policy_path: policy_path.to_path_buf(),
335    }
336    })
337}
338
339/// Stage `unsigned-policy.json` + `reconcile-report.json` and publish them
340/// atomically into a NEW directory (the signing ceremony's never-overwrite
341/// rule, `publish_boot_artifacts`). A failure leaves at most the empty
342/// reservation, which cannot be mistaken for a policy.
343fn publish_outputs(
344    output_dir: &Path,
345    policy: &CompiledPolicy,
346    report: impl FnOnce(&Path) -> ReconcileReport,
347) -> Result<ReconcileReport, ReconcileError> {
348    let parent = output_dir
349        .parent()
350        .filter(|p| !p.as_os_str().is_empty())
351        .unwrap_or_else(|| Path::new("."));
352    let staged = tempfile::tempdir_in(parent)?;
353    let policy_path = output_dir.join(UNSIGNED_POLICY_FILE);
354    let report = report(&policy_path);
355    for (name, bytes) in [
356        (
357            UNSIGNED_POLICY_FILE,
358            serde_json::to_vec_pretty(policy)
359                .map_err(|e| ReconcileError::Policy(PolicyDistError::Encode(e.to_string())))?,
360        ),
361        (
362            RECONCILE_REPORT_FILE,
363            serde_json::to_vec_pretty(&report)
364                .map_err(|e| ReconcileError::Policy(PolicyDistError::Encode(e.to_string())))?,
365        ),
366    ] {
367        let mut file = std::fs::File::create(staged.path().join(name))?;
368        file.write_all(&bytes)?;
369        #[cfg(unix)]
370        {
371            use std::os::unix::fs::PermissionsExt as _;
372            file.set_permissions(std::fs::Permissions::from_mode(0o644))?;
373        }
374        file.sync_all()?;
375    }
376    #[cfg(unix)]
377    {
378        use std::os::unix::fs::PermissionsExt as _;
379        std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755))?;
380    }
381    std::fs::File::open(staged.path())?.sync_all()?;
382    if output_dir.exists() {
383        return Err(ReconcileError::OutputExists(output_dir.to_path_buf()));
384    }
385    std::fs::create_dir(output_dir)?;
386    std::fs::rename(staged.path(), output_dir)?;
387    std::fs::File::open(parent)?.sync_all()?;
388    Ok(report)
389}
390
391#[cfg(test)]
392#[allow(clippy::unwrap_used, clippy::expect_used)]
393mod tests {
394    use super::*;
395    use crate::mac::enrollment_journal::{AppendOutcome, EnrollmentIntent};
396    use crate::mac::lattice::Compartment;
397    use hyprstream_rpc::auth::ucan::token::{Did, Ucan, UcanPayload};
398    use std::collections::BTreeMap;
399
400    fn intent(subject: &str, label: &str, epoch: u64, key: Option<&str>) -> EnrollmentIntent {
401        EnrollmentIntent {
402            subject: subject.to_owned(),
403            label: label.to_owned(),
404            provision_epoch: epoch,
405            idempotency_key: key.map(str::to_owned),
406        }
407    }
408
409    fn empty_grant() -> Ucan {
410        let did = Did::from_ed25519(&[0u8; 32]);
411        Ucan {
412            payload: UcanPayload {
413                issuer: did.clone(),
414                audience: did,
415                capabilities: vec![],
416                not_before: None,
417                expiration: None,
418                nonce: vec![],
419            },
420            proofs: vec![],
421            signature: vec![],
422        }
423    }
424
425    /// Write a current-artifact fixture (signed-policy-shaped JSON whose
426    /// signature is irrelevant here — the pin anchors it) plus the matching
427    /// pin values.
428    fn write_current_policy(
429        dir: &Path,
430        generation: u64,
431        enrollment: BTreeMap<String, SecurityLabel>,
432    ) -> (PathBuf, u64, String, CompiledPolicy) {
433        let policy = CompiledPolicy::new(
434            TeMatrix::default(),
435            &Lattice::new(
436                LatticeVersion(u32::try_from(generation).unwrap()),
437                [Compartment::new("pii")],
438            ),
439        )
440        .with_enrollment(enrollment);
441        let signed = SignedPolicy {
442            policy_bytes: policy.canonical_bytes().unwrap(),
443            signature: vec![],
444            generation,
445        };
446        let path = dir.join("signed-policy.json");
447        std::fs::write(&path, serde_json::to_vec(&signed).unwrap()).unwrap();
448        (
449            path,
450            generation,
451            hex::encode(policy.policy_hash().unwrap()),
452            policy,
453        )
454    }
455
456    fn enrolled(subject: &str, level: Level) -> (String, SecurityLabel) {
457        (
458            subject.to_owned(),
459            SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY),
460        )
461    }
462
463    fn read_emitted_policy(report: &ReconcileReport) -> CompiledPolicy {
464        serde_json::from_slice(&std::fs::read(&report.unsigned_policy_path).unwrap()).unwrap()
465    }
466
467    #[test]
468    fn intents_fold_into_next_generation_table() {
469        let tmp = tempfile::tempdir().unwrap();
470        let journal_dir = tmp.path().join("journal");
471        {
472            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
473            journal
474                .append(intent("alice", "internal", 1, Some("hosted:t1")))
475                .unwrap();
476            journal
477                .append(intent(
478                    "did:web:b.example.com",
479                    "confidential",
480                    2,
481                    Some("jit:i\u{1f}s"),
482                ))
483                .unwrap();
484        }
485        let (policy_path, generation, hash, current) = write_current_policy(
486            tmp.path(),
487            7,
488            BTreeMap::from([enrolled("carol", Level::Internal)]),
489        );
490        let output = tmp.path().join("out");
491        let report =
492            reconcile_enrollment(&journal_dir, &policy_path, generation, &hash, &output).unwrap();
493
494        assert_eq!(report.current_generation, 7);
495        assert_eq!(report.new_generation, 8);
496        assert_eq!(report.current_enrollment_count, 1);
497        assert_eq!(report.new_enrollment_count, 3);
498        assert_eq!(report.applied.len(), 2);
499        assert!(report.excluded.is_empty() && report.conflicts.is_empty());
500        assert!(report
501            .hash_command
502            .starts_with("hyprstream trust hash-mac-boot-policy --policy-input "));
503
504        let policy = read_emitted_policy(&report);
505        assert_eq!(policy.generation, 8);
506        assert_eq!(policy.lattice().unwrap().version().generation(), 8);
507        // Lattice vocabulary is carried over untouched.
508        assert_eq!(
509            policy.lattice().unwrap().compartment_names(),
510            current.lattice().unwrap().compartment_names()
511        );
512        // TE matrix untouched: still empty.
513        let (allow, escalate) = policy.matrix.sorted_rules();
514        assert!(allow.is_empty() && escalate.is_empty());
515        // Current table + pending intents.
516        assert_eq!(
517            policy.clearance_for("carol"),
518            current.clearance_for("carol")
519        );
520        assert_eq!(
521            policy.clearance_for("alice"),
522            user_clearance_label("internal")
523        );
524        assert_eq!(
525            policy.clearance_for("did:web:b.example.com"),
526            user_clearance_label("confidential")
527        );
528        assert_eq!(
529            hex::encode(policy.policy_hash().unwrap()),
530            report.new_policy_hash
531        );
532        // The emitted artifact passes the ceremony's enrollment-only gate.
533        crate::mac::bootload::check_enrollment_only(&policy, &empty_grant()).unwrap();
534
535        // Outputs are never overwritten.
536        assert!(matches!(
537            reconcile_enrollment(&journal_dir, &policy_path, generation, &hash, &output),
538            Err(ReconcileError::OutputExists(_))
539        ));
540    }
541
542    #[test]
543    fn hosted_signup_pair_enrolls_both_the_did_and_the_local_username() {
544        let tmp = tempfile::tempdir().unwrap();
545        let journal_dir = tmp.path().join("journal");
546        {
547            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
548            for intent in crate::mac::enrollment_journal::hosted_signup_intents(
549                "did:web:alice.acct.example.com",
550                "alice",
551                Some("tx-1"),
552                1,
553            ) {
554                journal.append(intent).unwrap();
555            }
556        }
557        let (policy_path, generation, hash, _current) =
558            write_current_policy(tmp.path(), 1, BTreeMap::new());
559        let output = tmp.path().join("out");
560        let report =
561            reconcile_enrollment(&journal_dir, &policy_path, generation, &hash, &output).unwrap();
562
563        // Both subjects of the hosted signup fold into the next table: the
564        // DID (atproto-profile `sub`) and the bare local username
565        // (native-profile `sub`) resolve the same clearance, so neither
566        // token profile mints unlabeled.
567        assert_eq!(report.new_enrollment_count, 2);
568        assert!(report.excluded.is_empty() && report.conflicts.is_empty());
569        let policy = read_emitted_policy(&report);
570        assert_eq!(
571            policy.clearance_for("did:web:alice.acct.example.com"),
572            user_clearance_label("internal")
573        );
574        assert_eq!(
575            policy.clearance_for("alice"),
576            user_clearance_label("internal")
577        );
578    }
579
580    #[test]
581    fn already_enrolled_intent_is_a_noop_fold() {
582        let tmp = tempfile::tempdir().unwrap();
583        let journal_dir = tmp.path().join("journal");
584        {
585            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
586            journal
587                .append(intent("alice", "internal", 1, Some("hosted:t1")))
588                .unwrap();
589        }
590        let (policy_path, generation, hash, current) = write_current_policy(
591            tmp.path(),
592            3,
593            BTreeMap::from([enrolled("alice", Level::Internal)]),
594        );
595        let report = reconcile_enrollment(
596            &journal_dir,
597            &policy_path,
598            generation,
599            &hash,
600            &tmp.path().join("out"),
601        )
602        .unwrap();
603        assert_eq!(report.applied.len(), 1);
604        assert!(report.applied[0].already_enrolled);
605        let policy = read_emitted_policy(&report);
606        assert_eq!(policy.enrollment, current.enrollment);
607        assert_eq!(policy.generation, 4);
608    }
609
610    #[test]
611    fn subject_collision_excludes_both_copies_and_reports() {
612        let tmp = tempfile::tempdir().unwrap();
613        let journal_dir = tmp.path().join("journal");
614        {
615            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
616            journal
617                .append(intent("alice", "internal", 1, Some("hosted:t1")))
618                .unwrap();
619            assert_eq!(
620                journal
621                    .append(intent("alice", "internal", 2, Some("hosted:t2")))
622                    .unwrap(),
623                AppendOutcome::Conflict { seq: 1 }
624            );
625            // An unrelated clean intent still folds.
626            journal
627                .append(intent("bob", "internal", 3, Some("hosted:t3")))
628                .unwrap();
629        }
630        let (policy_path, generation, hash, _) =
631            write_current_policy(tmp.path(), 7, BTreeMap::new());
632        let report = reconcile_enrollment(
633            &journal_dir,
634            &policy_path,
635            generation,
636            &hash,
637            &tmp.path().join("out"),
638        )
639        .unwrap();
640
641        assert_eq!(report.conflicts.len(), 1);
642        assert_eq!(report.conflicts[0].attempted_subject, "alice");
643        assert_eq!(
644            report.excluded,
645            vec![ExcludedIntent::ConflictedSubject {
646                seq: 0,
647                subject: "alice".to_owned()
648            }]
649        );
650        let policy = read_emitted_policy(&report);
651        assert!(
652            policy.clearance_for("alice").is_none(),
653            "never auto-resolve"
654        );
655        assert!(policy.clearance_for("bob").is_some());
656    }
657
658    #[test]
659    fn key_reuse_conflict_excludes_both_subjects() {
660        let tmp = tempfile::tempdir().unwrap();
661        let journal_dir = tmp.path().join("journal");
662        {
663            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
664            journal
665                .append(intent("alice", "internal", 1, Some("hosted:t1")))
666                .unwrap();
667            assert_eq!(
668                journal
669                    .append(intent("mallory", "internal", 2, Some("hosted:t1")))
670                    .unwrap(),
671                AppendOutcome::Conflict { seq: 1 }
672            );
673        }
674        let (policy_path, generation, hash, _) =
675            write_current_policy(tmp.path(), 7, BTreeMap::new());
676        let report = reconcile_enrollment(
677            &journal_dir,
678            &policy_path,
679            generation,
680            &hash,
681            &tmp.path().join("out"),
682        )
683        .unwrap();
684        let policy = read_emitted_policy(&report);
685        // "Refuses to enroll either copy": the attempted subject AND the
686        // subject holding the reused key are both held out.
687        assert!(policy.clearance_for("mallory").is_none());
688        assert!(policy.clearance_for("alice").is_none());
689        assert_eq!(report.excluded.len(), 1);
690        assert_eq!(report.conflicts.len(), 1);
691    }
692
693    #[test]
694    fn generation_comes_from_pinned_current_monotonically() {
695        let tmp = tempfile::tempdir().unwrap();
696        let journal_dir = tmp.path().join("journal");
697        EnrollmentJournal::open(&journal_dir).unwrap();
698        let (policy_path, generation, hash, _) =
699            write_current_policy(tmp.path(), 41, BTreeMap::new());
700        // Wrong pinned generation refuses — no counter of our own.
701        assert!(matches!(
702            reconcile_enrollment(
703                &journal_dir,
704                &policy_path,
705                40,
706                &hash,
707                &tmp.path().join("out")
708            ),
709            Err(ReconcileError::PinMismatch(_))
710        ));
711        assert!(!tmp.path().join("out").exists());
712        let report = reconcile_enrollment(
713            &journal_dir,
714            &policy_path,
715            generation,
716            &hash,
717            &tmp.path().join("out2"),
718        )
719        .unwrap();
720        assert_eq!(report.new_generation, 42);
721    }
722
723    #[test]
724    fn enrollment_only_invariant_is_enforced_on_input_and_output() {
725        use crate::mac::te::{Action, ObjectType, SubjectType, TeRule};
726        let tmp = tempfile::tempdir().unwrap();
727        let journal_dir = tmp.path().join("journal");
728        EnrollmentJournal::open(&journal_dir).unwrap();
729        // A current artifact carrying TE authority is refused outright.
730        let rule = TeRule {
731            subject_type: SubjectType(1),
732            object_type: ObjectType(1),
733            action: Action(1),
734        };
735        let policy = CompiledPolicy::new(
736            TeMatrix::from_allow([rule]),
737            &Lattice::new(LatticeVersion(7), []),
738        );
739        let signed = SignedPolicy {
740            policy_bytes: policy.canonical_bytes().unwrap(),
741            signature: vec![],
742            generation: 7,
743        };
744        let path = tmp.path().join("signed-policy.json");
745        std::fs::write(&path, serde_json::to_vec(&signed).unwrap()).unwrap();
746        let hash = hex::encode(policy.policy_hash().unwrap());
747        assert!(matches!(
748            reconcile_enrollment(&journal_dir, &path, 7, &hash, &tmp.path().join("out")),
749            Err(ReconcileError::NotEnrollmentOnly)
750        ));
751    }
752
753    #[test]
754    fn corrupt_or_missing_inputs_refuse_without_output() {
755        let tmp = tempfile::tempdir().unwrap();
756        let (policy_path, generation, hash, _) =
757            write_current_policy(tmp.path(), 7, BTreeMap::new());
758
759        // Corrupt journal.
760        let journal_dir = tmp.path().join("journal");
761        std::fs::create_dir(&journal_dir).unwrap();
762        std::fs::write(
763            journal_dir.join(crate::mac::enrollment_journal::JOURNAL_FILE_NAME),
764            b"not json\n",
765        )
766        .unwrap();
767        assert!(matches!(
768            reconcile_enrollment(
769                &journal_dir,
770                &policy_path,
771                generation,
772                &hash,
773                &tmp.path().join("out")
774            ),
775            Err(ReconcileError::Journal(JournalError::Decode { .. }))
776        ));
777        assert!(!tmp.path().join("out").exists());
778
779        // Missing current policy.
780        let good_journal = tmp.path().join("journal2");
781        EnrollmentJournal::open(&good_journal).unwrap();
782        assert!(matches!(
783            reconcile_enrollment(
784                &good_journal,
785                &tmp.path().join("absent.json"),
786                generation,
787                &hash,
788                &tmp.path().join("out2"),
789            ),
790            Err(ReconcileError::MissingCurrentPolicy(_))
791        ));
792        assert!(!tmp.path().join("out2").exists());
793
794        // Tampered artifact (hash pin mismatch).
795        let mut bytes = std::fs::read(&policy_path).unwrap();
796        let len = bytes.len();
797        bytes[len - 12] ^= 1;
798        let tampered = tmp.path().join("tampered.json");
799        std::fs::write(&tampered, bytes).unwrap();
800        assert!(matches!(
801            reconcile_enrollment(
802                &good_journal,
803                &tampered,
804                generation,
805                &hash,
806                &tmp.path().join("out3")
807            ),
808            Err(ReconcileError::CurrentPolicyDecode(_)) | Err(ReconcileError::PinMismatch(_))
809        ));
810        assert!(!tmp.path().join("out3").exists());
811    }
812
813    #[test]
814    fn unsupported_labels_are_excluded_fail_closed() {
815        let tmp = tempfile::tempdir().unwrap();
816        let journal_dir = tmp.path().join("journal");
817        {
818            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
819            journal
820                .append(intent("rootish", "secret", 1, Some("hosted:t1")))
821                .unwrap();
822            journal
823                .append(intent("alice", "Internal", 2, Some("hosted:t2")))
824                .unwrap();
825        }
826        let (policy_path, generation, hash, _) =
827            write_current_policy(tmp.path(), 7, BTreeMap::new());
828        let report = reconcile_enrollment(
829            &journal_dir,
830            &policy_path,
831            generation,
832            &hash,
833            &tmp.path().join("out"),
834        )
835        .unwrap();
836        assert_eq!(
837            report.excluded,
838            vec![ExcludedIntent::UnsupportedLabel {
839                seq: 0,
840                subject: "rootish".to_owned(),
841                label: "secret".to_owned()
842            }]
843        );
844        let policy = read_emitted_policy(&report);
845        assert!(policy.clearance_for("rootish").is_none());
846        // Label matching is case-insensitive for the allowed vocabulary.
847        assert_eq!(
848            policy.clearance_for("alice"),
849            user_clearance_label("internal")
850        );
851    }
852
853    #[test]
854    fn report_is_serialized_next_to_the_policy() {
855        let tmp = tempfile::tempdir().unwrap();
856        let journal_dir = tmp.path().join("journal");
857        {
858            let mut journal = EnrollmentJournal::open(&journal_dir).unwrap();
859            journal
860                .append(intent("alice", "internal", 1, Some("hosted:t1")))
861                .unwrap();
862        }
863        let (policy_path, generation, hash, _) =
864            write_current_policy(tmp.path(), 7, BTreeMap::new());
865        let output = tmp.path().join("out");
866        let report =
867            reconcile_enrollment(&journal_dir, &policy_path, generation, &hash, &output).unwrap();
868        let on_disk: serde_json::Value =
869            serde_json::from_slice(&std::fs::read(output.join(RECONCILE_REPORT_FILE)).unwrap())
870                .unwrap();
871        assert_eq!(on_disk["new_generation"], 8);
872        assert_eq!(
873            on_disk["new_policy_hash"].as_str().unwrap(),
874            report.new_policy_hash
875        );
876        assert!(on_disk["hash_command"]
877            .as_str()
878            .unwrap()
879            .contains(&report.unsigned_policy_path.display().to_string()));
880    }
881}