Skip to main content

hyprstream_pds/
at9p_chain.rs

1//! B1: `did:at9p` update-record chain validation — the `successor-check` (#885).
2//!
3//! This module answers one question, purely and fail-closed: **given a
4//! predecessor state (the genesis capsule or a previously-validated
5//! update-record) and a candidate update-record, is the candidate an authorized
6//! successor?** It decides *which key is authorized to sign the rotation* and
7//! then enforces the four `successor-check` gates from design #879 §5.5/§7.1.
8//!
9//! # KERI-style pre-rotation (the trust model)
10//!
11//! `did:at9p` rotates keys the way KERI does: a capsule/record does not name the
12//! key that will be *allowed* to rotate it next — it commits to that key's
13//! **digest** (`next_key_commitments`, the pre-rotation commitment). A rotation
14//! is an [`UpdateRecord`] that *reveals* the now-current keys in its
15//! `new_capsule_body.subject_keys` and is signed by them; the successor-check
16//! proves those revealed keys are exactly the ones the predecessor pre-committed
17//! to. Because rotation authority lives in keys that were only ever published as
18//! a hash until used, theft of a *current* signing key does not grant the
19//! ability to rotate the identity (design §7.1, A11).
20//!
21//! # The four gates ([`validate_successor`])
22//!
23//! 1. **Signer authorization** — the update-record's signing key (one of the
24//!    revealed `new_capsule_body.subject_keys`, which is a published SET, not a
25//!    positional singleton — #1188 / #1183) must have its
26//!    [`HybridKeyPair::commitment_digest`] present in the predecessor's
27//!    `next_key_commitments`, and must actually have signed the record. This is
28//!    the key-selection decision B1 owns: it tries each pre-committed revealed
29//!    candidate and accepts the one that verifies, rather than trusting position
30//!    0 or a caller-supplied key.
31//! 2. **Linkage** — `prev_record_digest` equals the predecessor's record digest
32//!    (`H512` of its canonical bytes), chaining the segment back toward genesis.
33//! 3. **Monotonic epoch** — strictly increasing epoch.
34//! 4. **Freshness** — `now < expires_at`, with `now` supplied by the caller
35//!    (this module does no clock I/O — it is a pure function so tests and the
36//!    duplicity layer can drive time deterministically).
37//!
38//! Any violation fails closed with a typed [`SuccessorError`] naming the failed
39//! gate. Success returns the candidate's [`ChainState`], ready to serve as the
40//! predecessor for the next link.
41//!
42//! # What this is NOT: duplicity detection (B2, #886)
43//!
44//! The successor-check validates a candidate *against a single predecessor*. It
45//! deliberately does **not** implement duplicity/fork detection — a second,
46//! divergent *but individually valid* successor at an epoch the client has
47//! already accepted (design §7.2). That watermark comparison is B2's job, and
48//! this API is shaped to be wrapped by it: [`ChainState`] carries exactly the
49//! persistent `(epoch, record_digest)` pair B2 stores as its high-watermark, so
50//! B2 can compare a freshly [`validate_successor`]-accepted state against the
51//! persisted watermark and raise duplicity (hard fail + alarm) when a valid
52//! record diverges from the recorded digest at `epoch <= watermark`.
53
54use crate::at9p::{h512, Capsule, HybridKeyPair, UpdateRecord, H512_LEN};
55use crate::at9p_sign::verify_update_record;
56
57/// A validated point in an identity's key-rotation chain: either the genesis
58/// capsule ([`ChainState::genesis`]) or a successfully validated update-record
59/// (the return value of [`validate_successor`]).
60///
61/// It is simultaneously (a) the predecessor input to the next successor-check
62/// and (b) the persistent duplicity **watermark** the B2 layer (#886) stores:
63/// the `(epoch, record_digest)` pair plus the commitments needed to admit the
64/// next link.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct ChainState {
67    /// The genesis cid512 that names this identity. Constant across the whole
68    /// chain; every update-record must carry the same `subject_cid512`.
69    pub subject_cid512: String,
70    /// Epoch of this state. Genesis is epoch 0 by construction; the first
71    /// update-record must therefore carry epoch >= 1.
72    pub epoch: u64,
73    /// `H512` over the canonical bytes of the record this state represents — the
74    /// value the *next* update-record must echo in `prev_record_digest`, and the
75    /// digest half of the B2 watermark.
76    pub record_digest: [u8; H512_LEN],
77    /// The keys this state pre-commits to for the *next* rotation. Empty means a
78    /// declared-immutable identity (§7.1) — no update-record is ever a valid
79    /// successor.
80    pub next_key_commitments: Vec<[u8; H512_LEN]>,
81}
82
83impl ChainState {
84    /// Build the predecessor state for a genesis capsule.
85    ///
86    /// The caller is responsible for having verified the capsule's own
87    /// self-signature and its `H512(bytes) == cid512` gate first
88    /// (`verify_capsule`, GATE 1/2); this only projects the fields the
89    /// successor-check needs. The genesis record digest is `H512` of the
90    /// capsule's canonical bytes — the same digest embedded in its cid512 — so
91    /// the first update-record's `prev_record_digest` chains to it directly.
92    pub fn genesis(capsule: &Capsule) -> anyhow::Result<Self> {
93        Ok(Self {
94            subject_cid512: capsule.cid512()?,
95            epoch: 0,
96            record_digest: h512(&capsule.to_dag_cbor()?),
97            next_key_commitments: capsule.body.next_key_commitments.clone(),
98        })
99    }
100
101    /// Project the predecessor state of an **already-validated** update-record —
102    /// e.g. reconstructing the watermark from a persisted record on startup.
103    /// For validating a fresh candidate, prefer [`validate_successor`], which
104    /// returns this state only after all gates pass.
105    pub fn from_validated_update(record: &UpdateRecord) -> Self {
106        Self {
107            subject_cid512: record.subject_cid512.clone(),
108            epoch: record.epoch,
109            // Already validated by contract; use the unchecked serializer so
110            // this infallible projector stays infallible (a record that
111            // reached here came from `from_dag_cbor` or the signing path).
112            record_digest: h512(&record.encode_value()),
113            next_key_commitments: record.new_capsule_body.next_key_commitments.clone(),
114        }
115    }
116}
117
118/// A typed successor-check failure. Every variant names the gate that failed;
119/// callers (and the B2 duplicity layer) can match on the specific reason.
120#[derive(Debug)]
121#[non_exhaustive]
122pub enum SuccessorError {
123    /// The candidate names a different identity than the predecessor
124    /// (`subject_cid512` mismatch) — it is not part of this chain at all.
125    SubjectMismatch { expected: String, found: String },
126    /// The predecessor pre-committed to no next keys: a declared-immutable
127    /// identity (§7.1). Its chain is frozen at its current epoch and no
128    /// update-record is ever a valid successor.
129    ///
130    /// The richer immutable-identity semantics are owned by B3 (#887); this is
131    /// only the fail-closed boundary the successor-check enforces.
132    ImmutableIdentity,
133    /// Epoch did not strictly increase over the predecessor.
134    NonMonotonicEpoch { predecessor: u64, candidate: u64 },
135    /// `prev_record_digest` does not match the predecessor's record digest — the
136    /// segment does not chain back to the accepted history.
137    BrokenLinkage,
138    /// The revealed signing key's commitment digest is absent from the
139    /// predecessor's `next_key_commitments`: the key was never pre-rotated, so
140    /// it is not authorized to rotate this identity.
141    SignerNotCommitted,
142    /// The pinned-Hybrid composite signature did not verify under the authorizing
143    /// (pre-committed) key.
144    SignatureInvalid(anyhow::Error),
145    /// `now >= expires_at`: the record is stale (freshness gate, §7.2). `now` is
146    /// caller-supplied.
147    Expired { now: String, expires_at: String },
148    /// The candidate record or a supplied timestamp was structurally malformed;
149    /// fail-closed rather than guess.
150    Malformed(anyhow::Error),
151}
152
153impl std::fmt::Display for SuccessorError {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        match self {
156            Self::SubjectMismatch { expected, found } => write!(
157                f,
158                "successor-check failed [subject]: update names {found:?}, predecessor is {expected:?}"
159            ),
160            Self::ImmutableIdentity => write!(
161                f,
162                "successor-check failed [signer]: predecessor is a declared-immutable identity (empty next_key_commitments); no successor is valid"
163            ),
164            Self::NonMonotonicEpoch {
165                predecessor,
166                candidate,
167            } => write!(
168                f,
169                "successor-check failed [epoch]: candidate epoch {candidate} does not strictly exceed predecessor epoch {predecessor}"
170            ),
171            Self::BrokenLinkage => write!(
172                f,
173                "successor-check failed [linkage]: prev_record_digest does not match the predecessor's record digest"
174            ),
175            Self::SignerNotCommitted => write!(
176                f,
177                "successor-check failed [signer]: signing key was not pre-committed in the predecessor's next_key_commitments"
178            ),
179            Self::SignatureInvalid(err) => {
180                write!(f, "successor-check failed [signature]: {err}")
181            }
182            Self::Expired { now, expires_at } => write!(
183                f,
184                "successor-check failed [freshness]: now {now:?} is not before expires_at {expires_at:?}"
185            ),
186            Self::Malformed(err) => write!(f, "successor-check failed [malformed]: {err}"),
187        }
188    }
189}
190
191impl std::error::Error for SuccessorError {
192    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
193        match self {
194            Self::SignatureInvalid(err) | Self::Malformed(err) => Some(err.as_ref()),
195            _ => None,
196        }
197    }
198}
199
200/// Validate that `candidate` is an authorized successor of `predecessor` as of
201/// `now`, enforcing every `successor-check` gate (design #879 §5.5) fail-closed.
202///
203/// `now` is an ISO-8601 UTC (`Z`-terminated) instant supplied by the caller;
204/// this function performs no clock I/O so it stays pure and deterministic.
205///
206/// On success returns the candidate's [`ChainState`] — feed it back as the
207/// `predecessor` for the next link, and (for the B2 duplicity layer, #886)
208/// persist its `(epoch, record_digest)` as the identity's high-watermark.
209pub fn validate_successor(
210    predecessor: &ChainState,
211    candidate: &UpdateRecord,
212    now: &str,
213) -> Result<ChainState, SuccessorError> {
214    // Structural schema gates first: a malformed candidate is rejected before any
215    // trust decision (fail-closed). `new_capsule_body.validate()` also guarantees
216    // `subject_keys` is non-empty, which the signer selection below relies on.
217    candidate
218        .new_capsule_body
219        .validate()
220        .map_err(SuccessorError::Malformed)?;
221
222    // Gate 0 (identity binding): the update must be for the same DID. The
223    // subject_cid512 names the genesis capsule and is invariant across the chain.
224    if candidate.subject_cid512 != predecessor.subject_cid512 {
225        return Err(SuccessorError::SubjectMismatch {
226            expected: predecessor.subject_cid512.clone(),
227            found: candidate.subject_cid512.clone(),
228        });
229    }
230
231    // A declared-immutable identity (empty commitments) has no valid successor.
232    if predecessor.next_key_commitments.is_empty() {
233        return Err(SuccessorError::ImmutableIdentity);
234    }
235
236    // Gate 3 (monotonic epoch): strictly increasing. Checked before the crypto so
237    // a stale/replayed record is rejected cheaply. Also pins a valid record to its
238    // position in the chain — a record valid at a later epoch does not validate
239    // against an earlier predecessor.
240    if candidate.epoch <= predecessor.epoch {
241        return Err(SuccessorError::NonMonotonicEpoch {
242            predecessor: predecessor.epoch,
243            candidate: candidate.epoch,
244        });
245    }
246
247    // Gate 2 (linkage): chain the segment back to the predecessor's record.
248    if candidate.prev_record_digest != predecessor.record_digest {
249        return Err(SuccessorError::BrokenLinkage);
250    }
251
252    // Gate 1 (signer authorization + signature): the rotation reveals its
253    // now-current keys in `new_capsule_body.subject_keys` — a published SET, not
254    // an ordered list with a positional "primary" (#1188 / #1183). The
255    // authorizing signer is whichever revealed key was BOTH pre-committed by the
256    // predecessor (its `commitment_digest` present in `next_key_commitments`) AND
257    // actually signed this record. B1 selects that key by trying each pre-rotation
258    // candidate rather than trusting position 0 or any caller input.
259    //
260    // This is the same discipline the durable rule (#1183) prescribes for a
261    // published key set with no wire-level selector: try each compatible
262    // candidate, accept the one that verifies, never let position confer
263    // authority. A predecessor may pre-commit to several next keys (hybrid /
264    // overlap), and the successor set may publish several; exactly one of them
265    // signs, and that one must have been pre-committed.
266    let precommitted: Vec<&HybridKeyPair> = candidate
267        .new_capsule_body
268        .subject_keys
269        .iter()
270        .filter(|key| {
271            let digest = key.commitment_digest();
272            predecessor
273                .next_key_commitments
274                .iter()
275                .any(|commitment| commitment == &digest)
276        })
277        .collect();
278    if precommitted.is_empty() {
279        // No revealed subject key was pre-rotated: none is authorized to rotate
280        // this identity, regardless of whether the signature is otherwise valid.
281        return Err(SuccessorError::SignerNotCommitted);
282    }
283
284    // Gate 1 (signature): a pre-committed key must actually have signed the
285    // record. Pinned-Hybrid (EdDSA + ML-DSA-65) verification (#939); done last as
286    // the most expensive check. Try each authorized candidate and accept the
287    // first whose composite verifies — set-selection by "which published key
288    // signed", not by index. If none verifies, the record was not signed by any
289    // authorized (pre-committed) key.
290    let mut last_err = None;
291    let signed = precommitted
292        .iter()
293        .any(|signer| match verify_update_record(candidate, signer) {
294            Ok(()) => true,
295            Err(e) => {
296                last_err = Some(e);
297                false
298            }
299        });
300    if !signed {
301        return Err(SuccessorError::SignatureInvalid(last_err.unwrap_or_else(
302            || anyhow::anyhow!("no pre-committed subject key verified the update record"),
303        )));
304    }
305
306    // Gate 4 (freshness): now < expires_at.
307    if !datetime_before(now, &candidate.expires_at).map_err(SuccessorError::Malformed)? {
308        return Err(SuccessorError::Expired {
309            now: now.to_owned(),
310            expires_at: candidate.expires_at.clone(),
311        });
312    }
313
314    Ok(ChainState::from_validated_update(candidate))
315}
316
317/// Total ordering of two ISO-8601 UTC (`Z`-terminated) instants: returns
318/// `Ok(true)` iff `a` is strictly before `b`. Pure integer parse — no clock, no
319/// external date crate. Malformed input is an error (fail-closed), never a
320/// silent `false`.
321pub(crate) fn datetime_before(a: &str, b: &str) -> anyhow::Result<bool> {
322    Ok(datetime_nanos(a)? < datetime_nanos(b)?)
323}
324
325/// Parse a `YYYY-MM-DDTHH:MM:SS[.fraction]Z` UTC instant into nanoseconds since
326/// the Unix epoch, as an `i128` sort key. Fractional seconds are optional and
327/// compared to nanosecond precision.
328fn datetime_nanos(s: &str) -> anyhow::Result<i128> {
329    let b = s.as_bytes();
330    anyhow::ensure!(
331        s.len() >= 20 && s.ends_with('Z'),
332        "datetime must be ISO-8601 UTC ending in 'Z': {s:?}"
333    );
334    anyhow::ensure!(
335        b.get(4) == Some(&b'-')
336            && b.get(7) == Some(&b'-')
337            && b.get(10) == Some(&b'T')
338            && b.get(13) == Some(&b':')
339            && b.get(16) == Some(&b':'),
340        "datetime has malformed field separators: {s:?}"
341    );
342
343    let year: i64 = parse_int_field(s, 0..4, "year")?;
344    let month: i64 = parse_int_field(s, 5..7, "month")?;
345    let day: i64 = parse_int_field(s, 8..10, "day")?;
346    let hour: i64 = parse_int_field(s, 11..13, "hour")?;
347    let minute: i64 = parse_int_field(s, 14..16, "minute")?;
348    let second: i64 = parse_int_field(s, 17..19, "second")?;
349
350    anyhow::ensure!((1..=12).contains(&month), "month out of range: {s:?}");
351    anyhow::ensure!((1..=31).contains(&day), "day out of range: {s:?}");
352    anyhow::ensure!((0..=23).contains(&hour), "hour out of range: {s:?}");
353    anyhow::ensure!((0..=59).contains(&minute), "minute out of range: {s:?}");
354    // Allow a leap second (60) so real timestamps are not rejected.
355    anyhow::ensure!((0..=60).contains(&second), "second out of range: {s:?}");
356
357    // Fractional seconds live between index 19 and the trailing 'Z'.
358    let tail = &s[19..s.len() - 1];
359    let nanos_frac: i128 = if tail.is_empty() {
360        0
361    } else {
362        anyhow::ensure!(
363            tail.starts_with('.') && tail.len() > 1,
364            "datetime fractional part must be a non-empty '.digits': {s:?}"
365        );
366        let mut digits = tail[1..].to_owned();
367        anyhow::ensure!(
368            digits.bytes().all(|d| d.is_ascii_digit()),
369            "datetime fractional part must be digits: {s:?}"
370        );
371        // Normalize to exactly 9 fractional digits (nanoseconds).
372        digits.truncate(9);
373        while digits.len() < 9 {
374            digits.push('0');
375        }
376        digits
377            .parse::<i128>()
378            .map_err(|e| anyhow::anyhow!("bad fractional seconds in {s:?}: {e}"))?
379    };
380
381    let days = days_from_civil(year, month, day);
382    let secs = days
383        .checked_mul(86_400)
384        .and_then(|d| d.checked_add(hour * 3_600 + minute * 60 + second))
385        .ok_or_else(|| anyhow::anyhow!("datetime overflow: {s:?}"))?;
386    Ok(i128::from(secs) * 1_000_000_000 + nanos_frac)
387}
388
389fn parse_int_field(s: &str, range: std::ops::Range<usize>, field: &str) -> anyhow::Result<i64> {
390    let slice = s
391        .get(range)
392        .ok_or_else(|| anyhow::anyhow!("datetime missing {field} field: {s:?}"))?;
393    anyhow::ensure!(
394        slice.bytes().all(|d| d.is_ascii_digit()),
395        "datetime {field} field is not numeric: {s:?}"
396    );
397    slice
398        .parse::<i64>()
399        .map_err(|e| anyhow::anyhow!("datetime {field} parse error in {s:?}: {e}"))
400}
401
402/// Days from the Unix epoch (1970-01-01) for a proleptic-Gregorian date, via
403/// Howard Hinnant's `days_from_civil` algorithm. Valid for all `month` in
404/// `1..=12` and `day` in `1..=31`.
405fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
406    let y = if m <= 2 { y - 1 } else { y };
407    let era = if y >= 0 { y } else { y - 399 } / 400;
408    let yoe = y - era * 400;
409    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
410    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
411    era * 146_097 + doe - 719_468
412}
413
414#[cfg(test)]
415#[allow(
416    clippy::unwrap_used,
417    clippy::expect_used,
418    clippy::indexing_slicing,
419    clippy::panic
420)]
421mod tests {
422    use super::*;
423    use crate::at9p::{
424        CapsuleBody, ServiceEndpoint, ServiceEntry, ServiceType, Transport, H512_LEN,
425    };
426    use crate::at9p_sign::{sign_capsule, sign_update_record};
427    use ed25519_dalek::SigningKey;
428    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
429    use rand::rngs::OsRng;
430
431    const FUTURE: &str = "2099-01-01T00:00:00Z";
432
433    /// A hybrid signer plus its public keypair (the pre-rotation commitment
434    /// preimage).
435    struct Signer {
436        ed_sk: SigningKey,
437        pq_sk: MlDsaSigningKey,
438        keypair: HybridKeyPair,
439    }
440
441    fn signer() -> Signer {
442        let ed_sk = SigningKey::generate(&mut OsRng);
443        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
444        let keypair = HybridKeyPair::new(
445            ed_sk.verifying_key().to_bytes().to_vec(),
446            ml_dsa_vk_bytes(&pq_vk),
447        )
448        .unwrap();
449        Signer {
450            ed_sk,
451            pq_sk,
452            keypair,
453        }
454    }
455
456    fn service_entries() -> Vec<ServiceEntry> {
457        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node0").unwrap();
458        vec![ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap()]
459    }
460
461    /// Build a capsule body whose primary subject key is `subject` and which
462    /// pre-commits to each key in `next`.
463    fn body_committing_to(subject: &Signer, next: &[&Signer]) -> CapsuleBody {
464        let mut body = CapsuleBody::new(vec![subject.keypair.clone()], service_entries()).unwrap();
465        body.next_key_commitments = next.iter().map(|s| s.keypair.commitment_digest()).collect();
466        body
467    }
468
469    /// Genesis: subject key `g`, pre-committing to `n1`.
470    fn genesis(g: &Signer, n1: &Signer) -> (Capsule, ChainState) {
471        let body = body_committing_to(g, &[n1]);
472        let capsule = sign_capsule(body, &g.ed_sk, &g.pq_sk).unwrap();
473        let state = ChainState::genesis(&capsule).unwrap();
474        (capsule, state)
475    }
476
477    /// Build an update-record signed by `signer_key`, revealing `signer_key` as
478    /// the new primary subject key and pre-committing to `next`.
479    fn update(
480        subject_cid512: &str,
481        epoch: u64,
482        prev_digest: [u8; H512_LEN],
483        signer_key: &Signer,
484        next: &[&Signer],
485        expires_at: &str,
486    ) -> UpdateRecord {
487        let body = body_committing_to(signer_key, next);
488        sign_update_record(
489            subject_cid512.to_owned(),
490            epoch,
491            prev_digest,
492            body,
493            expires_at.to_owned(),
494            &signer_key.ed_sk,
495            &signer_key.pq_sk,
496        )
497        .unwrap()
498    }
499
500    #[test]
501    fn valid_successor_accepted() {
502        let (g, n1, n2) = (signer(), signer(), signer());
503        let (_cap, gen_state) = genesis(&g, &n1);
504        let rec = update(
505            &gen_state.subject_cid512,
506            1,
507            gen_state.record_digest,
508            &n1,
509            &[&n2],
510            FUTURE,
511        );
512        let next_state = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z")
513            .expect("valid successor must be accepted");
514        assert_eq!(next_state.epoch, 1);
515        assert_eq!(next_state.record_digest, h512(&rec.to_dag_cbor().unwrap()));
516        assert_eq!(next_state.subject_cid512, gen_state.subject_cid512);
517    }
518
519    #[test]
520    fn multi_step_chain_extends() {
521        let (g, n1, n2, n3) = (signer(), signer(), signer(), signer());
522        let (_cap, s0) = genesis(&g, &n1);
523        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2], FUTURE);
524        let s1 = validate_successor(&s0, &r1, "2026-07-09T00:00:00Z").unwrap();
525        let r2 = update(&s1.subject_cid512, 2, s1.record_digest, &n2, &[&n3], FUTURE);
526        let s2 = validate_successor(&s1, &r2, "2026-07-09T00:00:00Z")
527            .expect("second link must validate against the first");
528        assert_eq!(s2.epoch, 2);
529    }
530
531    #[test]
532    fn signer_not_committed_rejected() {
533        let (g, n1, evil) = (signer(), signer(), signer());
534        let (_cap, gen_state) = genesis(&g, &n1);
535        // `evil` was never pre-committed; it signs and reveals itself.
536        let rec = update(
537            &gen_state.subject_cid512,
538            1,
539            gen_state.record_digest,
540            &evil,
541            &[&n1],
542            FUTURE,
543        );
544        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
545        assert!(
546            matches!(err, SuccessorError::SignerNotCommitted),
547            "expected SignerNotCommitted, got {err:?}"
548        );
549    }
550
551    #[test]
552    fn broken_linkage_rejected() {
553        let (g, n1, n2) = (signer(), signer(), signer());
554        let (_cap, gen_state) = genesis(&g, &n1);
555        // Sign over a WRONG prev digest so the signature is valid but linkage fails.
556        let rec = update(
557            &gen_state.subject_cid512,
558            1,
559            [0xAAu8; H512_LEN],
560            &n1,
561            &[&n2],
562            FUTURE,
563        );
564        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
565        assert!(
566            matches!(err, SuccessorError::BrokenLinkage),
567            "expected BrokenLinkage, got {err:?}"
568        );
569    }
570
571    #[test]
572    fn non_increasing_epoch_rejected() {
573        let (g, n1, n2) = (signer(), signer(), signer());
574        let (_cap, gen_state) = genesis(&g, &n1);
575        // Epoch 0 == genesis epoch → not strictly increasing.
576        let rec = update(
577            &gen_state.subject_cid512,
578            0,
579            gen_state.record_digest,
580            &n1,
581            &[&n2],
582            FUTURE,
583        );
584        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
585        assert!(
586            matches!(err, SuccessorError::NonMonotonicEpoch { .. }),
587            "expected NonMonotonicEpoch, got {err:?}"
588        );
589    }
590
591    #[test]
592    fn expired_record_rejected() {
593        let (g, n1, n2) = (signer(), signer(), signer());
594        let (_cap, gen_state) = genesis(&g, &n1);
595        let rec = update(
596            &gen_state.subject_cid512,
597            1,
598            gen_state.record_digest,
599            &n1,
600            &[&n2],
601            "2020-01-01T00:00:00Z",
602        );
603        // now is AFTER expires_at.
604        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
605        assert!(
606            matches!(err, SuccessorError::Expired { .. }),
607            "expected Expired, got {err:?}"
608        );
609    }
610
611    /// A record that is individually valid at its own position (epoch 2, chaining
612    /// through r1) is rejected when checked against the WRONG predecessor
613    /// (genesis): the pre-rotation binding ties a valid record to one epoch/link.
614    #[test]
615    fn valid_record_rejected_at_wrong_epoch() {
616        let (g, n1, n2, n3) = (signer(), signer(), signer(), signer());
617        let (_cap, s0) = genesis(&g, &n1);
618        let r1 = update(&s0.subject_cid512, 1, s0.record_digest, &n1, &[&n2], FUTURE);
619        let s1 = validate_successor(&s0, &r1, "2026-07-09T00:00:00Z").unwrap();
620        // r2 is a perfectly valid successor of s1...
621        let r2 = update(&s1.subject_cid512, 2, s1.record_digest, &n2, &[&n3], FUTURE);
622        validate_successor(&s1, &r2, "2026-07-09T00:00:00Z").expect("r2 valid against s1");
623        // ...but not against genesis: its epoch 2 chains through r1, not genesis,
624        // and its signer (n2) was never committed by genesis. First failing gate
625        // here is linkage.
626        let err = validate_successor(&s0, &r2, "2026-07-09T00:00:00Z").unwrap_err();
627        assert!(
628            matches!(err, SuccessorError::BrokenLinkage),
629            "expected BrokenLinkage against wrong predecessor, got {err:?}"
630        );
631    }
632
633    /// B3 (#887) boundary: an identity that pre-committed to no next keys is
634    /// declared-immutable — even an otherwise well-formed, correctly-signed
635    /// update is rejected.
636    #[test]
637    fn immutable_identity_has_no_successor() {
638        let (g, n1) = (signer(), signer());
639        // Genesis with EMPTY next_key_commitments.
640        let body = CapsuleBody::new(vec![g.keypair.clone()], service_entries()).unwrap();
641        assert!(body.next_key_commitments.is_empty());
642        let capsule = sign_capsule(body, &g.ed_sk, &g.pq_sk).unwrap();
643        let gen_state = ChainState::genesis(&capsule).unwrap();
644        let rec = update(
645            &gen_state.subject_cid512,
646            1,
647            gen_state.record_digest,
648            &n1,
649            &[&n1],
650            FUTURE,
651        );
652        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
653        assert!(
654            matches!(err, SuccessorError::ImmutableIdentity),
655            "expected ImmutableIdentity, got {err:?}"
656        );
657    }
658
659    #[test]
660    fn subject_mismatch_rejected() {
661        let (g, n1, n2) = (signer(), signer(), signer());
662        let (_cap, gen_state) = genesis(&g, &n1);
663        // A totally different identity's genesis.
664        let (other_g, other_n1) = (signer(), signer());
665        let (_oc, other_state) = genesis(&other_g, &other_n1);
666        let rec = update(
667            &other_state.subject_cid512,
668            1,
669            gen_state.record_digest,
670            &n1,
671            &[&n2],
672            FUTURE,
673        );
674        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
675        assert!(
676            matches!(err, SuccessorError::SubjectMismatch { .. }),
677            "expected SubjectMismatch, got {err:?}"
678        );
679    }
680
681    #[test]
682    fn datetime_before_orders_correctly() {
683        assert!(datetime_before("2026-07-09T00:00:00Z", "2026-07-09T00:00:01Z").unwrap());
684        assert!(!datetime_before("2026-07-09T00:00:01Z", "2026-07-09T00:00:00Z").unwrap());
685        // Equal instant is NOT strictly before (freshness requires now < expires).
686        assert!(!datetime_before("2026-07-09T00:00:00Z", "2026-07-09T00:00:00Z").unwrap());
687        // Across a year/month/day boundary.
688        assert!(datetime_before("2025-12-31T23:59:59Z", "2026-01-01T00:00:00Z").unwrap());
689        // Fractional seconds honored.
690        assert!(datetime_before("2026-07-09T00:00:00.100Z", "2026-07-09T00:00:00.200Z").unwrap());
691        // Malformed input fails closed (Err, never a silent false).
692        assert!(datetime_before("not-a-date", FUTURE).is_err());
693    }
694
695    #[test]
696    fn tampered_signature_rejected() {
697        let (g, n1, n2) = (signer(), signer(), signer());
698        let (_cap, gen_state) = genesis(&g, &n1);
699        let mut rec = update(
700            &gen_state.subject_cid512,
701            1,
702            gen_state.record_digest,
703            &n1,
704            &[&n2],
705            FUTURE,
706        );
707        // Flip a byte in the Ed25519 signature: still schema-valid, crypto-invalid.
708        rec.signatures.ed25519_signature[0] ^= 0x01;
709        let err = validate_successor(&gen_state, &rec, "2026-07-09T00:00:00Z").unwrap_err();
710        assert!(
711            matches!(err, SuccessorError::SignatureInvalid(_)),
712            "expected SignatureInvalid, got {err:?}"
713        );
714    }
715
716    // ── #1188 / #1183: subject_keys is a published SET, not a positional
717    //    singleton. These tests FAIL against the pre-fix `subject_keys.first()`
718    //    signer selection. ────────────────────────────────────────────────────
719
720    /// Build an update whose `new_capsule_body.subject_keys` publishes EVERY key
721    /// in `revealed` (a set — overlap/hybrid), signed by `signer_key` (which must
722    /// be one of `revealed`), and pre-committing to `next`.
723    fn update_revealing_set(
724        subject_cid512: &str,
725        epoch: u64,
726        prev_digest: [u8; H512_LEN],
727        revealed: &[&Signer],
728        signer_key: &Signer,
729        next: &[&Signer],
730        expires_at: &str,
731    ) -> UpdateRecord {
732        let mut body = CapsuleBody::new(
733            revealed.iter().map(|s| s.keypair.clone()).collect(),
734            service_entries(),
735        )
736        .unwrap();
737        body.next_key_commitments = next.iter().map(|s| s.keypair.commitment_digest()).collect();
738        sign_update_record(
739            subject_cid512.to_owned(),
740            epoch,
741            prev_digest,
742            body,
743            expires_at.to_owned(),
744            &signer_key.ed_sk,
745            &signer_key.pq_sk,
746        )
747        .unwrap()
748    }
749
750    /// Overlap rotation: the predecessor pre-commits to TWO next keys, and the
751    /// successor publishes BOTH as subject_keys but is signed by the SECOND
752    /// (non-position-0) one. The set-semantics successor-check must accept it by
753    /// trying each pre-committed candidate. The pre-fix code, which only ever
754    /// verified `subject_keys.first()`, rejects this as SignatureInvalid (the
755    /// first key did not sign).
756    #[test]
757    fn overlap_successor_signed_by_non_first_committed_key_accepted() {
758        let (g, n1, n2) = (signer(), signer(), signer());
759        // Genesis pre-commits to BOTH n1 and n2 (overlap: either may rotate).
760        let body = body_committing_to(&g, &[&n1, &n2]);
761        let capsule = sign_capsule(body, &g.ed_sk, &g.pq_sk).unwrap();
762        let s0 = ChainState::genesis(&capsule).unwrap();
763
764        // The successor publishes both n1 and n2 (n1 listed FIRST) but is signed
765        // by n2 — the second, non-positional key.
766        let (n3,) = (signer(),);
767        let rec = update_revealing_set(
768            &s0.subject_cid512,
769            1,
770            s0.record_digest,
771            &[&n1, &n2],
772            &n2,
773            &[&n3],
774            FUTURE,
775        );
776        let s1 = validate_successor(&s0, &rec, "2026-07-09T00:00:00Z")
777            .expect("a successor signed by any pre-committed published key must be accepted");
778        assert_eq!(s1.epoch, 1);
779    }
780
781    /// The dual guard: publishing a key in the set does NOT confer authority if
782    /// it was never pre-committed. Two shapes, both must be rejected:
783    ///
784    /// - set `[evil]` signed by `evil` (no committed key revealed at all) →
785    ///   `SignerNotCommitted`;
786    /// - set `[n1, evil]` signed by `evil` (a committed key `n1` is revealed but
787    ///   did not sign; `evil` signed but is uncommitted) → rejected. `n1` is
788    ///   tried and fails to verify, so the variant is `SignatureInvalid` — the
789    ///   record is still fail-closed, which is the property under test.
790    ///
791    /// Set semantics widens *which committed* key may sign, never admits an
792    /// uncommitted one.
793    #[test]
794    fn overlap_successor_signed_by_uncommitted_set_member_rejected() {
795        let (g, n1, evil) = (signer(), signer(), signer());
796        // Genesis pre-commits ONLY to n1.
797        let (_cap, s0) = genesis(&g, &n1);
798        let (n3,) = (signer(),);
799
800        // Shape 1: only the uncommitted `evil` is revealed and signs.
801        let rec_only_evil = update_revealing_set(
802            &s0.subject_cid512,
803            1,
804            s0.record_digest,
805            &[&evil],
806            &evil,
807            &[&n3],
808            FUTURE,
809        );
810        let err = validate_successor(&s0, &rec_only_evil, "2026-07-09T00:00:00Z").unwrap_err();
811        assert!(
812            matches!(err, SuccessorError::SignerNotCommitted),
813            "an uncommitted-only set must fail SignerNotCommitted, got {err:?}"
814        );
815
816        // Shape 2: committed `n1` is revealed but `evil` (uncommitted) signs.
817        let rec_mixed = update_revealing_set(
818            &s0.subject_cid512,
819            1,
820            s0.record_digest,
821            &[&n1, &evil],
822            &evil,
823            &[&n3],
824            FUTURE,
825        );
826        let err = validate_successor(&s0, &rec_mixed, "2026-07-09T00:00:00Z").unwrap_err();
827        assert!(
828            matches!(
829                err,
830                SuccessorError::SignatureInvalid(_) | SuccessorError::SignerNotCommitted
831            ),
832            "a rotation signed by an uncommitted set member must fail closed, got {err:?}"
833        );
834    }
835
836    /// Bounded retirement: a rotation is valid within its window and REJECTED
837    /// after it (freshness gate, §7.2). This is the "retired key rejected after
838    /// its bounded window" leg of the overlap test — the retired successor's
839    /// record has a bounded `expires_at`, and a `now` past it fails closed.
840    #[test]
841    fn overlap_retired_after_bounded_window_rejected() {
842        let (g, n1, n2) = (signer(), signer(), signer());
843        let body = body_committing_to(&g, &[&n1, &n2]);
844        let capsule = sign_capsule(body, &g.ed_sk, &g.pq_sk).unwrap();
845        let s0 = ChainState::genesis(&capsule).unwrap();
846
847        let (n3,) = (signer(),);
848        let bounded = "2026-07-10T00:00:00Z";
849        let rec = update_revealing_set(
850            &s0.subject_cid512,
851            1,
852            s0.record_digest,
853            &[&n1, &n2],
854            &n2,
855            &[&n3],
856            bounded,
857        );
858        // Inside the window: accepted.
859        validate_successor(&s0, &rec, "2026-07-09T00:00:00Z")
860            .expect("accepted inside the bounded window");
861        // After the window: the same record is rejected (retired).
862        let err = validate_successor(&s0, &rec, "2026-07-11T00:00:00Z").unwrap_err();
863        assert!(
864            matches!(err, SuccessorError::Expired { .. }),
865            "a rotation past its bounded window must be rejected, got {err:?}"
866        );
867    }
868}