Skip to main content

hyprstream_core/mac/
enrollment_journal.rs

1//! Enrollment-intent journal (#698 Phase 2) — the durable, append-only record
2//! of *intent to enroll* a provisioned subject into the MAC clearance table.
3//!
4//! Design: `docs/mac-architecture.md` "Enrollment lifecycle (#698 Phase 2)".
5//! Provisioning code (hosted-account mint, OIDC JIT first login) appends one
6//! intent record per newly provisioned subject. A later single-writer
7//! reconciler folds acknowledged intents into an unsigned `CompiledPolicy`
8//! for the offline `trust sign-mac-boot-policy` ceremony; the Policy
9//! authority key never comes online.
10//!
11//! Semantics (fail closed, mirroring the hosted-mint reservation):
12//!
13//! - **Idempotency**: keyed intents (hosted: `transaction_id`; JIT: the
14//!   atomically-bound `(issuer, subject)` pair) replay as a no-op — same key
15//!   AND same `(subject, label)` returns [`AppendOutcome::Replay`] without a
16//!   write (`provision_epoch` is observational and excluded from the match).
17//! - **Ambiguous retry ⇒ conflict**: same key with a different payload, a
18//!   subject already journaled under a different key, or a keyless retry of an
19//!   already-journaled subject appends a **conflict record**. The reconciler
20//!   refuses to enroll either copy until an operator disambiguates. There is
21//!   no silent second intent.
22//! - **Durability** (audit-journal pattern, `mac/audit.rs`): each append is
23//!   written, the *file* is fsynced, then the *directory* is fsynced before
24//!   the intent is considered committed. A record is never acknowledged
25//!   before it survives a crash.
26//!
27//! The store is a single JSON-lines file under a journal directory. This is
28//! deliberately the same local, fsync-ordered pattern as `mac/audit.rs`
29//! rather than the deployment records store: the OAuth service already owns
30//! the PDS root filesystem, and the reconciler is the single writer/reader —
31//! no second backend (and its selection ambiguity) is introduced in the
32//! provisioning hot path. Append serialization is enforced (process-global
33//! cached writer per directory under one mutex in-process; non-blocking
34//! exclusive `flock` cross-process — fail closed, never interleave); keep
35//! the journal on a local filesystem.
36
37use std::collections::HashMap;
38use std::fs::{File, OpenOptions};
39use std::io::{BufRead, BufReader, Write};
40use std::os::unix::fs::OpenOptionsExt as _;
41use std::os::unix::io::AsRawFd as _;
42use std::path::{Path, PathBuf};
43use std::sync::OnceLock;
44
45use nix::fcntl::{flock, FlockArg};
46use serde::{Deserialize, Serialize};
47
48/// Journal file name within the journal directory.
49pub const JOURNAL_FILE_NAME: &str = "enrollment-intents.jsonl";
50
51/// Cross-process writer lock file within the journal directory.
52pub const LOCK_FILE_NAME: &str = "enrollment-intents.lock";
53
54/// Clearance label recorded for intents appended by the provisioning hooks.
55///
56/// The reconciler maps this onto the lattice vocabulary when it builds the
57/// unsigned policy; the resolver floors every enrolled subject at
58/// `Assurance::Classical` regardless (Decision D), so only `Internal` /
59/// `Confidential`-tier labels are meaningful for user enrollments.
60pub const DEFAULT_ENROLLMENT_CLEARANCE: &str = "internal";
61
62/// Idempotency key for a hosted-account mint: the signup transaction id the
63/// allocation reservation already binds to.
64pub fn hosted_idempotency_key(transaction_id: &str) -> String {
65    format!("hosted:{transaction_id}")
66}
67
68/// Idempotency key for the LOCAL-USERNAME alias of a hosted-account mint:
69/// same signup transaction as [`hosted_idempotency_key`], distinct subject.
70pub fn hosted_local_idempotency_key(transaction_id: &str) -> String {
71    format!("hosted-local:{transaction_id}")
72}
73
74/// Idempotency key for OIDC JIT provisioning: the atomically-bound
75/// `(issuer, subject)` pair from `resolve_or_bind_external_idp`. Unit
76/// separator keeps the pair unambiguous even if either field contains `:`.
77pub fn jit_idempotency_key(issuer: &str, external_subject: &str) -> String {
78    format!("jit:{issuer}\u{1f}{external_subject}")
79}
80
81/// The enrollment intents one hosted signup journals (#698 Phase 2): the
82/// hosted DID and the account's local username, both at the default label.
83///
84/// A hosted signup creates ONE account whose stable subject differs by
85/// token profile: the atproto profile mints `sub=<did>` (PAR is
86/// DPoP-mandatory there), while native Bearer-only clients (e.g. OpenCode)
87/// take the non-atproto profile and mint `sub=<username>`. The clearance
88/// resolver matches the enrollment table by exact subject, so enrolling
89/// only the DID leaves every native-profile credential unlabeled (denied
90/// NoClearance at the dispatch PEPs). Journaling both subjects keeps the
91/// username an authority-owned enrollment key exactly like the JIT path
92/// already does (`append_jit_enrollment_intent` journals the local
93/// username), and both keys stay replay-idempotent per transaction.
94pub fn hosted_signup_intents(
95    did: &str,
96    username: &str,
97    transaction_id: Option<&str>,
98    provision_epoch: u64,
99) -> Vec<EnrollmentIntent> {
100    let label = DEFAULT_ENROLLMENT_CLEARANCE.to_owned();
101    [
102        EnrollmentIntent {
103            subject: did.to_owned(),
104            label: label.clone(),
105            provision_epoch,
106            idempotency_key: transaction_id.map(hosted_idempotency_key),
107        },
108        EnrollmentIntent {
109            subject: username.to_owned(),
110            label,
111            provision_epoch,
112            idempotency_key: transaction_id.map(hosted_local_idempotency_key),
113        },
114    ]
115    .into()
116}
117
118/// One enrollment intent: enroll `subject` (a DID or local username, per the
119/// provisioning subsystem) at clearance `label`, observed at
120/// `provision_epoch` (caller-chosen epoch, e.g. unix seconds).
121#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
122pub struct EnrollmentIntent {
123    pub subject: String,
124    pub label: String,
125    pub provision_epoch: u64,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub idempotency_key: Option<String>,
128}
129
130/// Why an attempted append was recorded as a conflict instead of an intent.
131#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(rename_all = "snake_case")]
133pub enum ConflictReason {
134    /// Same idempotency key, different payload — a retry that cannot prove it
135    /// is the same operation.
136    KeyReuseMismatch,
137    /// Subject already journaled under a different idempotency key.
138    SubjectKeyCollision,
139    /// Keyless append for a subject the journal already holds — with no token
140    /// there is no way to prove this is not a duplicate.
141    UnkeyedDuplicate,
142}
143
144/// A conflict record: the refused attempt plus the reason. The reconciler
145/// halts on conflicts until an operator resolves them out-of-band.
146#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
147pub struct ConflictRecord {
148    pub attempted: EnrollmentIntent,
149    pub reason: ConflictReason,
150}
151
152/// The body of a journal record: a committed intent or a conflict.
153#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(tag = "kind", rename_all = "snake_case")]
155pub enum RecordBody {
156    Intent(EnrollmentIntent),
157    Conflict(ConflictRecord),
158}
159
160/// One durable journal record. `seq` is the journal-internal sequence,
161/// assigned monotonically from 0 with no gaps (enforced on open).
162#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
163pub struct JournalRecord {
164    pub seq: u64,
165    #[serde(flatten)]
166    pub body: RecordBody,
167}
168
169/// Result of an [`EnrollmentJournal::append`] call.
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub enum AppendOutcome {
172    /// The intent (or conflict) was durably committed at this sequence.
173    Committed { seq: u64 },
174    /// An identical keyed intent was already committed; nothing was written.
175    Replay { seq: u64 },
176    /// The attempt was ambiguous; a conflict record was durably committed.
177    Conflict { seq: u64 },
178}
179
180#[derive(Debug, thiserror::Error)]
181pub enum JournalError {
182    #[error("enrollment journal I/O: {0}")]
183    Io(#[from] std::io::Error),
184    #[error("enrollment journal record {seq} does not decode: {source}")]
185    Decode { seq: u64, source: serde_json::Error },
186    #[error("enrollment journal sequence gap: expected seq {expected}, found {found}")]
187    SequenceGap { expected: u64, found: u64 },
188    #[error("enrollment intent subject is empty")]
189    EmptySubject,
190    #[error("enrollment intent label is empty")]
191    EmptyLabel,
192    #[error("enrollment intent idempotency key is present but empty")]
193    EmptyIdempotencyKey,
194    #[error("enrollment journal directory is not configured")]
195    NotConfigured,
196    #[error("global enrollment journal directory is already set")]
197    GlobalDirAlreadySet,
198    /// Another process (or a second in-process opener that bypassed
199    /// [`record_intent`]) holds the journal lock. Fail closed: the
200    /// deployment is single-writer by design, so a contended journal is an
201    /// operator-visible error, never a silent queue.
202    #[error("enrollment journal at {0} is locked by another writer")]
203    Locked(PathBuf),
204}
205
206/// Append-only enrollment-intent journal. Append serialization is enforced,
207/// not assumed (review F1):
208///
209/// - **In-process**: [`record_intent`] funnels every append through a
210///   process-global cached writer map (`parking_lot` mutex): one instance
211///   per directory, opened once and reused — concurrent async signup/login
212///   handlers serialize on the mutex, and exactly one open file description
213///   ever holds the flock in this process. A long-lived
214///   `EnrollmentJournal`'s `&mut self` append is compile-time serialized.
215/// - **Cross-process**: [`open`](Self::open) takes a non-blocking exclusive
216///   `flock(2)` on `enrollment-intents.lock` in the journal directory and
217///   holds it for the instance's lifetime; a second opener — in any process,
218///   including this one — fails closed with [`JournalError::Locked`]. Two
219///   processes must never share one journal directory; the reconciler reads
220///   by taking the same lock after the writer is done.
221///
222/// Keep the journal directory on the OAuth host's local filesystem: `flock`
223/// and the fsync ordering above are not reliable over 9P/NFS-style shared
224/// mounts.
225pub struct EnrollmentJournal {
226    dir: PathBuf,
227    path: PathBuf,
228    /// Held for the instance's lifetime; the flock is bound to this open
229    /// file description and released on drop.
230    _lock_file: File,
231    records: Vec<JournalRecord>,
232    /// Idempotency key → index of the committed intent record.
233    key_index: HashMap<String, usize>,
234    /// Subject → index of the first committed intent record.
235    subject_index: HashMap<String, usize>,
236}
237
238impl EnrollmentJournal {
239    /// Open (creating if necessary) the journal under `dir`, reading and
240    /// validating every committed record. A corrupt or gapped journal fails
241    /// closed: `open` errors rather than guessing at recovery. Takes the
242    /// cross-process writer lock (see the type docs).
243    pub fn open(dir: impl AsRef<Path>) -> Result<Self, JournalError> {
244        let dir = dir.as_ref().to_path_buf();
245        let dir_existed = dir.exists();
246        {
247            use std::os::unix::fs::DirBuilderExt as _;
248            std::fs::DirBuilder::new()
249                .recursive(true)
250                .mode(0o700)
251                .create(&dir)?;
252        }
253        if !dir_existed {
254            // First creation: make the new directory entry itself durable
255            // before any record can be committed inside it (same pattern as
256            // the reservation/publish dirs in identity_registration.rs).
257            if let Some(parent) = dir.parent() {
258                sync_dir(parent)?;
259            }
260        }
261        let lock_path = dir.join(LOCK_FILE_NAME);
262        let lock_file = OpenOptions::new()
263            .create(true)
264            .read(true)
265            .append(true)
266            .mode(0o600)
267            .open(&lock_path)?;
268        flock(lock_file.as_raw_fd(), FlockArg::LockExclusiveNonblock).map_err(|errno| {
269            if errno == nix::errno::Errno::EWOULDBLOCK {
270                JournalError::Locked(dir.clone())
271            } else {
272                JournalError::Io(errno.into())
273            }
274        })?;
275        let path = dir.join(JOURNAL_FILE_NAME);
276        let mut records = Vec::new();
277        let mut key_index = HashMap::new();
278        let mut subject_index = HashMap::new();
279        match File::open(&path) {
280            Ok(file) => {
281                for (line_no, line) in BufReader::new(file).lines().enumerate() {
282                    let line = line?;
283                    if line.trim().is_empty() {
284                        continue;
285                    }
286                    let seq = line_no as u64;
287                    let record: JournalRecord = serde_json::from_str(&line)
288                        .map_err(|source| JournalError::Decode { seq, source })?;
289                    if record.seq != seq {
290                        return Err(JournalError::SequenceGap {
291                            expected: seq,
292                            found: record.seq,
293                        });
294                    }
295                    if let RecordBody::Intent(intent) = &record.body {
296                        if let Some(key) = &intent.idempotency_key {
297                            key_index.insert(key.clone(), records.len());
298                        }
299                        subject_index
300                            .entry(intent.subject.clone())
301                            .or_insert(records.len());
302                    }
303                    records.push(record);
304                }
305            }
306            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
307            Err(error) => return Err(error.into()),
308        }
309        Ok(Self {
310            dir,
311            path,
312            _lock_file: lock_file,
313            records,
314            key_index,
315            subject_index,
316        })
317    }
318
319    /// Append an intent, applying the idempotency / fail-closed conflict
320    /// rules. The record is durable (file + directory fsync) before this
321    /// returns `Committed` or `Conflict`.
322    pub fn append(&mut self, intent: EnrollmentIntent) -> Result<AppendOutcome, JournalError> {
323        if intent.subject.is_empty() {
324            return Err(JournalError::EmptySubject);
325        }
326        if intent.label.is_empty() {
327            return Err(JournalError::EmptyLabel);
328        }
329        if intent.idempotency_key.as_deref().is_some_and(str::is_empty) {
330            return Err(JournalError::EmptyIdempotencyKey);
331        }
332
333        if let Some(key) = &intent.idempotency_key {
334            if let Some(&idx) = self.key_index.get(key) {
335                return match &self.records[idx].body {
336                    // Replay compares the operation payload (subject, label),
337                    // not the observational epoch: a self-healing retry
338                    // necessarily carries a later epoch and must not
339                    // false-conflict.
340                    RecordBody::Intent(existing)
341                        if existing.subject == intent.subject && existing.label == intent.label =>
342                    {
343                        Ok(AppendOutcome::Replay {
344                            seq: self.records[idx].seq,
345                        })
346                    }
347                    _ => self.append_conflict(intent, ConflictReason::KeyReuseMismatch),
348                };
349            }
350            if self.subject_index.contains_key(&intent.subject) {
351                return self.append_conflict(intent, ConflictReason::SubjectKeyCollision);
352            }
353            self.append_record(RecordBody::Intent(intent))
354        } else if self.subject_index.contains_key(&intent.subject) {
355            self.append_conflict(intent, ConflictReason::UnkeyedDuplicate)
356        } else {
357            self.append_record(RecordBody::Intent(intent))
358        }
359    }
360
361    fn append_conflict(
362        &mut self,
363        attempted: EnrollmentIntent,
364        reason: ConflictReason,
365    ) -> Result<AppendOutcome, JournalError> {
366        let seq =
367            match self.append_record(RecordBody::Conflict(ConflictRecord { attempted, reason }))? {
368                AppendOutcome::Committed { seq } => seq,
369                _ => unreachable!("append_record always commits"),
370            };
371        Ok(AppendOutcome::Conflict { seq })
372    }
373
374    /// Serialize, append, fsync file, fsync directory — in that order — then
375    /// admit the record to the in-memory index.
376    fn append_record(&mut self, body: RecordBody) -> Result<AppendOutcome, JournalError> {
377        let seq = self.records.len() as u64;
378        let record = JournalRecord { seq, body };
379        let mut line =
380            serde_json::to_vec(&record).map_err(|source| JournalError::Decode { seq, source })?;
381        line.push(b'\n');
382        {
383            let mut file = OpenOptions::new()
384                .create(true)
385                .append(true)
386                .mode(0o600)
387                .open(&self.path)?;
388            file.write_all(&line)?;
389            file.sync_all()?;
390        }
391        sync_dir(&self.dir)?;
392
393        if let RecordBody::Intent(intent) = &record.body {
394            if let Some(key) = &intent.idempotency_key {
395                self.key_index.insert(key.clone(), self.records.len());
396            }
397            self.subject_index
398                .entry(intent.subject.clone())
399                .or_insert(self.records.len());
400        }
401        self.records.push(record);
402        Ok(AppendOutcome::Committed { seq })
403    }
404
405    /// All committed records in sequence order — the reconciler's read API.
406    pub fn records(&self) -> &[JournalRecord] {
407        &self.records
408    }
409
410    /// Iterate committed records in sequence order.
411    pub fn iter(&self) -> impl ExactSizeIterator<Item = &JournalRecord> + DoubleEndedIterator {
412        self.records.iter()
413    }
414
415    /// Iterate committed (non-conflict) intents with their sequences. This is
416    /// the stream the reconciler folds into the next unsigned policy
417    /// generation; conflict records are excluded and must be handled
418    /// separately by the operator.
419    pub fn intents(&self) -> impl Iterator<Item = (u64, &EnrollmentIntent)> {
420        self.records.iter().filter_map(|record| match &record.body {
421            RecordBody::Intent(intent) => Some((record.seq, intent)),
422            RecordBody::Conflict(_) => None,
423        })
424    }
425
426    /// Iterate conflict records with their sequences.
427    pub fn conflicts(&self) -> impl Iterator<Item = (u64, &ConflictRecord)> {
428        self.records.iter().filter_map(|record| match &record.body {
429            RecordBody::Conflict(conflict) => Some((record.seq, conflict)),
430            RecordBody::Intent(_) => None,
431        })
432    }
433
434    pub fn len(&self) -> usize {
435        self.records.len()
436    }
437
438    pub fn is_empty(&self) -> bool {
439        self.records.is_empty()
440    }
441}
442
443/// Process-global journal directory, set once at daemon startup by wiring
444/// that owns the deployment layout. The provisioning hooks look the journal
445/// up here so they do not need config plumbing threaded through the HTTP
446/// state in this slice.
447static GLOBAL_JOURNAL_DIR: OnceLock<PathBuf> = OnceLock::new();
448
449/// Install the process-global journal directory. Write-once; a second call
450/// fails rather than silently redirecting intents.
451pub fn set_global_journal_dir(dir: PathBuf) -> Result<(), JournalError> {
452    GLOBAL_JOURNAL_DIR
453        .set(dir)
454        .map_err(|_| JournalError::GlobalDirAlreadySet)
455}
456
457/// The process-global journal directory, if startup wiring installed one.
458pub fn global_journal_dir() -> Option<&'static Path> {
459    GLOBAL_JOURNAL_DIR.get().map(PathBuf::as_path)
460}
461
462/// In-process writer cache + serializer (review F1, CI follow-up): one
463/// `EnrollmentJournal` per directory per process, opened once under this
464/// mutex and reused for every append. This both serializes concurrent
465/// signup/login handlers and guarantees exactly ONE open file description
466/// holds the flock per process — open-per-call would cycle lock
467/// acquire/release on every intent and depends on drop-timing and on the
468/// filesystem's flock semantics (some shared/overlay mounts serialize OFD
469/// conflicts per-process, which spuriously fails a fresh open even after
470/// the previous instance dropped). Open-once is immune to both.
471static WRITERS: OnceLock<parking_lot::Mutex<HashMap<PathBuf, EnrollmentJournal>>> = OnceLock::new();
472
473fn writers() -> &'static parking_lot::Mutex<HashMap<PathBuf, EnrollmentJournal>> {
474    WRITERS.get_or_init(|| parking_lot::Mutex::new(HashMap::new()))
475}
476
477/// Convenience for the provisioning hooks: append one intent through the
478/// process-global cached writer for `dir`, serialized against every other
479/// in-process caller. The cached instance keeps its replay/conflict indexes
480/// in memory (no re-read per call); durability across restarts still comes
481/// from the journal file itself, re-validated on the first open.
482pub fn record_intent(dir: &Path, intent: EnrollmentIntent) -> Result<AppendOutcome, JournalError> {
483    use std::collections::hash_map::Entry;
484    let mut writers = writers().lock();
485    if !writers.contains_key(dir) {
486        writers.insert(dir.to_path_buf(), EnrollmentJournal::open(dir)?);
487    }
488    let journal = match writers.entry(dir.to_path_buf()) {
489        Entry::Occupied(entry) => entry.into_mut(),
490        Entry::Vacant(_) => unreachable!("inserted above when vacant"),
491    };
492    journal.append(intent)
493}
494
495/// Drop the cached writer for `dir`, releasing its flock. Used at shutdown
496/// and to hand the journal to another writer role (e.g. the reconciler
497/// opening the same directory after the OAuth writer is done). Returns true
498/// if a cached writer existed.
499pub fn close_cached_writer(dir: &Path) -> bool {
500    writers().lock().remove(dir).is_some()
501}
502
503/// fsync a directory (durability of directory entries: creates, renames).
504fn sync_dir(path: &Path) -> Result<(), JournalError> {
505    File::open(path)?.sync_all()?;
506    Ok(())
507}
508
509#[cfg(test)]
510#[allow(clippy::unwrap_used, clippy::expect_used)]
511mod tests {
512    use super::*;
513
514    fn intent(subject: &str, label: &str, epoch: u64, key: Option<&str>) -> EnrollmentIntent {
515        EnrollmentIntent {
516            subject: subject.to_owned(),
517            label: label.to_owned(),
518            provision_epoch: epoch,
519            idempotency_key: key.map(str::to_owned),
520        }
521    }
522
523    #[test]
524    fn append_commits_in_sequence_and_reopens() {
525        let tmp = tempfile::tempdir().unwrap();
526        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
527        assert_eq!(
528            journal
529                .append(intent(
530                    "did:web:a.example.com",
531                    "internal",
532                    1,
533                    Some("hosted:t1")
534                ))
535                .unwrap(),
536            AppendOutcome::Committed { seq: 0 }
537        );
538        assert_eq!(
539            journal
540                .append(intent("alice", "internal", 2, Some("jit:i\u{1f}s")))
541                .unwrap(),
542            AppendOutcome::Committed { seq: 1 }
543        );
544        assert_eq!(journal.len(), 2);
545
546        let expected = journal.records().to_vec();
547        drop(journal);
548        let reopened = EnrollmentJournal::open(tmp.path()).unwrap();
549        assert_eq!(reopened.records(), expected.as_slice());
550    }
551
552    #[test]
553    fn keyed_replay_is_idempotent_and_writes_nothing() {
554        let tmp = tempfile::tempdir().unwrap();
555        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
556        let first = intent("did:web:a.example.com", "internal", 1, Some("hosted:t1"));
557        assert_eq!(
558            journal.append(first.clone()).unwrap(),
559            AppendOutcome::Committed { seq: 0 }
560        );
561        assert_eq!(
562            journal.append(first).unwrap(),
563            AppendOutcome::Replay { seq: 0 }
564        );
565        assert_eq!(journal.len(), 1);
566        // Replay survives a restart: the durable record itself deduplicates.
567        drop(journal);
568        let mut reopened = EnrollmentJournal::open(tmp.path()).unwrap();
569        assert_eq!(
570            reopened
571                .append(intent(
572                    "did:web:a.example.com",
573                    "internal",
574                    1,
575                    Some("hosted:t1")
576                ))
577                .unwrap(),
578            AppendOutcome::Replay { seq: 0 }
579        );
580        assert_eq!(reopened.len(), 1);
581    }
582
583    #[test]
584    fn hosted_signup_intents_cover_both_token_profile_subjects() {
585        let intents =
586            hosted_signup_intents("did:web:alice.acct.example.com", "alice", Some("tx-1"), 7);
587        assert_eq!(intents.len(), 2);
588        assert_eq!(intents[0].subject, "did:web:alice.acct.example.com");
589        assert_eq!(intents[0].idempotency_key.as_deref(), Some("hosted:tx-1"));
590        assert_eq!(intents[1].subject, "alice");
591        assert_eq!(
592            intents[1].idempotency_key.as_deref(),
593            Some("hosted-local:tx-1")
594        );
595        for intent in &intents {
596            assert_eq!(intent.label, DEFAULT_ENROLLMENT_CLEARANCE);
597            assert_eq!(intent.provision_epoch, 7);
598        }
599        // Keyless operator mints stay keyless: the first append commits and a
600        // later keyless retry fails closed as a conflict, like any keyless
601        // duplicate.
602        let keyless = hosted_signup_intents("did:web:alice.acct.example.com", "alice", None, 7);
603        assert!(keyless.iter().all(|i| i.idempotency_key.is_none()));
604    }
605
606    #[test]
607    fn hosted_signup_intent_pair_journals_and_replays_together() {
608        let tmp = tempfile::tempdir().unwrap();
609        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
610        for intent in
611            hosted_signup_intents("did:web:alice.acct.example.com", "alice", Some("tx-1"), 7)
612        {
613            journal.append(intent).unwrap();
614        }
615        assert_eq!(journal.len(), 2);
616        // A transaction retry re-appends both intents; both replay and the
617        // journal gains nothing.
618        for intent in
619            hosted_signup_intents("did:web:alice.acct.example.com", "alice", Some("tx-1"), 8)
620        {
621            assert!(matches!(
622                journal.append(intent).unwrap(),
623                AppendOutcome::Replay { .. }
624            ));
625        }
626        assert_eq!(journal.len(), 2);
627    }
628
629    #[test]
630    fn key_reuse_with_different_payload_conflicts() {
631        let tmp = tempfile::tempdir().unwrap();
632        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
633        journal
634            .append(intent(
635                "did:web:a.example.com",
636                "internal",
637                1,
638                Some("hosted:t1"),
639            ))
640            .unwrap();
641        assert_eq!(
642            journal
643                .append(intent(
644                    "did:web:b.example.com",
645                    "internal",
646                    2,
647                    Some("hosted:t1")
648                ))
649                .unwrap(),
650            AppendOutcome::Conflict { seq: 1 }
651        );
652        let conflicts: Vec<_> = journal.conflicts().collect();
653        assert_eq!(conflicts.len(), 1);
654        assert_eq!(conflicts[0].1.reason, ConflictReason::KeyReuseMismatch);
655        // The original keyed intent still replays; the conflict did not
656        // poison the key.
657        assert_eq!(
658            journal
659                .append(intent(
660                    "did:web:a.example.com",
661                    "internal",
662                    1,
663                    Some("hosted:t1")
664                ))
665                .unwrap(),
666            AppendOutcome::Replay { seq: 0 }
667        );
668        // Conflicts are durable too.
669        drop(journal);
670        let reopened = EnrollmentJournal::open(tmp.path()).unwrap();
671        assert_eq!(reopened.conflicts().count(), 1);
672        assert_eq!(reopened.intents().count(), 1);
673    }
674
675    #[test]
676    fn subject_collision_under_a_different_key_conflicts() {
677        let tmp = tempfile::tempdir().unwrap();
678        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
679        journal
680            .append(intent(
681                "did:web:a.example.com",
682                "internal",
683                1,
684                Some("hosted:t1"),
685            ))
686            .unwrap();
687        assert_eq!(
688            journal
689                .append(intent(
690                    "did:web:a.example.com",
691                    "internal",
692                    2,
693                    Some("hosted:t2")
694                ))
695                .unwrap(),
696            AppendOutcome::Conflict { seq: 1 }
697        );
698        assert_eq!(
699            journal.conflicts().next().unwrap().1.reason,
700            ConflictReason::SubjectKeyCollision
701        );
702    }
703
704    #[test]
705    fn unkeyed_retry_of_known_subject_conflicts() {
706        let tmp = tempfile::tempdir().unwrap();
707        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
708        assert_eq!(
709            journal
710                .append(intent("did:web:a.example.com", "internal", 1, None))
711                .unwrap(),
712            AppendOutcome::Committed { seq: 0 }
713        );
714        // No token ⇒ cannot prove sameness ⇒ fail closed.
715        assert_eq!(
716            journal
717                .append(intent("did:web:a.example.com", "internal", 2, None))
718                .unwrap(),
719            AppendOutcome::Conflict { seq: 1 }
720        );
721        assert_eq!(
722            journal.conflicts().next().unwrap().1.reason,
723            ConflictReason::UnkeyedDuplicate
724        );
725    }
726
727    #[test]
728    fn durability_roundtrip_without_clean_shutdown() {
729        let tmp = tempfile::tempdir().unwrap();
730        {
731            let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
732            journal
733                .append(intent(
734                    "did:web:a.example.com",
735                    "internal",
736                    1,
737                    Some("hosted:t1"),
738                ))
739                .unwrap();
740            // No close/shutdown hook: append returning means the bytes and
741            // the directory entry survived an immediate drop.
742        }
743        let reopened = EnrollmentJournal::open(tmp.path()).unwrap();
744        let intents: Vec<_> = reopened.intents().collect();
745        assert_eq!(intents.len(), 1);
746        assert_eq!(intents[0].1.subject, "did:web:a.example.com");
747        assert_eq!(intents[0].1.provision_epoch, 1);
748    }
749
750    #[test]
751    fn iteration_api_yields_records_in_order_and_partitions_kinds() {
752        let tmp = tempfile::tempdir().unwrap();
753        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
754        journal
755            .append(intent("s1", "internal", 1, Some("k1")))
756            .unwrap();
757        journal
758            .append(intent("s2", "internal", 2, Some("k1")))
759            .unwrap(); // conflict
760        journal
761            .append(intent("s3", "confidential", 3, Some("k3")))
762            .unwrap();
763        let seqs: Vec<u64> = journal.iter().map(|r| r.seq).collect();
764        assert_eq!(seqs, vec![0, 1, 2]);
765        assert_eq!(journal.iter().len(), 3);
766        assert_eq!(journal.iter().next_back().unwrap().seq, 2);
767        let intent_subjects: Vec<&str> =
768            journal.intents().map(|(_, i)| i.subject.as_str()).collect();
769        assert_eq!(intent_subjects, vec!["s1", "s3"]);
770        assert!(!journal.is_empty());
771    }
772
773    #[test]
774    fn corrupt_journal_fails_closed_on_open() {
775        let tmp = tempfile::tempdir().unwrap();
776        std::fs::write(tmp.path().join(JOURNAL_FILE_NAME), b"not json\n").unwrap();
777        assert!(matches!(
778            EnrollmentJournal::open(tmp.path()),
779            Err(JournalError::Decode { seq: 0, .. })
780        ));
781    }
782
783    #[test]
784    fn sequence_gap_fails_closed_on_open() {
785        let tmp = tempfile::tempdir().unwrap();
786        let record = JournalRecord {
787            seq: 7,
788            body: RecordBody::Intent(intent("s", "internal", 1, None)),
789        };
790        let mut line = serde_json::to_vec(&record).unwrap();
791        line.push(b'\n');
792        std::fs::write(tmp.path().join(JOURNAL_FILE_NAME), line).unwrap();
793        assert!(matches!(
794            EnrollmentJournal::open(tmp.path()),
795            Err(JournalError::SequenceGap {
796                expected: 0,
797                found: 7
798            })
799        ));
800    }
801
802    #[test]
803    fn invalid_intents_are_rejected_before_any_write() {
804        let tmp = tempfile::tempdir().unwrap();
805        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
806        assert!(matches!(
807            journal.append(intent("", "internal", 1, None)),
808            Err(JournalError::EmptySubject)
809        ));
810        assert!(matches!(
811            journal.append(intent("s", "", 1, None)),
812            Err(JournalError::EmptyLabel)
813        ));
814        assert!(matches!(
815            journal.append(intent("s", "internal", 1, Some(""))),
816            Err(JournalError::EmptyIdempotencyKey)
817        ));
818        assert!(journal.is_empty());
819    }
820
821    #[test]
822    fn replay_ignores_provision_epoch() {
823        let tmp = tempfile::tempdir().unwrap();
824        let mut journal = EnrollmentJournal::open(tmp.path()).unwrap();
825        journal
826            .append(intent("alice", "internal", 100, Some("jit:i\u{1f}s")))
827            .unwrap();
828        // A self-healing retry observes a later epoch; the operation payload
829        // (subject, label) is identical, so this is a replay, not a conflict.
830        assert_eq!(
831            journal
832                .append(intent("alice", "internal", 200, Some("jit:i\u{1f}s")))
833                .unwrap(),
834            AppendOutcome::Replay { seq: 0 }
835        );
836        assert_eq!(journal.len(), 1);
837    }
838
839    #[test]
840    fn record_intent_convenience_opens_and_appends() {
841        let tmp = tempfile::tempdir().unwrap();
842        assert_eq!(
843            record_intent(
844                tmp.path(),
845                intent("did:web:a.example.com", "internal", 1, Some("hosted:t1")),
846            )
847            .unwrap(),
848            AppendOutcome::Committed { seq: 0 }
849        );
850        assert_eq!(
851            record_intent(
852                tmp.path(),
853                intent("did:web:a.example.com", "internal", 1, Some("hosted:t1")),
854            )
855            .unwrap(),
856            AppendOutcome::Replay { seq: 0 }
857        );
858    }
859
860    #[test]
861    fn concurrent_record_intent_calls_produce_gap_free_journal() {
862        // Review F1 regression: N concurrent callers (the concurrent
863        // signup/login handler shape) must serialize through the
864        // process-global mutex — every append commits a distinct seq and the
865        // reopened journal is gap-free with exactly N intents.
866        let tmp = tempfile::tempdir().unwrap();
867        let dir = tmp.path().to_path_buf();
868        const N: usize = 16;
869        let mut handles = Vec::new();
870        for i in 0..N {
871            let dir = dir.clone();
872            handles.push(std::thread::spawn(move || {
873                record_intent(
874                    &dir,
875                    intent(
876                        &format!("did:web:user{i}.example.com"),
877                        "internal",
878                        i as u64,
879                        Some(&format!("hosted:t{i}")),
880                    ),
881                )
882            }));
883        }
884        let mut seqs = Vec::new();
885        for handle in handles {
886            match handle.join().unwrap().unwrap() {
887                AppendOutcome::Committed { seq } => seqs.push(seq),
888                other => panic!("expected Committed, got {other:?}"),
889            }
890        }
891        seqs.sort_unstable();
892        assert_eq!(seqs, (0..N as u64).collect::<Vec<_>>());
893        // The cached writer still holds the flock; release it before the
894        // verification reopen (nextest runs each test in its own process,
895        // but the cache is per-process so this is required either way).
896        assert!(close_cached_writer(&dir));
897        let reopened = EnrollmentJournal::open(&dir).unwrap();
898        assert_eq!(reopened.intents().count(), N);
899        assert_eq!(reopened.len(), N);
900    }
901
902    #[test]
903    fn second_opener_fails_closed_while_writer_holds_lock() {
904        // Review F1 cross-process semantics: a second open — simulating a
905        // second daemon process sharing the journal directory — fails closed
906        // with Locked instead of interleaving appends.
907        let tmp = tempfile::tempdir().unwrap();
908        let first = EnrollmentJournal::open(tmp.path()).unwrap();
909        assert!(matches!(
910            EnrollmentJournal::open(tmp.path()),
911            Err(JournalError::Locked(_))
912        ));
913        drop(first);
914        // Lock is released with the instance; a later opener succeeds.
915        EnrollmentJournal::open(tmp.path()).unwrap();
916    }
917
918    #[test]
919    fn cached_record_intent_writer_holds_the_lock_until_closed() {
920        let tmp = tempfile::tempdir().unwrap();
921        record_intent(
922            tmp.path(),
923            intent("did:web:a.example.com", "internal", 1, Some("hosted:t1")),
924        )
925        .unwrap();
926        // The cached writer keeps one OFD holding the flock for the process
927        // lifetime: a direct second open fails closed...
928        assert!(matches!(
929            EnrollmentJournal::open(tmp.path()),
930            Err(JournalError::Locked(_))
931        ));
932        // ...until explicitly handed off.
933        assert!(close_cached_writer(tmp.path()));
934        assert!(!close_cached_writer(tmp.path()));
935        let journal = EnrollmentJournal::open(tmp.path()).unwrap();
936        assert_eq!(journal.intents().count(), 1);
937    }
938
939    #[test]
940    fn idempotency_keys_are_namespaced_and_unambiguous() {
941        assert_eq!(hosted_idempotency_key("t1"), "hosted:t1");
942        let key = jit_idempotency_key("https://issuer.example", "sub:1");
943        assert!(key.starts_with("jit:"));
944        assert_ne!(
945            jit_idempotency_key("ab", "c"),
946            jit_idempotency_key("a", "bc")
947        );
948    }
949}